@rdlabo/ionic-angular-kit 21.6.6 → 21.6.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.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rdlabo-ionic-angular-kit-offline.mjs","sources":["../../../projects/kit/offline/src/lib/offline-replica-schema.ts","../../../projects/kit/offline/src/lib/offline-identity.ts","../../../projects/kit/offline/src/lib/offline-aggregate-intent-projector.ts","../../../projects/kit/offline/src/lib/offline-replica-puller.ts","../../../projects/kit/offline/src/lib/offline-command-hooks.ts","../../../projects/kit/offline/src/lib/offline-kit-options.ts","../../../projects/kit/offline/src/lib/offline-command-executor.ts","../../../projects/kit/offline/src/lib/offline-repository-concurrency.ts","../../../projects/kit/offline/src/lib/offline-repository.ts","../../../projects/kit/offline/src/lib/offline-replica-mutation-coordinator.ts","../../../projects/kit/offline/src/lib/offline-replica-pull.service.ts","../../../projects/kit/offline/src/lib/offline-network.service.ts","../../../projects/kit/offline/src/lib/offline-mutation-admission.service.ts","../../../projects/kit/offline/src/lib/offline-sync.service.ts","../../../projects/kit/offline/src/lib/offline-mutation-persistence.service.ts","../../../projects/kit/offline/src/lib/offline-session.service.ts","../../../projects/kit/offline/src/lib/offline-storage.ts","../../../projects/kit/offline/src/lib/offline-coordinator.service.ts","../../../projects/kit/offline/src/lib/offline-auth-bridge.ts","../../../projects/kit/offline/src/lib/offline-community-sqlite-config.ts","../../../projects/kit/offline/src/lib/offline-local-reset.ts","../../../projects/kit/offline/src/lib/offline-mutation-envelope.ts","../../../projects/kit/offline/src/lib/offline-request-policy.ts","../../../projects/kit/offline/src/lib/sqlite-offline-repository.ts","../../../projects/kit/offline/src/lib/offline-provider.ts","../../../projects/kit/offline/src/lib/offline.interceptor.ts","../../../projects/kit/offline/src/public-api.ts","../../../projects/kit/offline/src/rdlabo-ionic-angular-kit-offline.ts"],"sourcesContent":["/** SQLite storage affinity for a replicated entity column. */\nexport type OfflineReplicaSqliteAffinity = 'TEXT' | 'INTEGER' | 'REAL';\n\n/**\n * Logical storage kind for a replicated column, independent of SQLite affinity.\n *\n * For example, {@link booleanColumn} and {@link datetime} both use INTEGER/TEXT affinity\n * but remain distinguishable at runtime through this marker.\n */\nexport type OfflineReplicaStorageKind = 'text' | 'integer' | 'real' | 'booleanColumn' | 'json' | 'datetime';\n\n/** Scope partition persisted on every replica table row. */\nexport type OfflineReplicaEntityScope = 'user' | 'partition';\n\n/** Field projection policy for a source-model property. */\nexport type OfflineReplicaFieldPolicy = 'column' | 'remoteId' | 'ignored';\n\n/** Canonical value types accepted in a composite server-side natural key. */\nexport type OfflineNaturalKeyValue = string | number;\nconst MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES = 1024;\n\n/** Ordered natural-key values keyed by source-model field name. */\nexport type OfflineNaturalKey = Readonly<Record<string, OfflineNaturalKeyValue>>;\n\n/** Server-assigned remote identifier for a generated-identity entity. */\nexport type OfflineGeneratedRemoteId = number | string;\n\n/** Remote row identity. Exactly one variant is valid for a replicated entity. */\nexport type OfflineReplicaRemoteIdentity =\n | { readonly remoteId: OfflineGeneratedRemoteId; readonly naturalKey?: never }\n | { readonly remoteId?: never; readonly naturalKey: OfflineNaturalKey };\n\n/** Runtime identity policy materialized into an entity schema. */\nexport type OfflineReplicaIdentityDescriptor =\n | { readonly kind: 'localOnly'; readonly sourceKeys: readonly [] }\n | { readonly kind: 'generated'; readonly sourceKeys: readonly [string]; readonly affinity: OfflineReplicaSqliteAffinity }\n | { readonly kind: 'naturalKey'; readonly sourceKeys: readonly string[] };\n\n/** Runtime descriptor for one mapped source property. */\nexport interface OfflineReplicaFieldDescriptor {\n /** Source-model property name from the select shape. */\n readonly sourceKey: string;\n /** How the property is projected into SQLite. */\n readonly policy: OfflineReplicaFieldPolicy;\n /** Physical SQLite column name, or null when {@link policy} is `ignored`. */\n readonly sqliteColumnName: string | null;\n /** SQLite affinity for column policies, otherwise null. */\n readonly affinity: OfflineReplicaSqliteAffinity | null;\n /** Logical storage kind for column policies, otherwise null. */\n readonly storageKind: OfflineReplicaStorageKind | null;\n /** Whether the SQLite column accepts NULL. */\n readonly nullable: boolean;\n /** Human-readable reason when {@link policy} is `ignored`. */\n readonly ignoredReason: string | null;\n}\n\n/** Materialized replica entity schema used to create and fingerprint SQLite tables. */\nexport interface OfflineReplicaEntitySchema<TSelect extends Record<string, unknown>> {\n /** Validated SQLite table name. */\n readonly tableName: string;\n /** Stable source key used by sync and repository layers. */\n readonly sourceKey: string;\n /** Whether rows are partitioned by user only or user plus scope partition. */\n readonly scope: OfflineReplicaEntityScope;\n /** Remote identity policy used by repository and pull reconciliation. */\n readonly identity: OfflineReplicaIdentityDescriptor;\n /** Ordered field descriptors derived from the DSL definition. */\n readonly fields: readonly OfflineReplicaFieldDescriptor[];\n /** Deterministic DDL statements for the replica table and indexes. */\n readonly createTableSql: readonly string[];\n /** Canonical string input for schema fingerprinting; hashing is left to callers. */\n readonly schemaFingerprintInput: string;\n /** Phantom marker tying the schema to its select shape. */\n readonly __select?: TSelect;\n}\n\ndeclare const replicaNullableBrand: unique symbol;\n\n/** Phantom nullability brand carried by column builders. */\ninterface ReplicaNullableBrand {\n readonly [replicaNullableBrand]: 'nullable' | 'required';\n}\n\n/** Column builder definition with compile-time nullability tracking. */\nexport interface OfflineReplicaColumnDef<\n TValue = unknown,\n TNullable extends ReplicaNullableBrand = { readonly [replicaNullableBrand]: 'required' },\n> {\n readonly kind: 'column';\n readonly affinity: OfflineReplicaSqliteAffinity;\n readonly storageKind: OfflineReplicaStorageKind;\n readonly columnName?: string;\n readonly nullable?: boolean;\n readonly __types?: { readonly value: TValue; readonly nullable: TNullable[typeof replicaNullableBrand] };\n}\n\n/** Builder marking a source property as the server-assigned generated identifier. */\nexport interface OfflineReplicaRemoteIdDef<TAffinity extends OfflineReplicaSqliteAffinity = OfflineReplicaSqliteAffinity> {\n readonly kind: 'remoteId';\n readonly affinity: TAffinity;\n readonly __types?: TAffinity extends 'INTEGER' ? { readonly value: number } : { readonly value: string };\n}\n\n/** Builder excluding a source property from SQLite projection. */\nexport interface OfflineReplicaIgnoredDef {\n readonly kind: 'ignored';\n readonly reason: string;\n}\n\n/** Builder selecting non-null source columns as a composite remote identity. */\nexport interface OfflineReplicaNaturalKeyDef<TKey extends string = string> {\n readonly kind: 'naturalKey';\n readonly sourceKeys: readonly TKey[];\n}\n\n/** Explicit identity for a projection that is never synchronized to a remote row. */\nexport interface OfflineReplicaLocalOnlyDef {\n readonly kind: 'localOnly';\n}\n\ntype OfflineReplicaFieldDef = OfflineReplicaColumnDef | OfflineReplicaRemoteIdDef | OfflineReplicaIgnoredDef;\n\ntype StripNullish<T> = Exclude<T, null | undefined>;\n\ntype NormalizeReplicaColumnValue<T> = T extends string\n ? string\n : T extends number\n ? number\n : T extends boolean\n ? boolean\n : T extends Date\n ? string | Date\n : T;\n\ntype StrictNullChecksEnabled = undefined extends null ? false : true;\n\ntype ReplicaColumnNullabilityForSelect<T> = StrictNullChecksEnabled extends true\n ? null extends T\n ? ReplicaNullableBrand & { readonly [replicaNullableBrand]: 'nullable' }\n : undefined extends T\n ? ReplicaNullableBrand & { readonly [replicaNullableBrand]: 'nullable' }\n : ReplicaNullableBrand & { readonly [replicaNullableBrand]: 'required' }\n : ReplicaNullableBrand;\n\ntype OfflineReplicaColumnDefForValue<T> = OfflineReplicaColumnDef<\n NormalizeReplicaColumnValue<StripNullish<T>>,\n ReplicaColumnNullabilityForSelect<T>\n>;\n\ntype OfflineReplicaRemoteIdDefForValue<T> =\n StripNullish<T> extends number\n ? OfflineReplicaRemoteIdDef<'INTEGER'>\n : StripNullish<T> extends string\n ? OfflineReplicaRemoteIdDef<'TEXT'>\n : never;\n\ntype OfflineReplicaFieldDefForKey<TSelect extends Record<string, unknown>, K extends keyof TSelect> =\n | OfflineReplicaRemoteIdDefForValue<TSelect[K]>\n | OfflineReplicaIgnoredDef\n | OfflineReplicaColumnDefForValue<TSelect[K]>;\n\ntype ExactSelectKeys<TSelect extends Record<string, unknown>, TFields> =\n Exclude<keyof TFields, keyof TSelect> extends never ? (Exclude<keyof TSelect, keyof TFields> extends never ? TFields : never) : never;\n\n/** Configuration accepted by {@link defineReplicaEntity}. */\nexport interface OfflineReplicaEntityDefinition<\n TSelect extends Record<string, unknown>,\n TFields extends { readonly [K in keyof TSelect]: OfflineReplicaFieldDefForKey<TSelect, K> },\n> {\n readonly table: string;\n readonly sourceKey: string;\n readonly scope: OfflineReplicaEntityScope;\n readonly identity?: OfflineReplicaNaturalKeyDef<Extract<keyof TSelect, string>> | OfflineReplicaLocalOnlyDef;\n readonly fields: ExactSelectKeys<TSelect, TFields> & TFields;\n}\n\nconst IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/;\nconst RESERVED_COLUMN_NAMES = new Set([\n 'local_id',\n '_offline_user_id',\n '_offline_scope_id',\n 'server_id',\n '_offline_confirmed_json',\n '_offline_server_revision_json',\n '_offline_sync_state',\n '_offline_fetched_at',\n]);\n\n/**\n * Begins a type-safe replica entity schema definition for the given select shape.\n *\n * Every key in `TSelect` must appear exactly once in `fields`, and column nullability\n * must match the select property nullability. An entity may map at most one field with\n * {@link generatedId}; omit it for local-only projections that have no remote row identity.\n */\nexport function defineReplicaEntity<TSelect extends Record<string, unknown>>() {\n return function defineReplicaEntityConfig<\n const TFields extends { readonly [K in keyof TSelect]: OfflineReplicaFieldDefForKey<TSelect, K> },\n >(definition: OfflineReplicaEntityDefinition<TSelect, TFields>): OfflineReplicaEntitySchema<TSelect> {\n return buildOfflineReplicaEntitySchema<TSelect>({\n table: definition.table,\n sourceKey: definition.sourceKey,\n scope: definition.scope,\n identity: definition.identity,\n fields: definition.fields as Record<string, OfflineReplicaFieldDef>,\n });\n };\n}\n\nfunction requiredColumn<TValue>(\n affinity: OfflineReplicaSqliteAffinity,\n storageKind: OfflineReplicaStorageKind,\n): OfflineReplicaColumnDef<TValue> {\n return { kind: 'column', affinity, storageKind, nullable: false };\n}\n\n/** Maps a non-null string source property to a TEXT column. */\nexport function text(): OfflineReplicaColumnDef<string> {\n return requiredColumn<string>('TEXT', 'text');\n}\n\n/** Maps a non-null integer source property to an INTEGER column. */\nexport function integer(): OfflineReplicaColumnDef<number> {\n return requiredColumn<number>('INTEGER', 'integer');\n}\n\n/** Maps a non-null floating-point source property to a REAL column. */\nexport function real(): OfflineReplicaColumnDef<number> {\n return requiredColumn<number>('REAL', 'real');\n}\n\n/** Maps a non-null boolean source property to an INTEGER column. */\nexport function booleanColumn(): OfflineReplicaColumnDef<boolean> {\n return requiredColumn<boolean>('INTEGER', 'booleanColumn');\n}\n\n/** Maps a non-null JSON-serializable source property to a TEXT column. */\nexport function json<T>(): OfflineReplicaColumnDef<T> {\n return requiredColumn<T>('TEXT', 'json');\n}\n\n/** Maps a non-null datetime source property to a canonical ISO-8601 TEXT column. */\nexport function datetime(): OfflineReplicaColumnDef<string | Date> {\n return requiredColumn<string | Date>('TEXT', 'datetime');\n}\n\n/** Marks a column builder as nullable for nullable select properties. */\nexport function nullable<TValue>(\n column: OfflineReplicaColumnDef<TValue, { readonly [replicaNullableBrand]: 'required' }>,\n): OfflineReplicaColumnDef<TValue, { readonly [replicaNullableBrand]: 'nullable' }> {\n return {\n kind: 'column',\n affinity: column.affinity,\n storageKind: column.storageKind,\n nullable: true,\n ...(column.columnName !== undefined ? { columnName: column.columnName } : {}),\n };\n}\n\n/** Maps a source property to the nullable generated remote-id column. */\nexport function generatedId(kind: 'integer'): OfflineReplicaRemoteIdDef<'INTEGER'>;\nexport function generatedId(kind: 'text'): OfflineReplicaRemoteIdDef<'TEXT'>;\nexport function generatedId(kind: 'integer' | 'text'): OfflineReplicaRemoteIdDef {\n return { kind: 'remoteId', affinity: kind === 'integer' ? 'INTEGER' : 'TEXT' };\n}\n\n/** Declares an ordered remote natural key used directly as the scoped SQLite primary key. */\nexport function naturalKey<const TKey extends string>(sourceKeys: readonly TKey[]): OfflineReplicaNaturalKeyDef<TKey> {\n return { kind: 'naturalKey', sourceKeys };\n}\n\n/** Declares a projection with a local UUID address and no Outbox identity. */\nexport function localOnly(): OfflineReplicaLocalOnlyDef {\n return { kind: 'localOnly' };\n}\n/** Rejects a generated remote id on a local-only or natural-key projection before it reaches platform storage. */\nexport function assertOfflineReplicaGeneratedRemoteId(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n value: OfflineGeneratedRemoteId | null,\n): void {\n if (schema.identity.kind !== 'generated' && value !== null) {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" does not define a generated remote id field.`);\n }\n if (value === null) return;\n assertValidGeneratedRemoteId(schema, value);\n}\n\n/** Extracts and validates an entity's natural key in declared component order. */\nexport function offlineNaturalKeyFromValues(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n values: unknown,\n): OfflineNaturalKey | null {\n if (schema.identity.kind !== 'naturalKey') return null;\n if (!isPlainObject(values)) {\n throw new Error(`Offline replica values for \"${schema.sourceKey}\" must be a plain object.`);\n }\n return Object.fromEntries(\n schema.identity.sourceKeys.map((sourceKey) => {\n const value = values[sourceKey];\n const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKey)!;\n if (\n (field.storageKind === 'text' && typeof value !== 'string') ||\n (field.storageKind === 'integer' && (typeof value !== 'number' || !Number.isSafeInteger(value) || !Number.isFinite(value)))\n ) {\n throw new Error(`Offline replica naturalKey field \"${sourceKey}\" has an invalid value.`);\n }\n if (typeof value === 'string') assertNaturalKeyText(sourceKey, value);\n return [sourceKey, value as OfflineNaturalKeyValue];\n }),\n );\n}\n\n/** Validates a supplied natural key and returns it in schema-declared order. */\nexport function normalizeOfflineNaturalKey(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n naturalKey: OfflineNaturalKey,\n): OfflineNaturalKey {\n if (schema.identity.kind !== 'naturalKey') {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" does not define a naturalKey identity.`);\n }\n if (!isPlainObject(naturalKey)) {\n throw new Error(`Offline replica naturalKey for \"${schema.sourceKey}\" must be a plain object.`);\n }\n const actualKeys = Object.keys(naturalKey);\n if (\n actualKeys.length !== schema.identity.sourceKeys.length ||\n actualKeys.some((key) => !(schema.identity.sourceKeys as readonly string[]).includes(key))\n ) {\n throw new Error(`Offline replica naturalKey for \"${schema.sourceKey}\" must contain exactly its declared fields.`);\n }\n return offlineNaturalKeyFromValues(schema, naturalKey)!;\n}\n\n/** Stable, type-tagged identity key used by web uniqueness and pull collapse. */\nexport function canonicalOfflineRemoteIdentity(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n identity: OfflineReplicaRemoteIdentity,\n): string {\n if (schema.identity.kind === 'generated') {\n if (!('remoteId' in identity) || 'naturalKey' in identity) {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" requires generated remote id identity.`);\n }\n assertValidGeneratedRemoteId(schema, identity.remoteId);\n return typeof identity.remoteId === 'string' ? `remoteId:s:${identity.remoteId}` : `remoteId:n:${identity.remoteId}`;\n }\n if (schema.identity.kind === 'naturalKey') {\n if (!('naturalKey' in identity) || 'remoteId' in identity) {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" requires naturalKey identity.`);\n }\n const key = normalizeOfflineNaturalKey(schema, identity.naturalKey);\n return `naturalKey:${JSON.stringify(\n schema.identity.sourceKeys.map((sourceKey) => {\n const value = key[sourceKey]!;\n return [sourceKey, typeof value === 'number' ? 'n' : 's', value];\n }),\n )}`;\n }\n throw new Error(`Offline replica source \"${schema.sourceKey}\" is local-only.`);\n}\n\n/** Enforces one immutable natural identity across optimistic and confirmed row values. */\nexport function assertOfflineReplicaNaturalKeyBaseline(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n values: unknown,\n confirmedValues: unknown | null,\n): void {\n if (schema.identity.kind !== 'naturalKey' || confirmedValues === null) return;\n const current = canonicalOfflineRemoteIdentity(schema, { naturalKey: offlineNaturalKeyFromValues(schema, values)! });\n const confirmed = canonicalOfflineRemoteIdentity(schema, {\n naturalKey: offlineNaturalKeyFromValues(schema, confirmedValues)!,\n });\n if (current !== confirmed) {\n throw new Error(`Offline replica confirmedValues naturalKey must match values for \"${schema.sourceKey}\".`);\n }\n}\n\nfunction assertValidGeneratedRemoteId(schema: OfflineReplicaEntitySchema<Record<string, unknown>>, value: OfflineGeneratedRemoteId): void {\n if (schema.identity.kind !== 'generated') {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" does not define a generated remote id field.`);\n }\n if (schema.identity.affinity === 'INTEGER') {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {\n throw new Error('Offline replica generated remote id must be a positive integer.');\n }\n return;\n }\n if (typeof value !== 'string' || value.length === 0) {\n throw new Error('Offline replica generated remote id must be a non-empty string.');\n }\n assertNaturalKeyText('remoteId', value);\n}\n\nfunction assertNaturalKeyText(sourceKey: string, value: string): void {\n if (value.includes('\\0')) {\n throw new Error(`Offline replica naturalKey field \"${sourceKey}\" must not contain NUL.`);\n }\n if (/[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(^|[^\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/u.test(value)) {\n throw new Error(`Offline replica naturalKey field \"${sourceKey}\" must contain well-formed Unicode.`);\n }\n if (new TextEncoder().encode(value).byteLength > MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES) {\n throw new Error(`Offline replica naturalKey field \"${sourceKey}\" must not exceed ${MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES} UTF-8 bytes.`);\n }\n}\n\n/** Excludes a source property from SQLite while retaining it in the select shape. */\nexport function ignored(reason: string): OfflineReplicaIgnoredDef {\n return { kind: 'ignored', reason };\n}\n\nfunction buildOfflineReplicaEntitySchema<TSelect extends Record<string, unknown>>(definition: {\n readonly table: string;\n readonly sourceKey: string;\n readonly scope: OfflineReplicaEntityScope;\n readonly identity?: OfflineReplicaNaturalKeyDef | OfflineReplicaLocalOnlyDef;\n readonly fields: Record<string, OfflineReplicaFieldDef>;\n}): OfflineReplicaEntitySchema<TSelect> {\n validateIdentifier(definition.table, 'table');\n validateIdentifier(definition.sourceKey, 'source key');\n\n const sourceKeys = Object.keys(definition.fields).sort();\n const remoteIdCount = sourceKeys.filter((sourceKey) => definition.fields[sourceKey]?.kind === 'remoteId').length;\n if (remoteIdCount > 1) throw new Error('Replica entity must define at most one remoteId field.');\n const fields: OfflineReplicaFieldDescriptor[] = sourceKeys.map((sourceKey) => {\n const fieldDef = definition.fields[sourceKey as keyof TSelect] as OfflineReplicaFieldDef;\n return materializeFieldDescriptor(sourceKey, fieldDef);\n });\n const identity = materializeIdentity(definition.identity, fields);\n\n const createTableSql = buildCreateTableSql(definition.table, definition.scope, fields, identity);\n const schemaFingerprintInput = buildSchemaFingerprintInput(definition.table, definition.sourceKey, definition.scope, fields, identity);\n\n return {\n tableName: definition.table,\n sourceKey: definition.sourceKey,\n scope: definition.scope,\n identity,\n fields,\n createTableSql,\n schemaFingerprintInput,\n };\n}\n\nfunction materializeIdentity(\n definition: OfflineReplicaNaturalKeyDef | OfflineReplicaLocalOnlyDef | undefined,\n fields: readonly OfflineReplicaFieldDescriptor[],\n): OfflineReplicaIdentityDescriptor {\n const serverField = fields.find((field) => field.policy === 'remoteId');\n if (definition && serverField) throw new Error('Replica entity cannot combine a generated id field with another identity.');\n if (serverField) return { kind: 'generated', sourceKeys: [serverField.sourceKey], affinity: serverField.affinity! };\n if (!definition) throw new Error('Replica entity without a generated id field must declare identity explicitly.');\n if (definition.kind === 'localOnly') return { kind: 'localOnly', sourceKeys: [] };\n if (definition.sourceKeys.length === 0) throw new Error('Replica naturalKey must contain at least one source field.');\n if (new Set(definition.sourceKeys).size !== definition.sourceKeys.length) {\n throw new Error('Replica naturalKey source fields must be unique.');\n }\n for (const sourceKey of definition.sourceKeys) {\n const field = fields.find((candidate) => candidate.sourceKey === sourceKey);\n if (!field) throw new Error(`Replica naturalKey field \"${sourceKey}\" is not defined.`);\n if (field.policy !== 'column' || field.nullable || !['text', 'integer'].includes(field.storageKind ?? '')) {\n throw new Error(`Replica naturalKey field \"${sourceKey}\" must be a required text or integer column.`);\n }\n }\n return { kind: 'naturalKey', sourceKeys: [...definition.sourceKeys] };\n}\n\nfunction materializeFieldDescriptor(sourceKey: string, fieldDef: OfflineReplicaFieldDef): OfflineReplicaFieldDescriptor {\n if (fieldDef.kind === 'ignored') {\n if (!fieldDef.reason.trim()) throw new Error(`Replica ignored field \"${sourceKey}\" requires a reason.`);\n return {\n sourceKey,\n policy: 'ignored',\n sqliteColumnName: null,\n affinity: null,\n storageKind: null,\n nullable: false,\n ignoredReason: fieldDef.reason,\n };\n }\n\n if (fieldDef.kind === 'remoteId') {\n return {\n sourceKey,\n policy: 'remoteId',\n sqliteColumnName: 'server_id',\n affinity: fieldDef.affinity,\n storageKind: null,\n nullable: true,\n ignoredReason: null,\n };\n }\n\n const sqliteColumnName = fieldDef.columnName ?? toSnakeCase(sourceKey);\n validateIdentifier(sqliteColumnName, 'column');\n if (RESERVED_COLUMN_NAMES.has(sqliteColumnName)) {\n throw new Error(`Replica column \"${sqliteColumnName}\" is reserved.`);\n }\n\n return {\n sourceKey,\n policy: 'column',\n sqliteColumnName,\n affinity: fieldDef.affinity,\n storageKind: fieldDef.storageKind,\n nullable: fieldDef.nullable === true,\n ignoredReason: null,\n };\n}\n\nfunction buildCreateTableSql(\n tableName: string,\n scope: OfflineReplicaEntityScope,\n fields: readonly OfflineReplicaFieldDescriptor[],\n identity: OfflineReplicaIdentityDescriptor,\n): readonly string[] {\n const columnLines = ['_offline_user_id TEXT NOT NULL'];\n if (scope === 'partition') {\n columnLines.push('_offline_scope_id TEXT NOT NULL');\n }\n if (identity.kind === 'generated') {\n columnLines.push('local_id TEXT NOT NULL', `server_id ${identity.affinity}`);\n } else if (identity.kind === 'localOnly') {\n columnLines.push('local_id TEXT NOT NULL');\n }\n columnLines.push(\n '_offline_confirmed_json TEXT',\n '_offline_server_revision_json TEXT',\n '_offline_sync_state TEXT NOT NULL',\n \"_offline_visibility TEXT NOT NULL DEFAULT 'present'\",\n '_offline_fetched_at INTEGER NOT NULL',\n );\n\n for (const field of fields) {\n if (field.policy !== 'column') {\n continue;\n }\n const nullability = field.nullable ? '' : ' NOT NULL';\n columnLines.push(`${field.sqliteColumnName} ${field.affinity}${nullability}`);\n }\n\n const pkColumns = [\n '_offline_user_id',\n ...(scope === 'partition' ? ['_offline_scope_id'] : []),\n ...(identity.kind === 'naturalKey'\n ? identity.sourceKeys.map((sourceKey) => fields.find((field) => field.sourceKey === sourceKey)!.sqliteColumnName!)\n : ['local_id']),\n ];\n\n const statements = [\n `CREATE TABLE IF NOT EXISTS ${tableName} (\\n ${columnLines.join(',\\n ')},\\n PRIMARY KEY (${pkColumns.join(', ')})\\n)`,\n ];\n\n if (identity.kind === 'generated') {\n const indexColumns = scope === 'partition' ? '_offline_user_id, _offline_scope_id, server_id' : '_offline_user_id, server_id';\n statements.push(\n `CREATE UNIQUE INDEX IF NOT EXISTS uq_${tableName}_server_id ON ${tableName} (${indexColumns}) WHERE server_id IS NOT NULL`,\n );\n }\n\n return statements;\n}\n\nfunction buildSchemaFingerprintInput(\n tableName: string,\n sourceKey: string,\n scope: OfflineReplicaEntityScope,\n fields: readonly OfflineReplicaFieldDescriptor[],\n identity: OfflineReplicaIdentityDescriptor,\n): string {\n const fieldParts = fields.map((field) => {\n if (field.policy === 'ignored') {\n return `${field.sourceKey}:ignored:${field.ignoredReason ?? ''}`;\n }\n if (field.policy === 'remoteId') {\n return `${field.sourceKey}:remoteId:server_id:${field.affinity}:nullable`;\n }\n return `${field.sourceKey}:column:${field.sqliteColumnName}:${field.affinity}:${field.storageKind}:${field.nullable ? 'nullable' : 'required'}`;\n });\n\n return [\n `table=${tableName}`,\n `source=${sourceKey}`,\n `scope=${scope}`,\n ...(identity.kind === 'naturalKey'\n ? [`identity=naturalKey:${identity.sourceKeys.join(',')}`, 'identityCodec=v2']\n : identity.kind === 'generated'\n ? [`identity=generated:${identity.sourceKeys[0]}:${identity.affinity}`, 'identityCodec=v2']\n : ['identity=localOnly', 'identityCodec=v2']),\n `fields=${fieldParts.join(';')}`,\n ].join('|');\n}\n\nfunction validateIdentifier(value: string, kind: 'table' | 'column' | 'source key'): void {\n if (!IDENTIFIER_PATTERN.test(value)) {\n throw new Error(`Replica ${kind} \"${value}\" must match ${IDENTIFIER_PATTERN.source}.`);\n }\n}\n\nfunction toSnakeCase(value: string): string {\n return value\n .replace(/([A-Z])/g, '_$1')\n .replace(/^_/, '')\n .toLowerCase();\n}\n\n/**\n * Validates and encodes a source-model row into SQLite-bound column values.\n *\n * Only {@link OfflineReplicaFieldPolicy} `column` fields are emitted, keyed by\n * {@link OfflineReplicaFieldDescriptor.sqliteColumnName} in descriptor order.\n * Source properties mapped as `remoteId` or `ignored` may be present but are not encoded.\n */\nexport function encodeOfflineReplicaValues(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n values: unknown,\n): Readonly<Record<string, string | number | null>> {\n if (!isPlainObject(values)) {\n throw new Error('Replica row values must be a plain object.');\n }\n\n const sourceValues = values;\n const allowedSourceKeys = new Set(schema.fields.map((field) => field.sourceKey));\n\n for (const sourceKey of Object.keys(sourceValues)) {\n if (!allowedSourceKeys.has(sourceKey)) {\n throw new Error(`Replica row contains unknown source key \"${sourceKey}\".`);\n }\n }\n\n const encoded: Record<string, string | number | null> = {};\n\n for (const field of schema.fields) {\n if (field.policy !== 'column') {\n continue;\n }\n\n const sqliteColumnName = field.sqliteColumnName;\n if (sqliteColumnName === null) {\n continue;\n }\n\n if (!Object.prototype.hasOwnProperty.call(sourceValues, field.sourceKey)) {\n throw new Error(`Replica row is missing required source key \"${field.sourceKey}\".`);\n }\n\n const rawValue = sourceValues[field.sourceKey];\n if (rawValue === null) {\n if (!field.nullable) {\n throw new Error(`Replica row source key \"${field.sourceKey}\" must not be null.`);\n }\n encoded[sqliteColumnName] = null;\n continue;\n }\n\n if (rawValue === undefined) {\n throw new Error(`Replica row source key \"${field.sourceKey}\" must not be undefined.`);\n }\n\n encoded[sqliteColumnName] = encodeReplicaColumnValue(field, rawValue);\n }\n\n return encoded;\n}\n\n/**\n * Validates and decodes SQLite column values into a source-model row.\n *\n * Only {@link OfflineReplicaFieldPolicy} `column` fields are emitted, keyed by\n * {@link OfflineReplicaFieldDescriptor.sourceKey} in descriptor order.\n * Physical columns such as `server_id`, sync metadata, and scope keys may be\n * present in `row` but are not decoded.\n */\nexport function decodeOfflineReplicaValues(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n row: unknown,\n): Readonly<Record<string, unknown>> {\n if (!isPlainObject(row)) {\n throw new Error('Replica SQLite row must be a plain object.');\n }\n\n const decoded: Record<string, unknown> = {};\n\n for (const field of schema.fields) {\n if (field.policy !== 'column') {\n continue;\n }\n\n const sqliteColumnName = field.sqliteColumnName;\n if (sqliteColumnName === null) {\n continue;\n }\n\n if (!Object.prototype.hasOwnProperty.call(row, sqliteColumnName)) {\n throw new Error(`Replica SQLite row is missing required column \"${sqliteColumnName}\".`);\n }\n\n const rawValue = row[sqliteColumnName];\n if (rawValue === null) {\n if (!field.nullable) {\n throw new Error(`Replica SQLite column \"${sqliteColumnName}\" must not be null.`);\n }\n decoded[field.sourceKey] = null;\n continue;\n }\n\n if (rawValue === undefined) {\n throw new Error(`Replica SQLite column \"${sqliteColumnName}\" must not be undefined.`);\n }\n\n decoded[field.sourceKey] = decodeReplicaColumnValue(field, rawValue);\n }\n\n return decoded;\n}\n\n/**\n * Validates a source-model row and returns the canonical domain projection persisted by every repository.\n *\n * Fields mapped as `remoteId` or `ignored` are intentionally omitted. This keeps web and native row shapes\n * identical; the server identifier remains available through the replica row's dedicated `remoteId` field.\n */\nexport function projectOfflineReplicaValues(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n values: unknown,\n): Readonly<Record<string, unknown>> {\n return decodeOfflineReplicaValues(schema, encodeOfflineReplicaValues(schema, values));\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction encodeReplicaColumnValue(field: OfflineReplicaFieldDescriptor, value: unknown): string | number {\n switch (field.storageKind) {\n case 'text':\n return encodeReplicaTextValue(field.sourceKey, value);\n case 'integer':\n return encodeReplicaIntegerValue(field.sourceKey, value);\n case 'real':\n return encodeReplicaRealValue(field.sourceKey, value);\n case 'booleanColumn':\n return encodeReplicaBooleanValue(field.sourceKey, value);\n case 'json':\n return encodeReplicaJsonValue(field.sourceKey, value);\n case 'datetime':\n return encodeReplicaDatetimeValue(field.sourceKey, value);\n default:\n throw new Error(`Replica row source key \"${field.sourceKey}\" has no storage kind.`);\n }\n}\n\nfunction decodeReplicaColumnValue(field: OfflineReplicaFieldDescriptor, value: unknown): unknown {\n switch (field.storageKind) {\n case 'text':\n return decodeReplicaTextValue(field.sourceKey, value);\n case 'integer':\n return decodeReplicaIntegerValue(field.sourceKey, value);\n case 'real':\n return decodeReplicaRealValue(field.sourceKey, value);\n case 'booleanColumn':\n return decodeReplicaBooleanValue(field.sourceKey, value);\n case 'json':\n return decodeReplicaJsonValue(field.sourceKey, value);\n case 'datetime':\n return decodeReplicaDatetimeValue(field.sourceKey, value);\n default:\n throw new Error(`Replica row source key \"${field.sourceKey}\" has no storage kind.`);\n }\n}\n\nfunction encodeReplicaTextValue(sourceKey: string, value: unknown): string {\n if (typeof value !== 'string') {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a string.`);\n }\n return value;\n}\n\nfunction encodeReplicaIntegerValue(sourceKey: string, value: unknown): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isSafeInteger(value)) {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a finite safe integer.`);\n }\n return value;\n}\n\nfunction encodeReplicaRealValue(sourceKey: string, value: unknown): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a finite number.`);\n }\n return value;\n}\n\nfunction encodeReplicaBooleanValue(sourceKey: string, value: unknown): 0 | 1 {\n if (typeof value !== 'boolean') {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a boolean.`);\n }\n return value ? 1 : 0;\n}\n\nfunction encodeReplicaJsonValue(sourceKey: string, value: unknown): string {\n assertJsonSerializable(sourceKey, value);\n return JSON.stringify(value);\n}\n\nfunction encodeReplicaDatetimeValue(sourceKey: string, value: unknown): string {\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a valid Date.`);\n }\n return value.toISOString();\n }\n\n if (typeof value === 'string') {\n return value;\n }\n\n throw new Error(`Replica row source key \"${sourceKey}\" must be a Date or string.`);\n}\n\nfunction decodeReplicaTextValue(sourceKey: string, value: unknown): string {\n if (typeof value !== 'string') {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a string.`);\n }\n return value;\n}\n\nfunction decodeReplicaIntegerValue(sourceKey: string, value: unknown): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isSafeInteger(value)) {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a finite safe integer.`);\n }\n return value;\n}\n\nfunction decodeReplicaRealValue(sourceKey: string, value: unknown): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a finite number.`);\n }\n return value;\n}\n\nfunction decodeReplicaBooleanValue(sourceKey: string, value: unknown): boolean {\n if (value !== 0 && value !== 1) {\n throw new Error(`Replica row source key \"${sourceKey}\" must be boolean integer 0 or 1.`);\n }\n return value === 1;\n}\n\nfunction decodeReplicaJsonValue(sourceKey: string, value: unknown): unknown {\n if (typeof value !== 'string') {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a JSON string.`);\n }\n\n try {\n return JSON.parse(value);\n } catch {\n throw new Error(`Replica row source key \"${sourceKey}\" must be valid JSON.`);\n }\n}\n\nfunction decodeReplicaDatetimeValue(sourceKey: string, value: unknown): string {\n if (typeof value !== 'string') {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a string.`);\n }\n return value;\n}\n\nfunction assertJsonSerializable(sourceKey: string, value: unknown, seen = new WeakSet<object>()): void {\n if (value === null || typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {\n return;\n }\n\n if (typeof value === 'undefined') {\n throw new Error(`Replica row source key \"${sourceKey}\" must be JSON-serializable without undefined.`);\n }\n\n if (typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint') {\n throw new Error(`Replica row source key \"${sourceKey}\" must be JSON-serializable without functions.`);\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n assertJsonSerializable(sourceKey, item, seen);\n }\n return;\n }\n\n if (typeof value === 'object') {\n if (seen.has(value)) {\n throw new Error(`Replica row source key \"${sourceKey}\" must be JSON-serializable without cycles.`);\n }\n seen.add(value);\n for (const key of Object.keys(value)) {\n assertJsonSerializable(sourceKey, (value as Record<string, unknown>)[key], seen);\n }\n }\n}\n\n/** Domain payload transformed during web replica schema migration. Identity and sync metadata stay outside this shape. */\nexport interface OfflineReplicaWebMigrationRow {\n readonly sourceKey: string;\n readonly values: Readonly<Record<string, unknown>>;\n readonly confirmedValues: Readonly<Record<string, unknown>> | null;\n}\n\n/** Result of {@link OfflineReplicaMigration.migrateWebRow}; `null` deletes the stored row. */\nexport type OfflineReplicaWebMigrationResult = OfflineReplicaWebMigrationRow | null;\n\n/** Transforms one replica row's domain projection during a web schema migration step. */\nexport type OfflineReplicaWebMigrationCallback = (\n row: OfflineReplicaWebMigrationRow,\n) => OfflineReplicaWebMigrationResult | Promise<OfflineReplicaWebMigrationResult>;\n\n/** One explicit schema-version step applied during offline SQLite and web replica migrations. */\nexport interface OfflineReplicaMigration {\n /** Source schema version; the migration advances to {@link fromVersion} + 1. */\n readonly fromVersion: number;\n /** Non-empty DDL/DML statements executed in order on native SQLite for this step. Web ignores these. */\n readonly statements: readonly string[];\n /**\n * Transforms one row's domain projection for web storage during this step.\n * The callback receives only {@link OfflineReplicaWebMigrationRow}; it must not read or mutate\n * `localId`, `remoteId`, scope, revision, or `syncState`. Return `null` to delete the row.\n */\n readonly migrateWebRow: OfflineReplicaWebMigrationCallback;\n}\n\n/** Versioned product replica schema bundle with entities and migration path. */\nexport interface OfflineReplicaSchemaBundle {\n /** Current bundle schema version. */\n readonly version: number;\n /** Entity schemas sorted by {@link OfflineReplicaEntitySchema.sourceKey}. */\n readonly entities: readonly OfflineReplicaEntitySchema<Record<string, unknown>>[];\n /** Migrations sorted by {@link OfflineReplicaMigration.fromVersion}. */\n readonly migrations: readonly OfflineReplicaMigration[];\n /** Canonical fingerprint input spanning version and every entity fingerprint. */\n readonly schemaFingerprintInput: string;\n}\n\n/** Input accepted by {@link defineOfflineReplicaSchema}. */\nexport interface OfflineReplicaSchemaDefinition {\n /** Current bundle schema version. */\n readonly version: number;\n /** Entity schemas for the bundle version. */\n readonly entities: readonly OfflineReplicaEntitySchema<Record<string, unknown>>[];\n /** Ordered one-step migrations from older bundle versions. */\n readonly migrations: readonly OfflineReplicaMigration[];\n}\n\n/**\n * Validates and materializes a versioned offline replica schema bundle.\n *\n * Entity `tableName` and `sourceKey` values must each be unique within the bundle.\n * Migrations must advance one version at a time without duplicates or gaps.\n */\nexport function defineOfflineReplicaSchema(definition: OfflineReplicaSchemaDefinition): OfflineReplicaSchemaBundle {\n assertPositiveInteger(definition.version, 'schema version');\n\n const entities = [...definition.entities].sort((left, right) =>\n left.sourceKey < right.sourceKey ? -1 : left.sourceKey > right.sourceKey ? 1 : 0,\n );\n const tableNames = new Set<string>();\n const sourceKeys = new Set<string>();\n for (const entity of entities) {\n if (tableNames.has(entity.tableName)) {\n throw new Error(`Duplicate replica entity table \"${entity.tableName}\".`);\n }\n tableNames.add(entity.tableName);\n\n if (sourceKeys.has(entity.sourceKey)) {\n throw new Error(`Duplicate replica entity source key \"${entity.sourceKey}\".`);\n }\n sourceKeys.add(entity.sourceKey);\n }\n\n const migrations = normalizeOfflineReplicaMigrations(definition.migrations, definition.version);\n const schemaFingerprintInput = buildBundleSchemaFingerprintInput(definition.version, entities, migrations);\n\n return {\n version: definition.version,\n entities,\n migrations,\n schemaFingerprintInput,\n };\n}\n\n/**\n * Computes a lowercase SHA-256 hex digest of {@link OfflineReplicaSchemaBundle.schemaFingerprintInput}.\n */\nexport async function sha256OfflineReplicaSchema(bundle: OfflineReplicaSchemaBundle): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(bundle.schemaFingerprintInput));\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\nfunction normalizeOfflineReplicaMigrations(\n migrations: readonly OfflineReplicaMigration[],\n bundleVersion: number,\n): readonly OfflineReplicaMigration[] {\n const sorted = [...migrations].sort((left, right) => left.fromVersion - right.fromVersion);\n const seenFromVersions = new Set<number>();\n\n for (const migration of sorted) {\n assertPositiveInteger(migration.fromVersion, 'migration fromVersion');\n\n const targetVersion = migration.fromVersion + 1;\n if (targetVersion > bundleVersion) {\n throw new Error(\n `Replica migration from version ${migration.fromVersion} targets version ${targetVersion}, which exceeds bundle version ${bundleVersion}.`,\n );\n }\n\n if (seenFromVersions.has(migration.fromVersion)) {\n throw new Error(`Duplicate replica migration from version ${migration.fromVersion}.`);\n }\n seenFromVersions.add(migration.fromVersion);\n\n if (typeof migration.migrateWebRow !== 'function') {\n throw new Error(`Replica migration from version ${migration.fromVersion} requires migrateWebRow.`);\n }\n\n if (migration.statements.length === 0) {\n throw new Error(`Replica migration from version ${migration.fromVersion} requires at least one SQL statement.`);\n }\n\n for (const [index, statement] of migration.statements.entries()) {\n if (!statement.trim()) {\n throw new Error(`Replica migration from version ${migration.fromVersion} statement ${index + 1} must not be empty.`);\n }\n }\n }\n\n for (let index = 1; index < sorted.length; index++) {\n const previous = sorted[index - 1]!;\n const current = sorted[index]!;\n if (current.fromVersion !== previous.fromVersion + 1) {\n throw new Error(\n `Replica migrations must advance consecutive schema versions; expected fromVersion ${previous.fromVersion + 1}, received ${current.fromVersion}.`,\n );\n }\n }\n\n if (sorted.length > 0 && sorted[0]!.fromVersion !== 1) {\n throw new Error(\n `Replica migrations must advance consecutive schema versions; expected fromVersion 1, received ${sorted[0]!.fromVersion}.`,\n );\n }\n\n const finalRequiredFromVersion = bundleVersion - 1;\n if (finalRequiredFromVersion > 0 && sorted.at(-1)?.fromVersion !== finalRequiredFromVersion) {\n const firstMissingVersion = (sorted.at(-1)?.fromVersion ?? 0) + 1;\n throw new Error(\n `Missing offline replica schema migration from version ${firstMissingVersion} to ${firstMissingVersion + 1}.`,\n );\n }\n\n return sorted;\n}\n\nfunction buildBundleSchemaFingerprintInput(\n version: number,\n entities: readonly OfflineReplicaEntitySchema<Record<string, unknown>>[],\n migrations: readonly OfflineReplicaMigration[],\n): string {\n const entityFingerprints = entities.map((entity) => entity.schemaFingerprintInput).join(';');\n const migrationFingerprints = migrations\n .map((migration) => `from=${migration.fromVersion}|statements=${migration.statements.join('\\n')}`)\n .join(';');\n return `version=${version}|entities=${entityFingerprints}|migrations=${migrationFingerprints}`;\n}\n\nfunction assertPositiveInteger(value: number, label: string): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new Error(`Replica ${label} must be a positive integer.`);\n }\n}\n","import {\n canonicalOfflineRemoteIdentity,\n normalizeOfflineNaturalKey,\n offlineNaturalKeyFromValues,\n type OfflineGeneratedRemoteId,\n type OfflineNaturalKey,\n type OfflineReplicaEntitySchema,\n type OfflineReplicaRemoteIdentity,\n} from './offline-replica-schema';\n\n/** Product-agnostic authenticated principal identifier. */\nexport type OfflinePrincipalId = string | number;\n\n/** Narrows a product DB id without duplicating the numeric identity boundary. */\nexport function requirePositiveOfflineInteger(value: unknown, label = 'Offline id'): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {\n throw new Error(`${label} must be a positive safe integer.`);\n }\n return value;\n}\n\n/** Type-tagged SQLite/web key; numeric 7 and text \"7\" never share a boundary. */\nexport function canonicalOfflinePrincipalId(value: OfflinePrincipalId): string {\n if (typeof value === 'number') {\n if (!Number.isSafeInteger(value) || !Number.isFinite(value)) {\n throw new Error('Offline principal id number must be a finite safe integer.');\n }\n return `n:${value}`;\n }\n if (value.length === 0) throw new Error('Offline principal id string must not be empty.');\n return `s:${JSON.stringify(value)}`;\n}\n\n/** Decodes a principal previously persisted by {@link canonicalOfflinePrincipalId}. */\nexport function parseOfflinePrincipalId(value: string): OfflinePrincipalId {\n if (value.startsWith('n:')) {\n const numberValue = Number(value.slice(2));\n if (!Number.isSafeInteger(numberValue)) throw new Error('Stored offline principal id is invalid.');\n return numberValue;\n }\n if (value.startsWith('s:')) {\n const stringValue: unknown = JSON.parse(value.slice(2));\n if (typeof stringValue !== 'string' || stringValue.length === 0) throw new Error('Stored offline principal id is invalid.');\n return stringValue;\n }\n throw new Error('Stored offline principal id has an unknown codec.');\n}\n\n/** Durable address of a generated or natural-key replica row. */\nexport type OfflineReplicaIdentity =\n | { readonly kind: 'generated'; readonly localId: string; readonly remoteId: OfflineGeneratedRemoteId | null }\n | { readonly kind: 'natural'; readonly naturalKey: OfflineNaturalKey }\n | { readonly kind: 'local'; readonly localId: string };\n\n/** Outbox address. Generated ids are resolved to the latest server id immediately before transport. */\nexport type OfflineCommandIdentity =\n | { readonly kind: 'generated'; readonly localId: string }\n | { readonly kind: 'natural'; readonly naturalKey: OfflineNaturalKey };\n\n/** Stable lookup address for every replica row, including local-only projections. */\nexport type OfflineReplicaAddress = OfflineCommandIdentity | { readonly kind: 'local'; readonly localId: string };\n\n/** Stable storage key for one outbox or replica row identity. */\nexport function canonicalOfflineCommandIdentity(identity: OfflineCommandIdentity): string {\n if (identity.kind === 'generated') {\n assertOfflineLocalId(identity.localId);\n return `generated:${identity.localId}`;\n }\n return `natural:${canonicalOfflineNaturalKeyIdentity(identity.naturalKey)}`;\n}\n\n/** Stable storage key for one materialized replica row identity. */\nexport function canonicalOfflineReplicaIdentity(identity: OfflineReplicaIdentity): string {\n if (identity.kind === 'generated') {\n assertOfflineLocalId(identity.localId);\n return `generated:${identity.localId}`;\n }\n if (identity.kind === 'local') {\n assertOfflineLocalId(identity.localId);\n return `local:${identity.localId}`;\n }\n return `natural:${canonicalOfflineNaturalKeyIdentity(identity.naturalKey)}`;\n}\n\n/** JSON persisted in SQLite/web outbox rows. */\nexport function serializeOfflineCommandIdentity(identity: OfflineCommandIdentity): string {\n canonicalOfflineCommandIdentity(identity);\n return JSON.stringify(identity);\n}\n\n/** Parses durable outbox identity JSON. */\nexport function parseOfflineCommandIdentity(value: unknown): OfflineCommandIdentity {\n if (!isPlainObject(value)) throw new Error('Offline command identity must be a plain object.');\n if (value['kind'] === 'generated') {\n assertOfflineLocalId(value['localId']);\n return { kind: 'generated', localId: value['localId'] };\n }\n if (value['kind'] === 'natural') {\n if (!isPlainObject(value['naturalKey'])) throw new Error('Offline natural command identity requires naturalKey.');\n return { kind: 'natural', naturalKey: value['naturalKey'] as OfflineNaturalKey };\n }\n throw new Error('Offline command identity must be generated or natural.');\n}\n\n/** Builds a generated replica identity. */\nexport function offlineGeneratedReplicaIdentity(localId: string, remoteId: OfflineGeneratedRemoteId | null): OfflineReplicaIdentity {\n assertOfflineLocalId(localId);\n return { kind: 'generated', localId, remoteId };\n}\n\n/** Validates a durable local row id before it can enter either storage backend. */\nexport function assertOfflineLocalId(value: unknown): asserts value is string {\n if (\n typeof value !== 'string' ||\n value.length === 0 ||\n value.includes('\\0') ||\n value !== value.normalize('NFC') ||\n new TextEncoder().encode(value).byteLength > 255\n ) {\n throw new Error('Offline localId must be a non-empty normalized string of at most 255 UTF-8 bytes without NUL.');\n }\n}\n\n/** Builds a natural replica identity from current domain values. */\nexport function offlineNaturalReplicaIdentity(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n values: unknown,\n): OfflineReplicaIdentity {\n return { kind: 'natural', naturalKey: offlineNaturalKeyFromValues(schema, values)! };\n}\n\n/** Converts a materialized replica identity into an outbox address. */\nexport function commandIdentityFromReplicaIdentity(identity: OfflineReplicaIdentity): OfflineCommandIdentity {\n if (identity.kind === 'generated') return { kind: 'generated', localId: identity.localId };\n if (identity.kind === 'local') {\n throw new Error('Local-only replica rows cannot be added to the Outbox.');\n }\n return { kind: 'natural', naturalKey: identity.naturalKey };\n}\n\n/** Converts a materialized row identity into its immutable repository address. */\nexport function replicaAddressFromIdentity(identity: OfflineReplicaIdentity): OfflineReplicaAddress {\n if (identity.kind === 'natural') return { kind: 'natural', naturalKey: identity.naturalKey };\n return { kind: identity.kind, localId: identity.localId };\n}\n\n/** Whether a command identity addresses the given replica row. */\nexport function commandIdentityMatchesReplicaRow(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n row: { readonly identity: OfflineReplicaIdentity },\n commandIdentity: OfflineCommandIdentity,\n): boolean {\n if (commandIdentity.kind === 'generated') {\n return row.identity.kind === 'generated' && row.identity.localId === commandIdentity.localId;\n }\n if (row.identity.kind !== 'natural') return false;\n return (\n canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) ===\n canonicalOfflineRemoteIdentity(schema, { naturalKey: normalizeOfflineNaturalKey(schema, commandIdentity.naturalKey) })\n );\n}\n\n/** Remote identity used by pull reconciliation and uniqueness checks. */\nexport function offlineReplicaRemoteIdentity(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n identity: OfflineReplicaIdentity,\n): OfflineReplicaRemoteIdentity | null {\n if (schema.identity.kind === 'generated') {\n return identity.kind === 'generated' && identity.remoteId !== null ? { remoteId: identity.remoteId } : null;\n }\n if (schema.identity.kind === 'naturalKey') {\n return identity.kind === 'natural' ? { naturalKey: identity.naturalKey } : null;\n }\n return null;\n}\n\nfunction canonicalOfflineNaturalKeyIdentity(naturalKey: OfflineNaturalKey): string {\n return JSON.stringify(\n Object.keys(naturalKey)\n .sort()\n .map((key) => {\n const value = naturalKey[key]!;\n return [key, typeof value === 'number' ? 'n' : 's', value];\n }),\n );\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n","import { InjectionToken } from '@angular/core';\nimport type { OfflineCommand, OfflineReplicaRow, OfflineReplicaRowKey, OfflineReplicaTransaction } from './offline-repository';\n\n/**\n * Authoritative inputs for rematerializing one aggregate from its remaining\n * ordered Outbox chain.\n *\n * `baseRow` is the current replica row for the aggregate, including its latest\n * `confirmedValues`. `localOnlyRows` are the current localOnly projection rows\n * owned by that aggregate. `commands` is the complete remaining FIFO chain\n * after the triggering mutation.\n */\nexport interface OfflineAggregateIntentProjectInput {\n /** Current aggregate base replica row, or `null` when the row is absent. */\n readonly baseRow: OfflineReplicaRow | null;\n /** Current authoritative localOnly projection rows for this aggregate. */\n readonly localOnlyRows: readonly OfflineReplicaRow[];\n /** Complete remaining ordered pending command chain for this aggregate. */\n readonly commands: readonly OfflineCommand[];\n /** Boundary that requested rematerialization. Only pull may return a conflict outcome. */\n readonly trigger?: 'local' | 'pull';\n /** Incoming authoritative revision when `trigger` is `pull`. */\n readonly incomingRevision?: string | number;\n}\n\n/**\n * Fully rematerialized aggregate projection.\n *\n * Kit writes `baseRow` as the sole base mutation (`null` removes the row) and\n * applies only the localOnly put/remove lists. Domain folding belongs here;\n * Kit never interprets command payloads.\n */\nexport interface OfflineAggregateIntentProjection {\n /** Rematerialized base replica row, or `null` to remove the aggregate row. */\n readonly baseRow: OfflineReplicaRow | null;\n /** LocalOnly projection rows to upsert for this aggregate. */\n readonly putLocalOnlyRows?: readonly OfflineReplicaRow[];\n /** LocalOnly projection rows to remove for this aggregate. */\n readonly removeLocalOnlyRows?: readonly OfflineReplicaRowKey[];\n}\n\n/** Product decision that pending intents cannot be replayed onto an incoming authoritative revision. */\nexport interface OfflineAggregateIntentConflict {\n readonly kind: 'conflict';\n readonly reason: string;\n}\n\n/** Result of product-owned aggregate rematerialization. */\nexport type OfflineAggregateIntentProjectResult = OfflineAggregateIntentProjection | OfflineAggregateIntentConflict;\n\n/**\n * Product-owned pure rematerialization of one aggregate.\n *\n * Given the authoritative base row, current localOnly projection rows, and the\n * remaining ordered {@link OfflineCommand} chain, return one fully materialized\n * base row plus localOnly put/remove mutations. The adapter must derive only\n * from confirmed base/localOnly values plus complete FIFO pending intents. It\n * must not perform I/O; Kit supplies already-read replica state and validates\n * scope, schema, identity, and footprints before writing.\n */\nexport interface OfflineAggregateIntentProjector {\n /** Rematerializes one aggregate from authoritative replica state and remaining intents. */\n project(input: OfflineAggregateIntentProjectInput): OfflineAggregateIntentProjectResult;\n}\n\n/** Returns whether the projector rejected replay onto an authoritative pull revision. */\nexport function isOfflineAggregateIntentConflict(result: OfflineAggregateIntentProjectResult): result is OfflineAggregateIntentConflict {\n return 'kind' in result && result.kind === 'conflict';\n}\n\n/** Required product adapter for aggregate rematerialization from remaining Outbox intents. */\nexport const OFFLINE_AGGREGATE_INTENT_PROJECTOR = new InjectionToken<OfflineAggregateIntentProjector>('OFFLINE_AGGREGATE_INTENT_PROJECTOR');\n\n/**\n * Converts a validated aggregate projection into replica put/remove mutations.\n *\n * @param projection - Rematerialized aggregate returned by the product projector.\n * @param baseRow - Current aggregate base row, used when the projection removes it.\n */\nexport function offlineAggregateIntentMutations(\n projection: OfflineAggregateIntentProjection,\n baseRow: OfflineReplicaRow | null,\n): Pick<OfflineReplicaTransaction, 'putRows' | 'removeRows'> {\n const putRows: OfflineReplicaRow[] = [];\n const removeRows: OfflineReplicaRowKey[] = [];\n if (projection.baseRow) putRows.push(projection.baseRow);\n else if (baseRow) {\n removeRows.push({\n userId: baseRow.userId,\n scopeId: baseRow.scopeId,\n sourceKey: baseRow.sourceKey,\n identity: baseRow.identity,\n });\n }\n putRows.push(...(projection.putLocalOnlyRows ?? []));\n removeRows.push(...(projection.removeLocalOnlyRows ?? []));\n return { putRows, removeRows };\n}\n","import { InjectionToken } from '@angular/core';\nimport type { OfflineReplicaRow, OfflineReplicaRowKey, OfflineScope } from './offline-repository';\nimport type { OfflineGeneratedRemoteId, OfflineNaturalKey, OfflineReplicaRemoteIdentity } from './offline-replica-schema';\n\n/** Server pull request for one user or partition-scoped replica. */\nexport interface OfflineReplicaPullRequest {\n scope: OfflineScope;\n cursor: string;\n schemaVersion: number;\n schemaHash: string;\n /**\n * Successfully transported commands that still require an authoritative row acknowledgement.\n * The server must hydrate and authorize each target from primary state and acknowledge it only\n * on the returned reconciliation change; it must never trust this client identity as proof.\n */\n reconciliationTargets: readonly OfflineReplicaReconciliationTarget[];\n}\n\n/** One awaiting-pull command whose canonical state must be hydrated independently of journal retention. */\nexport interface OfflineReplicaReconciliationTarget {\n readonly commandId: string;\n readonly operation: string;\n readonly sourceKey: string;\n readonly identity: OfflineReplicaRemoteIdentity;\n}\n\n/** One server-side replica mutation returned by an explicit pull page. */\nexport interface OfflineReplicaChangeBase {\n sourceKey: string;\n serverRevision: string | number;\n /**\n * Idempotency command ids durably recorded by the server and reflected in this final row state.\n * They may include commands from other clients; the runtime correlates only ids in its local Outbox.\n */\n acknowledgedCommandIds?: readonly string[];\n values: unknown | null;\n deleted: boolean;\n}\n\n/** One server-side mutation with the identity kind declared by its replica schema. */\nexport type OfflineReplicaChange = OfflineReplicaChangeBase & OfflineReplicaRemoteIdentity;\n\n/**\n * Backend wire identity accepted at the HTTP boundary.\n *\n * `serverId` is the database-facing name used by Hono applications. The\n * offline runtime deliberately calls the same value `remoteId`, because the\n * repository is not tied to a particular server database. Normalize exactly\n * once at the transport boundary with {@link normalizeOfflineReplicaPullPage}.\n */\nexport type OfflineReplicaWireIdentity =\n | { readonly serverId: OfflineGeneratedRemoteId }\n | { readonly remoteId: OfflineGeneratedRemoteId }\n | { readonly naturalKey: OfflineNaturalKey };\n\n/** One backend pull mutation before its DB-facing identity is normalized. */\nexport type OfflineReplicaWireChange = OfflineReplicaChangeBase & OfflineReplicaWireIdentity;\n\n/** One explicit replica pull response page from the application backend. */\nexport interface OfflineReplicaPullPage {\n schemaVersion: number;\n schemaHash: string;\n changes: readonly OfflineReplicaChange[];\n nextCursor: string;\n hasMore: boolean;\n /** The server can no longer continue this cursor and requires a confirmed-state snapshot rebuild. */\n rebaselineRequired?: boolean;\n}\n\n/** Product projection derived from one collapsed authoritative pull page. */\nexport interface OfflineReplicaPullProjection {\n putRows?: readonly OfflineReplicaRow[];\n removeRows?: readonly OfflineReplicaRowKey[];\n}\n\n/** Pure product adapter for local-only projections derived from server replica changes. */\nexport interface OfflineReplicaProjector {\n project(input: { scope: OfflineScope; changes: readonly OfflineReplicaChange[] }): Promise<OfflineReplicaPullProjection>;\n}\n\n/** Backend response accepted by the shared pull-page normalizer. */\nexport interface OfflineReplicaWirePullPage {\n schemaVersion: number;\n schemaHash: string;\n changes: readonly OfflineReplicaWireChange[];\n nextCursor: string;\n hasMore: boolean;\n /** The server can no longer continue this cursor and requires a confirmed-state snapshot rebuild. */\n rebaselineRequired?: boolean;\n}\n\n/**\n * Converts a backend DB identity (`serverId`) to the runtime identity\n * (`remoteId`) without allowing product pullers to each reimplement the rule.\n */\nexport function normalizeOfflineReplicaPullPage(page: OfflineReplicaWirePullPage): OfflineReplicaPullPage {\n return {\n ...page,\n changes: page.changes.map((change, index) => {\n if ('naturalKey' in change) return change;\n if ('serverId' in change && 'remoteId' in change) {\n throw new Error(`Offline replica pull page changes[${index}] cannot contain both serverId and remoteId.`);\n }\n if ('serverId' in change) {\n const { serverId, ...rest } = change;\n return { ...rest, remoteId: serverId };\n }\n return change;\n }),\n };\n}\n\n/** Application-provided transport that fetches explicit replica pull pages from the server. */\nexport interface OfflineReplicaPuller {\n pull(request: OfflineReplicaPullRequest): Promise<OfflineReplicaPullPage>;\n}\n\n/** DI token for the application-provided explicit replica pull transport. */\nexport const OFFLINE_REPLICA_PULLER = new InjectionToken<OfflineReplicaPuller>('OFFLINE_REPLICA_PULLER');\n\n/** Optional product adapter for local-only replica projections. */\nexport const OFFLINE_REPLICA_PROJECTOR = new InjectionToken<OfflineReplicaProjector>('OFFLINE_REPLICA_PROJECTOR');\n","import { InjectionToken } from '@angular/core';\nimport type { OfflineCommand } from './offline-repository';\n\n/** Optional product hooks for entity projection and command cleanup. */\nexport interface OfflineCommandHooks {\n entityType(command: Pick<OfflineCommand, 'operation' | 'aggregateType'>): string;\n onCommandRemoved?(command: OfflineCommand): Promise<void>;\n}\n\nexport const DEFAULT_OFFLINE_COMMAND_HOOKS: OfflineCommandHooks = {\n entityType: (command) => command.aggregateType,\n};\n\n/** DI token for optional product-specific synchronization hooks. */\nexport const OFFLINE_COMMAND_HOOKS = new InjectionToken<OfflineCommandHooks>('OFFLINE_COMMAND_HOOKS', {\n providedIn: 'root',\n factory: () => DEFAULT_OFFLINE_COMMAND_HOOKS,\n});\n","import { InjectionToken, type Type } from '@angular/core';\nimport type { OfflineReplicaSchemaBundle } from './offline-replica-schema';\nimport type { OfflineStorageUnavailableError } from './offline-storage';\n\n/** Backpressure limits for durable commands. Pending commands are never evicted automatically. */\nexport interface OfflineOutboxLimits {\n /** Maximum number of commands retained for one user. Defaults to 1,000. */\n maxCommandsPerUser?: number;\n /** Maximum serialized size retained for one user. Defaults to 10 MiB. */\n maxBytesPerUser?: number;\n}\n\n/** Product persistence adapter for the device-local offline mutation preference. */\nexport interface OfflineMutationPersistenceAdapter {\n /** Loads the last durable preference. `null` or `undefined` uses the configured default. */\n loadEnabled(): Promise<boolean | null | undefined>;\n /** Persists a completed enable or disable transition. */\n saveEnabled(enabled: boolean): Promise<void>;\n}\n\n/** Configuration for device-local mutation persistence control. */\nexport interface OfflineMutationPersistenceOptions {\n /** Injectable product adapter for the durable preference store. */\n adapter: Type<OfflineMutationPersistenceAdapter>;\n /** Initial value when no durable preference exists. Defaults to `true`. */\n defaultEnabled?: boolean;\n}\n\n/** Product-independent native offline persistence settings. */\nexport interface OfflineKitOptions {\n /** Runtime transport mode. Defaults to full synchronized replica/outbox behavior. */\n mode?: 'synchronized' | 'readCacheOnly';\n /** Encrypted SQLite database name used on iOS and Android. */\n databaseName: string;\n /** Creates the native database encryption key on first install. Required on iOS and Android. */\n createEncryptionKey?: () => Promise<string>;\n /** Versioned product replica schema applied to native SQLite during initialization. */\n replicaSchema: OfflineReplicaSchemaBundle;\n /**\n * Product wire protocol fingerprint exchanged with the synchronization server.\n *\n * Keep this independent from {@link replicaSchema}: local-only tables and\n * storage migrations must not force a server rollout. When omitted, Kit uses\n * the replica schema fingerprint for backward compatibility.\n */\n wireProtocol?: OfflineWireProtocolFingerprint;\n /** Optional durable Outbox backpressure policy. */\n outboxLimits?: OfflineOutboxLimits;\n /**\n * Optional device-local control for accepting new durable Outbox mutations.\n *\n * Replica reads remain enabled while mutation persistence is disabled. When omitted,\n * Kit preserves the historical always-enabled mutation behavior.\n */\n mutationPersistence?: OfflineMutationPersistenceOptions;\n /**\n * Optional product callback invoked when local storage initialization fails.\n *\n * Providing this callback opts the application into online-only startup degradation:\n * after the callback settles successfully, the app initializer completes with\n * {@link OfflineCoordinatorService.storageState} `unavailable` and session/sync are not started.\n * When omitted, initialization throws {@link OfflineStorageUnavailableError} as before.\n * If the callback throws or rejects, initialization still fails.\n *\n * Kit never deletes Outbox or replica data in response to storage failure. Products may invoke\n * `recoverOfflineLocalReset` only after an explicit destructive reset request.\n */\n onStorageUnavailable?: (error: OfflineStorageUnavailableError) => void | Promise<void>;\n}\n\n/** Exact versioned wire contract exchanged by pull transport. */\nexport interface OfflineWireProtocolFingerprint {\n /** Monotonic product wire protocol version. */\n readonly version: number;\n /** Deterministic fingerprint of the pull/push wire contract. */\n readonly hash: string;\n}\n\n/** DI token for product-independent offline persistence settings. */\nexport const OFFLINE_KIT_OPTIONS = new InjectionToken<OfflineKitOptions>('OFFLINE_KIT_OPTIONS');\n","import { InjectionToken } from '@angular/core';\nimport type { OfflineCommand, OfflineScope } from './offline-repository';\nimport type { OfflineCommandIdentity, OfflinePrincipalId, OfflineReplicaIdentity } from './offline-identity';\nimport type { OfflineGeneratedRemoteId, OfflineNaturalKey } from './offline-replica-schema';\n\n/** Server acknowledgement used to reconcile one optimistic local mutation. */\nexport interface OfflineCommandResult {\n /** Remote id returned by a successful generated-identity mutation. */\n remoteId?: OfflineGeneratedRemoteId;\n serverRevision?: string | number;\n /**\n * Full server-confirmed domain values after applying the mutation.\n *\n * Kit does not treat this as the durable confirmed baseline while the\n * command remains in the Outbox. Authoritative confirmed values come from\n * pull acknowledgement of `commandId`.\n */\n confirmedValues?: unknown;\n /** Removes the local replica row after a confirmed server delete. */\n removeReplica?: boolean;\n /**\n * Releases the deleted row's remote identity while keeping\n * its immutable local id for a queued recreate of the same logical target.\n */\n clearRemoteId?: boolean;\n response?: unknown;\n}\n\n/** Target identity resolved from the local replica immediately before transport. */\nexport type OfflineCommandTarget =\n | { readonly kind: 'generated'; readonly localId: string; readonly remoteId: OfflineGeneratedRemoteId | null }\n | { readonly kind: 'natural'; readonly naturalKey: OfflineNaturalKey };\n\n/** Product adapter that sends commands and projects acknowledgements into entities. */\nexport interface OfflineCommandExecutor {\n /** Sends the command using `command.commandId` as its durable server-side idempotency key. */\n execute(command: OfflineCommand, target: OfflineCommandTarget): Promise<OfflineCommandResult>;\n /**\n * Whether this transport error authoritatively proves that this idempotency\n * key did not commit. Returning true may clear an ambiguity retained from an\n * earlier response-loss attempt and expose normal conflict resolution.\n */\n provesCommandNotCommitted?(error: unknown, command: OfflineCommand): boolean;\n}\n\n/**\n * Returns a command whose only changed field is `baseRevision`.\n *\n * Payload and every other field are copied unchanged. Kit uses this when a\n * newer server revision is known, and passes `null` after a generated remote\n * identity is released.\n */\nexport function offlineCommandWithBaseRevision(command: OfflineCommand, baseRevision: string | number | null): OfflineCommand {\n return { ...command, baseRevision };\n}\n\n/** DI token for the product-specific command transport adapter. */\nexport const OFFLINE_COMMAND_EXECUTOR = new InjectionToken<OfflineCommandExecutor>('OFFLINE_COMMAND_EXECUTOR');\n\n/** Authenticated user and partition scopes currently eligible for synchronization. */\nexport interface OfflineSyncSession {\n userId: OfflinePrincipalId;\n scopes: OfflineScope[];\n}\n\n/** Product adapter that exposes the currently authenticated synchronization session. */\nexport interface OfflineSyncContext {\n /** Session allowed to read/write the local replica and append durable outbox commands. */\n getLocalSession?(): Promise<OfflineSyncSession | null>;\n /** Remotely authenticated session allowed to pull and replay commands. */\n getSession(): Promise<OfflineSyncSession | null>;\n}\n\n/** DI token for authenticated synchronization context. */\nexport const OFFLINE_SYNC_CONTEXT = new InjectionToken<OfflineSyncContext>('OFFLINE_SYNC_CONTEXT');\n\n/** Resolves the transport target from a replica row. */\nexport function offlineCommandTargetFromReplicaRow(row: { readonly identity: OfflineReplicaIdentity }): OfflineCommandTarget {\n if (row.identity.kind === 'natural') return { kind: 'natural', naturalKey: row.identity.naturalKey };\n if (row.identity.kind === 'local') throw new Error('Local-only replica rows cannot be synchronized.');\n return { kind: 'generated', localId: row.identity.localId, remoteId: row.identity.remoteId };\n}\n\n/** Resolves a command lookup identity from an enqueue request identity. */\nexport function offlineCommandLookupIdentity(identity: EnqueueOfflineCommandIdentity): OfflineCommandIdentity {\n if (identity.kind === 'generated') return { kind: 'generated', localId: identity.localId };\n return { kind: 'natural', naturalKey: identity.naturalKey };\n}\n\n/** Enqueue identity for generated entities. */\nexport interface EnqueueOfflineGeneratedIdentity {\n readonly kind: 'generated';\n readonly localId: string;\n readonly remoteId?: OfflineGeneratedRemoteId | null;\n readonly remoteIdHint?: OfflineGeneratedRemoteId | null;\n}\n\n/** Enqueue identity for natural-key entities. */\nexport interface EnqueueOfflineNaturalIdentity {\n readonly kind: 'natural';\n readonly naturalKey: OfflineNaturalKey;\n}\n\nexport type EnqueueOfflineCommandIdentity = EnqueueOfflineGeneratedIdentity | EnqueueOfflineNaturalIdentity;\n","/**\n * Internal repository capability used to detect commits made through another\n * native SQLite connection during a local read/derive/write operation.\n *\n * This symbol is intentionally not re-exported from the package entry point.\n */\nexport const OFFLINE_REPOSITORY_ATOMIC_MUTATION: unique symbol = Symbol('OFFLINE_REPOSITORY_ATOMIC_MUTATION');\n","import { inject, Injectable, InjectionToken } from '@angular/core';\nimport { KitStorageService } from '@rdlabo/ionic-angular-kit';\nimport {\n canonicalOfflineCommandIdentity,\n canonicalOfflinePrincipalId,\n canonicalOfflineReplicaIdentity,\n commandIdentityFromReplicaIdentity,\n offlineReplicaRemoteIdentity,\n type OfflineCommandIdentity,\n type OfflineReplicaAddress,\n type OfflineReplicaIdentity,\n type OfflinePrincipalId,\n} from './offline-identity';\nimport { OFFLINE_REPOSITORY_ATOMIC_MUTATION } from './offline-repository-concurrency';\nimport { OFFLINE_KIT_OPTIONS } from './offline-kit-options';\nimport {\n assertOfflineReplicaGeneratedRemoteId,\n assertOfflineReplicaNaturalKeyBaseline,\n canonicalOfflineRemoteIdentity,\n encodeOfflineReplicaValues,\n normalizeOfflineNaturalKey,\n offlineNaturalKeyFromValues,\n projectOfflineReplicaValues,\n sha256OfflineReplicaSchema,\n type OfflineGeneratedRemoteId,\n type OfflineReplicaEntitySchema,\n type OfflineReplicaRemoteIdentity,\n type OfflineReplicaWebMigrationRow,\n} from './offline-replica-schema';\n\nexport type { OfflineCommandIdentity, OfflinePrincipalId, OfflineReplicaAddress, OfflineReplicaIdentity } from './offline-identity';\nexport {\n canonicalOfflineCommandIdentity,\n canonicalOfflinePrincipalId,\n canonicalOfflineReplicaIdentity,\n commandIdentityFromReplicaIdentity,\n commandIdentityMatchesReplicaRow,\n offlineGeneratedReplicaIdentity,\n offlineNaturalReplicaIdentity,\n offlineReplicaRemoteIdentity,\n parseOfflineCommandIdentity,\n parseOfflinePrincipalId,\n replicaAddressFromIdentity,\n serializeOfflineCommandIdentity,\n} from './offline-identity';\n\n/** Current durable storage schema used by both web and native repositories. */\nexport const OFFLINE_SCHEMA_VERSION = 2;\n\nconst settledRepositoryOperation = async (): Promise<void> => undefined;\n\n/** User and partition scope of all local offline data. */\nexport interface OfflineScope {\n userId: OfflinePrincipalId;\n scopeId: string;\n}\n\n/** Synchronization state of a locally materialized product replica row. */\nexport type OfflineReplicaSyncState = 'confirmed' | 'pending' | 'blocked_auth' | 'rejected' | 'conflict';\nexport type OfflineReplicaVisibility = 'present' | 'pending_delete';\nexport type OfflineReplicaMutation = 'upsert' | 'delete';\n\n/** Durable processing state of an outbox command. */\nexport type OfflineCommandState = 'pending' | 'sending' | 'retry_wait' | 'awaiting_pull' | 'blocked_auth' | 'rejected' | 'conflict';\n\ninterface OfflineCommandBase<T> extends OfflineScope {\n commandId: string;\n aggregateType: string;\n /** Replica schema source key resolved when the command is enqueued. */\n sourceKey: string;\n /** Stable row identity. The Outbox never persists a generated server id. */\n identity: OfflineCommandIdentity;\n operation: string;\n /** Opaque product payload. Kit never mutates this after enqueue. */\n payload: T;\n /**\n * Declared localOnly projection rows this intent may create, update, or remove.\n * Kit persists keys only; before/after images are not durable truth.\n */\n localOnlyFootprint?: readonly OfflineReplicaRowKey[];\n /** Durable intent used to preserve a hidden tombstone across restart and replay. */\n replicaMutation?: OfflineReplicaMutation;\n baseRevision: string | number | null;\n state: OfflineCommandState;\n attempts: number;\n retryAt: number | null;\n createdAt: number;\n lastErrorCode: string | null;\n /** True when transport started but the client cannot prove whether the server committed. */\n serverCommitUnknown?: boolean;\n /** Remote identity captured after transport for journal-independent authoritative reconciliation. */\n reconciliationIdentity?: OfflineReplicaRemoteIdentity;\n}\n\nexport type OfflineCommand<T = unknown> = OfflineCommandBase<T>;\n\n/** Product replica row materialized from a versioned schema entity. */\ninterface OfflineReplicaRowBase<TValues> extends OfflineScope {\n /** Stable source key matching {@link OfflineReplicaEntitySchema.sourceKey}. */\n sourceKey: string;\n /** Row identity matching the entity schema. Natural-key rows have no synthetic ids. */\n identity: OfflineReplicaIdentity;\n /** Current optimistic domain values displayed locally. */\n values: TValues;\n /** Last server-confirmed domain values, or null while pending. */\n confirmedValues: TValues | null;\n serverRevision: string | number | null;\n fetchedAt: number;\n syncState: OfflineReplicaSyncState;\n /** Library-owned visibility; pending deletes remain durable but are hidden from product reads. */\n visibility?: OfflineReplicaVisibility;\n}\n\nexport type OfflineReplicaRow<TValues = unknown> = OfflineReplicaRowBase<TValues>;\n\n/** Stable address of a product replica row inside a user or partition-scoped replica. */\nexport interface OfflineReplicaRowKey extends OfflineScope {\n sourceKey: string;\n identity: OfflineReplicaIdentity;\n}\n\n/** Canonical physical key shared by every repository and replica transaction coordinator. */\nexport function canonicalOfflineReplicaRowKey(\n schema: Pick<OfflineReplicaEntitySchema<Record<string, unknown>>, 'scope'>,\n row: OfflineReplicaRowKey,\n): string {\n const partition = schema.scope === 'user' ? 'user' : String(row.scopeId);\n return `${canonicalOfflinePrincipalId(row.userId)}:${partition}:${row.sourceKey}:${canonicalOfflineReplicaIdentity(row.identity)}`;\n}\n\n/** Explicit one-way release of a generated remote id during a replica delete acknowledgement. */\nexport interface OfflineReplicaRemoteIdRelease extends OfflineReplicaRowKey {\n /** The current remote id being released; the matching put row must set `remoteId` to null. */\n remoteId: OfflineGeneratedRemoteId;\n}\n\n/** Scope partition plus the durable replica pull cursor for that partition. */\nexport interface OfflineReplicaCursor extends OfflineScope {\n cursor: string;\n}\n\n/**\n * Closed set of durable reasons a scope cannot be pulled until the client recovers\n * (app upgrade or re-authorization). Independent of Outbox command state.\n */\nexport type OfflinePullAttentionReason = 'schema_upgrade_required' | 'authorization_required';\n\n/**\n * First-class durable attention for a fatal pull failure scoped to user+scope.\n * Survives restart even when the Outbox is empty.\n */\nexport interface OfflinePullAttention extends OfflineScope {\n reason: OfflinePullAttentionReason;\n /** Optional HTTP status that produced this attention (for example 401, 403, or 409). */\n status?: number;\n}\n\n/** Atomic changes applied to the local replica and durable outbox together. */\nexport interface OfflineReplicaTransaction {\n putRows?: readonly OfflineReplicaRow[];\n /**\n * Allows only the matching `remoteId: current -> null` transition in `putRows`.\n * All other remote-id changes remain immutable.\n */\n releaseRemoteIds?: readonly OfflineReplicaRemoteIdRelease[];\n removeRows?: readonly OfflineReplicaRowKey[];\n putCommands?: readonly OfflineCommand[];\n removeCommandIds?: readonly string[];\n putCursors?: readonly OfflineReplicaCursor[];\n /** Durable fatal-pull attentions to upsert for user+scope. */\n putPullAttentions?: readonly OfflinePullAttention[];\n /** Scopes whose fatal-pull attentions should be removed after a successful pull. */\n removePullAttentions?: readonly OfflineScope[];\n}\n\n/**\n * Read-only view of durable offline state that cannot observe an in-flight write transaction.\n *\n * Obtain via {@link OfflineRepository.runReadSnapshot}. Compose multiple reads through this\n * handle inside one callback; do not call {@link OfflineRepository.runReadSnapshot} recursively.\n */\nexport interface OfflineRepositoryReader {\n getLastUserId(): Promise<OfflinePrincipalId | null>;\n getSessionManifest<T>(userId: OfflinePrincipalId): Promise<T | null>;\n getReplicaRow<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null>;\n getReplicaRowIncludingPendingDelete?<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null>;\n getReplicaRows<TValues = unknown>(scope: OfflineScope, sourceKey: string): Promise<OfflineReplicaRow<TValues>[]>;\n getReplicaRowByRemoteId<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n remoteId: OfflineGeneratedRemoteId,\n ): Promise<OfflineReplicaRow<TValues> | null>;\n getReplicaRowByRemoteIdentity<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaRemoteIdentity,\n ): Promise<OfflineReplicaRow<TValues> | null>;\n getReplicaCursor(scope: OfflineScope): Promise<OfflineReplicaCursor | null>;\n getPullAttentions?(userId: OfflinePrincipalId): Promise<OfflinePullAttention[]>;\n getCommands(scope: OfflineScope): Promise<OfflineCommand[]>;\n getCommandsForUser?(userId: OfflinePrincipalId): Promise<OfflineCommand[]>;\n}\n\n/** Durable local replica and outbox persistence contract. */\nexport interface OfflineRepository {\n initialize(): Promise<void>;\n getLastUserId(): Promise<OfflinePrincipalId | null>;\n setLastUserId(userId: OfflinePrincipalId): Promise<void>;\n getSessionManifest<T>(userId: OfflinePrincipalId): Promise<T | null>;\n putSessionManifest<T>(userId: OfflinePrincipalId, value: T): Promise<void>;\n getReplicaRow<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null>;\n /** Internal durable lookup used by synchronization; includes pending-delete tombstones. */\n getReplicaRowIncludingPendingDelete?<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null>;\n getReplicaRows<TValues = unknown>(scope: OfflineScope, sourceKey: string): Promise<OfflineReplicaRow<TValues>[]>;\n getReplicaRowByRemoteId<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n remoteId: OfflineGeneratedRemoteId,\n ): Promise<OfflineReplicaRow<TValues> | null>;\n getReplicaRowByRemoteIdentity<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaRemoteIdentity,\n ): Promise<OfflineReplicaRow<TValues> | null>;\n getReplicaCursor(scope: OfflineScope): Promise<OfflineReplicaCursor | null>;\n /** Durable fatal-pull attentions for the principal, ordered by scope id. */\n getPullAttentions?(userId: OfflinePrincipalId): Promise<OfflinePullAttention[]>;\n getCommands(scope: OfflineScope): Promise<OfflineCommand[]>;\n getCommandsForUser?(userId: OfflinePrincipalId): Promise<OfflineCommand[]>;\n putCommand(command: OfflineCommand): Promise<void>;\n replaceCommand(command: OfflineCommand): Promise<void>;\n removeCommand(commandId: string): Promise<void>;\n /** Upserts a durable fatal-pull attention for user+scope. */\n putPullAttention?(attention: OfflinePullAttention): Promise<void>;\n /** Removes a durable fatal-pull attention for user+scope when present. */\n removePullAttention?(scope: OfflineScope): Promise<void>;\n clearUser(userId: OfflinePrincipalId): Promise<void>;\n clearScope(scope: OfflineScope): Promise<void>;\n transactReplica(transaction: OfflineReplicaTransaction): Promise<void>;\n /**\n * Runs `read` against a committed snapshot that cannot observe an in-flight write.\n *\n * Each call independently waits for prior writes, then holds a reader lease until `read`\n * settles so concurrent writers wait for all active readers. Compose multi-reads only via\n * the provided {@link OfflineRepositoryReader}; callers must not invoke `runReadSnapshot`\n * recursively from inside `read` (nested support is intentionally absent). Mutating APIs\n * must not be called from `read`.\n */\n runReadSnapshot<T>(read: (reader: OfflineRepositoryReader) => Promise<T>): Promise<T>;\n /** @internal Runs one optimistic read/derive/write operation with platform-specific concurrency validation. */\n [OFFLINE_REPOSITORY_ATOMIC_MUTATION]?<T>(operation: (repository: OfflineRepository) => Promise<T>): Promise<T>;\n}\n\n/** DI token for the selected platform repository. */\nexport const OFFLINE_REPOSITORY = new InjectionToken<OfflineRepository>('OFFLINE_REPOSITORY');\n\n/** Returns whether the platform uses the cross-process-safe native repository. */\nexport function supportsSynchronizedOfflineRepository(platform: string): boolean {\n return platform === 'ios' || platform === 'android';\n}\n\n/** Selects encrypted SQLite on native platforms and Ionic Storage elsewhere. */\nexport function selectOfflineRepository(\n platform: string,\n webRepository: OfflineRepository,\n nativeRepository: OfflineRepository,\n): OfflineRepository {\n return supportsSynchronizedOfflineRepository(platform) ? nativeRepository : webRepository;\n}\n\ninterface OfflineMetadata {\n schemaVersion: number;\n lastUserId: OfflinePrincipalId | null;\n replicaSchemaVersion: number | null;\n replicaSchemaHash: string | null;\n}\n\n/** Crash-recoverable journal for an in-flight web replica schema migration. */\ninterface OfflineReplicaSchemaMigrationJournal {\n originalRows: Record<string, OfflineReplicaRow>;\n fromVersion: number;\n fromHash: string;\n targetVersion: number;\n targetHash: string;\n}\n\nconst METADATA_KEY = 'offline:metadata';\nconst SESSION_MANIFESTS_KEY = 'offline:session:manifests';\nconst ROWS_KEY = 'offline:replica:rows';\nconst ROW_PARTITION_PREFIX = 'offline:replica:rows:index:v1:';\nconst ROW_PARTITION_READY_KEY = 'offline:replica:rows:index:v1:ready';\nconst CURSORS_KEY = 'offline:replica:cursors';\nconst OUTBOX_KEY = 'offline:outbox:commands';\nconst REPLICA_TRANSACTION_KEY = 'offline:replica:transaction';\nconst REPLICA_SCHEMA_MIGRATION_KEY = 'offline:replica:schema-migration';\n// Legacy marker storage is no longer read or written. Keep cleanup support for\n// databases created by released versions that persisted this key.\nconst RECONCILIATION_SCOPES_KEY = 'offline:replica:reconciliation-scopes';\nconst PULL_ATTENTIONS_KEY = 'offline:replica:pull-attentions';\n\nfunction compareOfflineCommands(left: OfflineCommand, right: OfflineCommand): number {\n return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);\n}\n\n/** WebはIonic StorageのIndexedDB driverを利用する。 */\n@Injectable({ providedIn: 'root' })\nexport class IonicOfflineRepository implements OfflineRepository {\n readonly #storage = inject(KitStorageService);\n readonly #options = inject(OFFLINE_KIT_OPTIONS);\n #initialization: Promise<void> | null = null;\n #writes: Promise<void> = settledRepositoryOperation();\n #activeReaders = 0;\n #readersIdle: Promise<void> = settledRepositoryOperation();\n #resolveReadersIdle: (() => void) | null = null;\n #rowIndexBuild: Promise<void> | null = null;\n\n initialize(): Promise<void> {\n if (!this.#initialization) {\n this.#initialization = this.#migrate().catch((error: unknown) => {\n this.#initialization = null;\n throw error;\n });\n }\n return this.#initialization;\n }\n\n async getLastUserId(): Promise<OfflinePrincipalId | null> {\n return this.#withCommittedRead(() => this.#readLastUserId());\n }\n\n async setLastUserId(userId: OfflinePrincipalId): Promise<void> {\n await this.initialize();\n await this.#enqueueWrite(async () => {\n await this.#storage.set<OfflineMetadata>(METADATA_KEY, { ...(await this.#metadata()), lastUserId: userId });\n });\n }\n\n async getSessionManifest<T>(userId: OfflinePrincipalId): Promise<T | null> {\n return this.#withCommittedRead(() => this.#readSessionManifest<T>(userId));\n }\n\n async putSessionManifest<T>(userId: OfflinePrincipalId, value: T): Promise<void> {\n await this.initialize();\n await this.#mutateRecord<T>(SESSION_MANIFESTS_KEY, (manifests) => {\n manifests[canonicalOfflinePrincipalId(userId)] = value;\n return manifests;\n });\n }\n\n async getReplicaRow<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n return this.#withCommittedRead(() => this.#readReplicaRow(scope, sourceKey, identity, false));\n }\n\n async getReplicaRowIncludingPendingDelete<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n return this.#withCommittedRead(() => this.#readReplicaRow(scope, sourceKey, identity, true));\n }\n\n async getReplicaRows<TValues = unknown>(scope: OfflineScope, sourceKey: string): Promise<OfflineReplicaRow<TValues>[]> {\n return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey));\n }\n\n async getReplicaRowByRemoteId<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n remoteId: OfflineGeneratedRemoteId,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated') return null;\n return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });\n }\n\n async getReplicaRowByRemoteIdentity<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaRemoteIdentity,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n return this.#withCommittedRead(() => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity));\n }\n\n async getReplicaCursor(scope: OfflineScope): Promise<OfflineReplicaCursor | null> {\n return this.#withCommittedRead(() => this.#readReplicaCursor(scope));\n }\n\n async getPullAttentions(userId: OfflinePrincipalId): Promise<OfflinePullAttention[]> {\n return this.#withCommittedRead(() => this.#readPullAttentions(userId));\n }\n\n async getCommands(scope: OfflineScope): Promise<OfflineCommand[]> {\n return this.#withCommittedRead(() => this.#readCommands(scope));\n }\n\n async getCommandsForUser(userId: OfflinePrincipalId): Promise<OfflineCommand[]> {\n return this.#withCommittedRead(() => this.#readCommandsForUser(userId));\n }\n\n async runReadSnapshot<T>(read: (reader: OfflineRepositoryReader) => Promise<T>): Promise<T> {\n return this.#withCommittedRead(() => read(this.#reader()));\n }\n\n #normalizeCommand(command: OfflineCommand): OfflineCommand {\n if (command.serverCommitUnknown !== undefined) return command;\n const legacyAmbiguousFailure = command.attempts >= 2 && ['blocked_auth', 'conflict', 'rejected'].includes(command.state);\n return command.state === 'sending' || command.state === 'retry_wait' || legacyAmbiguousFailure\n ? { ...command, serverCommitUnknown: true }\n : command;\n }\n\n async #readLastUserId(): Promise<OfflinePrincipalId | null> {\n return (await this.#metadata()).lastUserId;\n }\n\n async #readSessionManifest<T>(userId: OfflinePrincipalId): Promise<T | null> {\n const manifests = await this.#readRecord<T>(SESSION_MANIFESTS_KEY);\n return manifests[canonicalOfflinePrincipalId(userId)] ?? null;\n }\n\n async #readReplicaRow<TValues>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n includePendingDelete: boolean,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n const schema = this.#resolveReplicaEntitySchema(sourceKey);\n const rows = await this.#readRowPartition<TValues>(scope, sourceKey, schema);\n const row = this.#findRowByAddress(rows, scope, sourceKey, schema, identity);\n if (!row || (!includePendingDelete && (row.visibility ?? 'present') === 'pending_delete')) return null;\n return this.#rowForScope(row, schema, scope) as OfflineReplicaRow<TValues>;\n }\n\n async #readReplicaRows<TValues>(scope: OfflineScope, sourceKey: string): Promise<OfflineReplicaRow<TValues>[]> {\n const schema = this.#resolveReplicaEntitySchema(sourceKey);\n const rows = await this.#readRowPartition<TValues>(scope, sourceKey, schema);\n return Object.values(rows)\n .filter((row) => {\n if (row.sourceKey !== sourceKey || row.userId !== scope.userId) return false;\n if ((row.visibility ?? 'present') === 'pending_delete') return false;\n return schema.scope === 'partition' ? row.scopeId === scope.scopeId : true;\n })\n .map((row) => this.#rowForScope(row, schema, scope))\n .sort((left, right) => this.#compareReplicaIdentity(schema, left.identity, right.identity));\n }\n\n async #readReplicaRowByRemoteIdentity<TValues>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaRemoteIdentity,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n const schema = this.#resolveReplicaEntitySchema(sourceKey);\n const canonical = canonicalOfflineRemoteIdentity(schema, identity);\n const rows = await this.#readRowPartition<TValues>(scope, sourceKey, schema);\n const row = Object.values(rows).find((candidate) => {\n if (candidate.sourceKey !== sourceKey || candidate.userId !== scope.userId) return false;\n if (schema.scope === 'partition' && candidate.scopeId !== scope.scopeId) return false;\n const candidateIdentity = offlineReplicaRemoteIdentity(schema, candidate.identity);\n return candidateIdentity !== null && canonicalOfflineRemoteIdentity(schema, candidateIdentity) === canonical;\n });\n return row ? (this.#rowForScope(row, schema, scope) as OfflineReplicaRow<TValues>) : null;\n }\n\n async #readReplicaCursor(scope: OfflineScope): Promise<OfflineReplicaCursor | null> {\n const cursors = await this.#readRecord<string>(CURSORS_KEY);\n const cursor = cursors[this.#cursorKey(scope)];\n return cursor === undefined ? null : { ...scope, cursor };\n }\n\n async #readPullAttentions(userId: OfflinePrincipalId): Promise<OfflinePullAttention[]> {\n const attentions = await this.#readRecord<OfflinePullAttention>(PULL_ATTENTIONS_KEY);\n return Object.values(attentions)\n .filter((attention) => attention.userId === userId)\n .sort((left, right) => (left.scopeId < right.scopeId ? -1 : left.scopeId > right.scopeId ? 1 : 0));\n }\n\n async #readCommands(scope: OfflineScope): Promise<OfflineCommand[]> {\n const commands = await this.#readRecord<OfflineCommand>(OUTBOX_KEY);\n return Object.values(commands)\n .filter((command) => command.userId === scope.userId && command.scopeId === scope.scopeId)\n .map((command) => this.#normalizeCommand(command))\n .sort(compareOfflineCommands);\n }\n\n async #readCommandsForUser(userId: OfflinePrincipalId): Promise<OfflineCommand[]> {\n const commands = await this.#readRecord<OfflineCommand>(OUTBOX_KEY);\n return Object.values(commands)\n .filter((command) => command.userId === userId)\n .map((command) => this.#normalizeCommand(command))\n .sort(compareOfflineCommands);\n }\n\n #reader(): OfflineRepositoryReader {\n return {\n getLastUserId: () => this.#readLastUserId(),\n getSessionManifest: (userId) => this.#readSessionManifest(userId),\n getReplicaRow: (scope, sourceKey, identity) => this.#readReplicaRow(scope, sourceKey, identity, false),\n getReplicaRowIncludingPendingDelete: (scope, sourceKey, identity) => this.#readReplicaRow(scope, sourceKey, identity, true),\n getReplicaRows: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey),\n getReplicaRowByRemoteId: async (scope, sourceKey, remoteId) => {\n if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated') return null;\n return this.#readReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });\n },\n getReplicaRowByRemoteIdentity: (scope, sourceKey, identity) => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity),\n getReplicaCursor: (scope) => this.#readReplicaCursor(scope),\n getPullAttentions: (userId) => this.#readPullAttentions(userId),\n getCommands: (scope) => this.#readCommands(scope),\n getCommandsForUser: (userId) => this.#readCommandsForUser(userId),\n };\n }\n\n async #withCommittedRead<T>(operation: () => Promise<T>): Promise<T> {\n await this.initialize();\n // Finish index readiness first (may enqueue a write). Then await the latest write\n // tail and register the reader synchronously — no await gap for a writer to start.\n await this.#ensureRowPartitionsReady();\n await this.#writes;\n this.#beginReaders();\n const read = async (): Promise<T> => operation();\n return read().finally(() => this.#endReaders());\n }\n\n #beginReaders(): void {\n if (this.#activeReaders === 0) {\n this.#readersIdle = new Promise<void>((resolve) => {\n this.#resolveReadersIdle = resolve;\n });\n }\n this.#activeReaders += 1;\n }\n\n #endReaders(): void {\n this.#activeReaders -= 1;\n if (this.#activeReaders === 0) {\n this.#resolveReadersIdle?.();\n this.#resolveReadersIdle = null;\n this.#readersIdle = settledRepositoryOperation();\n }\n }\n\n async putCommand(command: OfflineCommand): Promise<void> {\n await this.initialize();\n await this.#assertReplicaSchemaLocked();\n await this.#mutateRecord<OfflineCommand>(OUTBOX_KEY, (commands) => {\n commands[command.commandId] = command;\n return commands;\n });\n }\n\n replaceCommand(command: OfflineCommand): Promise<void> {\n return this.putCommand(command);\n }\n\n async removeCommand(commandId: string): Promise<void> {\n await this.initialize();\n await this.#mutateRecord<OfflineCommand>(OUTBOX_KEY, (commands) => {\n delete commands[commandId];\n return commands;\n });\n }\n\n async putPullAttention(attention: OfflinePullAttention): Promise<void> {\n await this.initialize();\n await this.#mutateRecord<OfflinePullAttention>(PULL_ATTENTIONS_KEY, (attentions) => {\n attentions[this.#cursorKey(attention)] = attention;\n return attentions;\n });\n }\n\n async removePullAttention(scope: OfflineScope): Promise<void> {\n await this.initialize();\n await this.#mutateRecord<OfflinePullAttention>(PULL_ATTENTIONS_KEY, (attentions) => {\n delete attentions[this.#cursorKey(scope)];\n return attentions;\n });\n }\n\n async clearUser(userId: OfflinePrincipalId): Promise<void> {\n await this.initialize();\n await this.#enqueueWrite(async () => {\n await this.#removeRowPartitions((key) => key.startsWith(`${ROW_PARTITION_PREFIX}${canonicalOfflinePrincipalId(userId)}:`));\n await Promise.all([\n this.#mutateRecordNow(SESSION_MANIFESTS_KEY, (manifests) => {\n delete manifests[canonicalOfflinePrincipalId(userId)];\n return manifests;\n }),\n this.#filterRecordNow<OfflineReplicaRow>(ROWS_KEY, (value) => value.userId !== userId),\n this.#filterRecordNow<OfflineCommand>(OUTBOX_KEY, (value) => value.userId !== userId),\n this.#filterRecordNow<string>(CURSORS_KEY, (_value, key) => !key.startsWith(`${canonicalOfflinePrincipalId(userId)}:`)),\n this.#filterRecordNow<OfflineScope>(RECONCILIATION_SCOPES_KEY, (value) => value.userId !== userId),\n this.#filterRecordNow<OfflinePullAttention>(PULL_ATTENTIONS_KEY, (value) => value.userId !== userId),\n ]);\n const metadata = await this.#metadata();\n if (metadata.lastUserId === userId) {\n await this.#storage.set<OfflineMetadata>(METADATA_KEY, { ...metadata, lastUserId: null });\n }\n });\n }\n\n async clearScope(scope: OfflineScope): Promise<void> {\n await this.initialize();\n const belongsToGroup = (value: OfflineScope) => value.userId === scope.userId && value.scopeId === scope.scopeId;\n await this.#enqueueWrite(async () => {\n await this.#removeRowPartitions((key) => {\n if (!key.startsWith(`${ROW_PARTITION_PREFIX}${canonicalOfflinePrincipalId(scope.userId)}:`)) return false;\n return key.includes(`:partition:${encodeURIComponent(scope.scopeId)}:`);\n });\n await Promise.all([\n this.#filterRecordNow<OfflineReplicaRow>(ROWS_KEY, (value) => {\n const schema = this.#resolveReplicaEntitySchema(value.sourceKey);\n return schema.scope === 'user' || !belongsToGroup(value);\n }),\n this.#filterRecordNow<OfflineCommand>(OUTBOX_KEY, (value) => {\n const schema = this.#resolveReplicaEntitySchema(value.sourceKey);\n return schema.scope === 'user' || !belongsToGroup(value);\n }),\n this.#filterRecordNow<string>(CURSORS_KEY, (_value, key) => key !== this.#cursorKey(scope)),\n this.#filterRecordNow<OfflineScope>(RECONCILIATION_SCOPES_KEY, (value) => !belongsToGroup(value)),\n this.#filterRecordNow<OfflinePullAttention>(PULL_ATTENTIONS_KEY, (value) => !belongsToGroup(value)),\n ]);\n });\n }\n\n async transactReplica(transaction: OfflineReplicaTransaction): Promise<void> {\n await this.initialize();\n return this.#enqueueWrite(() => this.#applyReplicaTransaction(transaction, true));\n }\n\n async #migrate(): Promise<void> {\n const metadata = await this.#storage.get<Partial<OfflineMetadata>>(METADATA_KEY);\n if (metadata?.schemaVersion !== undefined && metadata.schemaVersion !== OFFLINE_SCHEMA_VERSION) {\n throw new Error(\n `Unsupported offline storage schema version ${metadata.schemaVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +\n 'A lossless core schema migration is required before this database can be opened.',\n );\n }\n\n const interruptedSchemaMigration = await this.#storage.get<OfflineReplicaSchemaMigrationJournal>(REPLICA_SCHEMA_MIGRATION_KEY);\n if (interruptedSchemaMigration) {\n await this.#recoverReplicaSchemaMigration(interruptedSchemaMigration);\n }\n\n const currentMetadata = await this.#metadata();\n await this.#initializeReplicaSchema(currentMetadata.replicaSchemaVersion, currentMetadata.replicaSchemaHash);\n\n const interrupted = await this.#storage.get<OfflineReplicaTransaction>(REPLICA_TRANSACTION_KEY);\n if (interrupted) await this.#applyReplicaTransaction(interrupted, false);\n }\n\n async #initializeReplicaSchema(storedVersion: number | null, storedHash: string | null): Promise<void> {\n const bundle = this.#options.replicaSchema;\n const targetVersion = bundle.version;\n const targetHash = await sha256OfflineReplicaSchema(bundle);\n\n if (storedVersion === null) {\n const metadata = await this.#metadata();\n await this.#storage.set<OfflineMetadata>(METADATA_KEY, {\n ...metadata,\n replicaSchemaVersion: targetVersion,\n replicaSchemaHash: targetHash,\n });\n return;\n }\n\n if (storedVersion === targetVersion && storedHash === targetHash) {\n return;\n }\n\n if (storedVersion === targetVersion) {\n throw new Error(\n `Offline replica schema hash mismatch at version ${targetVersion}. Reinstall the application or bump replicaSchema.version after intentional schema changes.`,\n );\n }\n\n if (storedVersion > targetVersion) {\n throw new Error(\n `Offline replica schema version ${storedVersion} is newer than application version ${targetVersion}. Upgrade the application before opening this database.`,\n );\n }\n\n if (storedHash === null) {\n throw new Error(`Offline replica schema metadata at version ${storedVersion} is missing its schema hash.`);\n }\n\n await this.#runReplicaSchemaMigration(storedVersion, storedHash, targetVersion, targetHash);\n }\n\n async #recoverReplicaSchemaMigration(journal: OfflineReplicaSchemaMigrationJournal): Promise<void> {\n await this.#removeRowPartitions(() => true);\n await this.#storage.set(ROWS_KEY, journal.originalRows);\n const metadata = await this.#metadata();\n await this.#storage.set<OfflineMetadata>(METADATA_KEY, {\n ...metadata,\n replicaSchemaVersion: journal.fromVersion,\n replicaSchemaHash: journal.fromHash,\n });\n await this.#storage.remove(REPLICA_SCHEMA_MIGRATION_KEY);\n }\n\n async #runReplicaSchemaMigration(fromVersion: number, fromHash: string, targetVersion: number, targetHash: string): Promise<void> {\n const bundle = this.#options.replicaSchema;\n for (let version = fromVersion; version < targetVersion; version++) {\n if (!bundle.migrations.some((migration) => migration.fromVersion === version)) {\n throw new Error(`Missing offline replica schema migration from version ${version} to ${version + 1}.`);\n }\n }\n\n return this.#enqueueWrite(async (): Promise<void> => {\n const rows = await this.#readRecord<OfflineReplicaRow>(ROWS_KEY);\n const originalRows = structuredClone(rows);\n await this.#storage.set<OfflineReplicaSchemaMigrationJournal>(REPLICA_SCHEMA_MIGRATION_KEY, {\n originalRows,\n fromVersion,\n fromHash,\n targetVersion,\n targetHash,\n });\n\n const commitMigration = async (): Promise<void> => {\n const transformedRows: Record<string, OfflineReplicaRow> = {};\n for (const row of Object.values(rows)) {\n let current: OfflineReplicaWebMigrationRow | null = this.#toWebMigrationRow(row);\n for (let version = fromVersion; version < targetVersion; version++) {\n if (current === null) break;\n const migration = bundle.migrations.find((candidate) => candidate.fromVersion === version);\n if (!migration) {\n throw new Error(`Missing offline replica schema migration from version ${version} to ${version + 1}.`);\n }\n current = await migration.migrateWebRow(current);\n }\n if (current === null) continue;\n\n const entitySchema = bundle.entities.find((entity) => entity.sourceKey === current!.sourceKey);\n if (!entitySchema) {\n throw new Error(`Unknown offline replica source key \"${current!.sourceKey}\" after schema migration.`);\n }\n encodeOfflineReplicaValues(entitySchema, current!.values);\n if (current!.confirmedValues !== null) {\n encodeOfflineReplicaValues(entitySchema, current!.confirmedValues);\n }\n\n const transformedRow: OfflineReplicaRow = {\n ...row,\n sourceKey: current!.sourceKey,\n values: projectOfflineReplicaValues(entitySchema, current!.values),\n confirmedValues: current!.confirmedValues === null ? null : projectOfflineReplicaValues(entitySchema, current!.confirmedValues),\n };\n const transformedKey = this.#rowKey(transformedRow);\n if (transformedRows[transformedKey]) {\n throw new Error(`Replica schema migration produced duplicate row key \"${transformedKey}\".`);\n }\n transformedRows[transformedKey] = transformedRow;\n }\n\n const metadata = await this.#metadata();\n await this.#storage.set(ROWS_KEY, transformedRows);\n await this.#removeRowPartitions(() => true);\n await this.#storage.set<OfflineMetadata>(METADATA_KEY, {\n ...metadata,\n replicaSchemaVersion: targetVersion,\n replicaSchemaHash: targetHash,\n });\n await this.#storage.remove(REPLICA_SCHEMA_MIGRATION_KEY);\n };\n await commitMigration().catch(async (error: unknown) => {\n await this.#recoverReplicaSchemaMigration({\n originalRows,\n fromVersion,\n fromHash,\n targetVersion,\n targetHash,\n });\n throw error;\n });\n });\n }\n\n #toWebMigrationRow(row: OfflineReplicaRow): OfflineReplicaWebMigrationRow {\n return {\n sourceKey: row.sourceKey,\n values: structuredClone(row.values as Record<string, unknown>),\n confirmedValues: row.confirmedValues === null ? null : structuredClone(row.confirmedValues as Record<string, unknown>),\n };\n }\n\n async #assertReplicaSchemaLocked(): Promise<void> {\n const bundle = this.#options.replicaSchema;\n const metadata = await this.#metadata();\n const targetHash = await sha256OfflineReplicaSchema(bundle);\n if (metadata.replicaSchemaVersion === null) {\n throw new Error('Offline replica schema metadata is not initialized.');\n }\n if (metadata.replicaSchemaVersion !== bundle.version) {\n throw new Error(\n `Offline replica schema version ${metadata.replicaSchemaVersion} does not match application version ${bundle.version}.`,\n );\n }\n if (metadata.replicaSchemaHash !== targetHash) {\n throw new Error(\n `Offline replica schema hash mismatch at version ${bundle.version}. Reinstall the application or bump replicaSchema.version after intentional schema changes.`,\n );\n }\n }\n\n async #applyReplicaTransaction(transaction: OfflineReplicaTransaction, journal: boolean): Promise<void> {\n await this.#assertReplicaSchemaLocked();\n for (const row of transaction.putRows ?? []) this.#validateReplicaRow(row);\n const [rows, commands, cursors, pullAttentions] = await Promise.all([\n this.#readRecord<OfflineReplicaRow>(ROWS_KEY),\n this.#readRecord<OfflineCommand>(OUTBOX_KEY),\n this.#readRecord<string>(CURSORS_KEY),\n this.#readRecord<OfflinePullAttention>(PULL_ATTENTIONS_KEY),\n ]);\n const identityCheckRows = { ...rows };\n const releases = new Map<string, OfflineReplicaRemoteIdRelease>();\n for (const release of transaction.releaseRemoteIds ?? []) {\n this.#assertValidReleaseRemoteId(release.remoteId);\n const key = this.#rowKey(release);\n if (releases.has(key)) {\n throw new Error(\n `Offline replica remoteId release is duplicated for ${release.sourceKey}/${canonicalOfflineReplicaIdentity(release.identity)}.`,\n );\n }\n releases.set(key, release);\n }\n const consumedReleases = new Set<string>();\n for (const row of transaction.putRows ?? []) {\n const key = this.#rowKey(row);\n const existing = identityCheckRows[key];\n const release = releases.get(key);\n if (!existing && release) {\n throw new Error(\n `Offline replica remoteId release requires an existing row for ${row.sourceKey}/${canonicalOfflineReplicaIdentity(row.identity)}.`,\n );\n }\n if (existing) this.#assertReplicaIdentityAssignment(existing, row, release);\n if (release) consumedReleases.add(key);\n this.#assertUniqueReplicaIdentity(identityCheckRows, row);\n identityCheckRows[key] = row;\n }\n if (consumedReleases.size !== releases.size) {\n throw new Error('Offline replica remoteId release must match an existing row in putRows.');\n }\n if (journal) await this.#storage.set(REPLICA_TRANSACTION_KEY, transaction);\n for (const row of transaction.putRows ?? []) {\n const schema = this.#resolveReplicaEntitySchema(row.sourceKey);\n rows[this.#rowKey(row)] = {\n ...row,\n scopeId: schema.scope === 'user' ? '' : row.scopeId,\n values: projectOfflineReplicaValues(schema, row.values),\n confirmedValues: row.confirmedValues === null ? null : projectOfflineReplicaValues(schema, row.confirmedValues),\n };\n }\n for (const row of transaction.removeRows ?? []) {\n delete rows[this.#rowKey(row)];\n }\n for (const command of transaction.putCommands ?? []) commands[command.commandId] = command;\n for (const commandId of transaction.removeCommandIds ?? []) delete commands[commandId];\n for (const cursor of transaction.putCursors ?? []) {\n cursors[this.#cursorKey(cursor)] = cursor.cursor;\n }\n for (const attention of transaction.putPullAttentions ?? []) {\n pullAttentions[this.#cursorKey(attention)] = attention;\n }\n for (const scope of transaction.removePullAttentions ?? []) {\n delete pullAttentions[this.#cursorKey(scope)];\n }\n await Promise.all([\n this.#storage.set(ROWS_KEY, rows),\n this.#storage.set(OUTBOX_KEY, commands),\n this.#storage.set(CURSORS_KEY, cursors),\n this.#storage.set(PULL_ATTENTIONS_KEY, pullAttentions),\n ]);\n await this.#writeAffectedRowPartitions(rows, transaction);\n await this.#storage.remove(REPLICA_TRANSACTION_KEY);\n }\n\n async #readRowPartition<TValues>(\n scope: OfflineScope,\n sourceKey: string,\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n ): Promise<Record<string, OfflineReplicaRow<TValues>>> {\n const key = this.#rowPartitionKey(scope, sourceKey, schema);\n const cached = await this.#storage.get<Record<string, OfflineReplicaRow<TValues>>>(key);\n if (cached !== null) return cached;\n if (await this.#storage.get<boolean>(ROW_PARTITION_READY_KEY)) return {};\n // Non-mutating fallback under a reader lease (indexes are normally built before the lease).\n return this.#legacyRowPartition(scope, sourceKey, schema);\n }\n\n async #legacyRowPartition<TValues>(\n scope: OfflineScope,\n sourceKey: string,\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n ): Promise<Record<string, OfflineReplicaRow<TValues>>> {\n const rows = await this.#readRecord<OfflineReplicaRow<TValues>>(ROWS_KEY);\n return Object.fromEntries(\n Object.entries(rows).filter(([, row]) => {\n if (row.userId !== scope.userId || row.sourceKey !== sourceKey) return false;\n return schema.scope === 'user' || row.scopeId === scope.scopeId;\n }),\n );\n }\n\n async #ensureRowPartitionsReady(): Promise<void> {\n if (await this.#storage.get<boolean>(ROW_PARTITION_READY_KEY)) return;\n await this.#buildRowPartitions();\n }\n\n #buildRowPartitions(): Promise<void> {\n if (!this.#rowIndexBuild) {\n const run = async (): Promise<void> => {\n if (await this.#storage.get<boolean>(ROW_PARTITION_READY_KEY)) return;\n const rows = await this.#readRecord<OfflineReplicaRow>(ROWS_KEY);\n const partitions = new Map<string, Record<string, OfflineReplicaRow>>();\n for (const [rowKey, row] of Object.entries(rows)) {\n const schema = this.#resolveReplicaEntitySchema(row.sourceKey);\n const key = this.#rowPartitionKey(row, row.sourceKey, schema);\n const partition = partitions.get(key) ?? {};\n partition[rowKey] = row;\n partitions.set(key, partition);\n }\n await Promise.all([...partitions].map(([key, partition]) => this.#storage.set(key, partition)));\n await this.#storage.set(ROW_PARTITION_READY_KEY, true);\n };\n const build = this.#enqueueWrite(run);\n this.#rowIndexBuild = build.finally(() => {\n this.#rowIndexBuild = null;\n });\n }\n return this.#rowIndexBuild;\n }\n\n async #writeAffectedRowPartitions(rows: Record<string, OfflineReplicaRow>, transaction: OfflineReplicaTransaction): Promise<void> {\n const affected = new Map<\n string,\n { scope: OfflineScope; sourceKey: string; schema: OfflineReplicaEntitySchema<Record<string, unknown>> }\n >();\n for (const row of [...(transaction.putRows ?? []), ...(transaction.removeRows ?? [])]) {\n const schema = this.#resolveReplicaEntitySchema(row.sourceKey);\n const key = this.#rowPartitionKey(row, row.sourceKey, schema);\n affected.set(key, { scope: row, sourceKey: row.sourceKey, schema });\n }\n await Promise.all(\n [...affected].map(([key, { scope, sourceKey, schema }]) =>\n this.#storage.set(\n key,\n Object.fromEntries(\n Object.entries(rows).filter(([, row]) => {\n if (row.userId !== scope.userId || row.sourceKey !== sourceKey) return false;\n return schema.scope === 'user' || row.scopeId === scope.scopeId;\n }),\n ),\n ),\n ),\n );\n }\n\n #rowPartitionKey(scope: OfflineScope, sourceKey: string, schema: OfflineReplicaEntitySchema<Record<string, unknown>>): string {\n const partition = schema.scope === 'user' ? 'user' : `partition:${encodeURIComponent(scope.scopeId)}`;\n return `${ROW_PARTITION_PREFIX}${canonicalOfflinePrincipalId(scope.userId)}:${partition}:${encodeURIComponent(sourceKey)}`;\n }\n\n async #removeRowPartitions(matches: (key: string) => boolean): Promise<void> {\n const keys = (await this.#storage.keys()).filter((key) => key.startsWith(ROW_PARTITION_PREFIX) && matches(key));\n await Promise.all(keys.map((key) => this.#storage.remove(key)));\n }\n\n async #metadata(): Promise<OfflineMetadata> {\n const metadata = await this.#storage.get<Partial<OfflineMetadata>>(METADATA_KEY);\n return {\n schemaVersion: metadata?.schemaVersion ?? OFFLINE_SCHEMA_VERSION,\n lastUserId: metadata?.lastUserId ?? null,\n replicaSchemaVersion: metadata?.replicaSchemaVersion ?? null,\n replicaSchemaHash: metadata?.replicaSchemaHash ?? null,\n };\n }\n\n async #readRecord<T>(key: string): Promise<Record<string, T>> {\n return (await this.#storage.get<Record<string, T>>(key)) ?? {};\n }\n\n #filterRecordNow<T>(key: string, predicate: (value: T, recordKey: string) => boolean): Promise<void> {\n return this.#mutateRecordNow<T>(key, (record) =>\n Object.fromEntries(Object.entries(record).filter(([recordKey, value]) => predicate(value, recordKey))),\n );\n }\n\n #mutateRecord<T>(key: string, mutate: (record: Record<string, T>) => Record<string, T>): Promise<void> {\n return this.#enqueueWrite(() => this.#mutateRecordNow(key, mutate));\n }\n\n async #mutateRecordNow<T>(key: string, mutate: (record: Record<string, T>) => Record<string, T>): Promise<void> {\n const record = await this.#readRecord<T>(key);\n await this.#storage.set(key, mutate(record));\n }\n\n #enqueueWrite<T>(operation: () => Promise<T>): Promise<T> {\n const write = this.#writes.then(async () => {\n if (this.#activeReaders > 0) await this.#readersIdle;\n return operation();\n });\n this.#writes = write.then(\n () => undefined,\n () => undefined,\n );\n return write;\n }\n\n #rowKey(row: OfflineScope & { sourceKey: string; identity: OfflineReplicaIdentity }): string {\n const schema = this.#resolveReplicaEntitySchema(row.sourceKey);\n return canonicalOfflineReplicaRowKey(schema, row);\n }\n\n #findRowByAddress<TValues>(\n rows: Record<string, OfflineReplicaRow<TValues>>,\n scope: OfflineScope,\n sourceKey: string,\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n identity: OfflineReplicaAddress,\n ): OfflineReplicaRow<TValues> | undefined {\n return Object.values(rows).find((row) => {\n if (row.sourceKey !== sourceKey || row.userId !== scope.userId) return false;\n if (schema.scope === 'partition' && row.scopeId !== scope.scopeId) return false;\n if (identity.kind === 'generated') {\n return row.identity.kind === 'generated' && row.identity.localId === identity.localId;\n }\n if (identity.kind === 'local') {\n return row.identity.kind === 'local' && row.identity.localId === identity.localId;\n }\n if (row.identity.kind !== 'natural') return false;\n return (\n canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) ===\n canonicalOfflineRemoteIdentity(schema, { naturalKey: normalizeOfflineNaturalKey(schema, identity.naturalKey) })\n );\n });\n }\n\n #rowForScope<TValues>(\n row: OfflineReplicaRow<TValues>,\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n scope: OfflineScope,\n ): OfflineReplicaRow<TValues> {\n const normalized = { ...row, visibility: row.visibility ?? ('present' as const) };\n return schema.scope === 'user' ? { ...normalized, scopeId: scope.scopeId } : normalized;\n }\n\n #cursorKey(scope: OfflineScope): string {\n return `${canonicalOfflinePrincipalId(scope.userId)}:${scope.scopeId}`;\n }\n\n #compareReplicaIdentity(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n left: import('./offline-identity').OfflineReplicaIdentity,\n right: import('./offline-identity').OfflineReplicaIdentity,\n ): number {\n if (left.kind === 'natural' && right.kind === 'natural' && schema.identity.kind === 'naturalKey') {\n const leftKey = normalizeOfflineNaturalKey(schema, left.naturalKey);\n const rightKey = normalizeOfflineNaturalKey(schema, right.naturalKey);\n for (const sourceKey of schema.identity.sourceKeys) {\n const leftValue = leftKey[sourceKey]!;\n const rightValue = rightKey[sourceKey]!;\n if (leftValue === rightValue) continue;\n if (typeof leftValue === 'number' && typeof rightValue === 'number') {\n return leftValue < rightValue ? -1 : 1;\n }\n return compareUtf8Binary(String(leftValue), String(rightValue));\n }\n return 0;\n }\n const leftId = left.kind === 'natural' ? canonicalOfflineReplicaIdentity(left) : left.localId;\n const rightId = right.kind === 'natural' ? canonicalOfflineReplicaIdentity(right) : right.localId;\n return compareUtf8Binary(leftId, rightId);\n }\n\n #validateReplicaRow(row: OfflineReplicaRow): void {\n const schema = this.#resolveReplicaEntitySchema(row.sourceKey);\n this.#validateRowIdentity(schema, row);\n encodeOfflineReplicaValues(schema, row.values);\n if (row.confirmedValues !== null) encodeOfflineReplicaValues(schema, row.confirmedValues);\n assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);\n }\n\n #validateRowIdentity(schema: OfflineReplicaEntitySchema<Record<string, unknown>>, row: OfflineReplicaRow): void {\n if (schema.identity.kind === 'localOnly') {\n if (row.identity.kind !== 'local') {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" requires local identity.`);\n }\n return;\n }\n if (schema.identity.kind === 'generated') {\n if (row.identity.kind !== 'generated') {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" requires generated identity.`);\n }\n assertOfflineReplicaGeneratedRemoteId(schema, row.identity.remoteId);\n return;\n }\n if (schema.identity.kind === 'naturalKey') {\n if (row.identity.kind !== 'natural') {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" requires natural identity.`);\n }\n const fromValues = offlineNaturalKeyFromValues(schema, row.values)!;\n if (\n canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) !==\n canonicalOfflineRemoteIdentity(schema, { naturalKey: fromValues })\n ) {\n throw new Error(`Offline replica identity naturalKey must match values for \"${schema.sourceKey}\".`);\n }\n }\n }\n\n #assertUniqueReplicaIdentity(rows: Record<string, OfflineReplicaRow>, incoming: OfflineReplicaRow): void {\n const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);\n const identity = offlineReplicaRemoteIdentity(schema, incoming.identity);\n if (identity === null) return;\n const canonical = canonicalOfflineRemoteIdentity(schema, identity);\n const incomingKey = this.#rowKey(incoming);\n const collision = Object.entries(rows).find(([key, row]) => {\n if (key === incomingKey) return false;\n if (row.userId !== incoming.userId || row.sourceKey !== incoming.sourceKey) return false;\n if (schema.scope === 'partition' && row.scopeId !== incoming.scopeId) return false;\n const rowIdentity = offlineReplicaRemoteIdentity(schema, row.identity);\n return rowIdentity !== null && canonicalOfflineRemoteIdentity(schema, rowIdentity) === canonical;\n });\n if (collision) {\n if (schema.identity.kind === 'generated') {\n const remoteId = incoming.identity.kind === 'generated' ? incoming.identity.remoteId : null;\n const mapped =\n collision[1].identity.kind === 'generated'\n ? collision[1].identity.localId\n : canonicalOfflineReplicaIdentity(collision[1].identity);\n throw new Error(`Offline replica remote id ${String(remoteId)} is already mapped to ${mapped}.`);\n }\n throw new Error(`Offline replica remote identity is already mapped to another row.`);\n }\n }\n\n #assertReplicaIdentityAssignment(\n existing: OfflineReplicaRow,\n incoming: OfflineReplicaRow,\n release: OfflineReplicaRemoteIdRelease | undefined,\n ): void {\n const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);\n if (release && schema.identity.kind !== 'generated') {\n throw new Error(`Offline replica remoteId release is unsupported for source \"${incoming.sourceKey}\".`);\n }\n if (schema.identity.kind === 'localOnly') {\n if (existing.identity.kind !== 'local' || incoming.identity.kind !== 'local') {\n throw new Error(`Offline replica local identity is required for \"${incoming.sourceKey}\".`);\n }\n if (existing.identity.localId !== incoming.identity.localId) {\n throw new Error(`Offline replica localId is immutable for \"${schema.sourceKey}\".`);\n }\n return;\n }\n if (schema.identity.kind === 'generated') {\n if (existing.identity.kind !== 'generated' || incoming.identity.kind !== 'generated') {\n throw new Error(`Offline replica generated identity is required for \"${incoming.sourceKey}\".`);\n }\n if (release) {\n if (existing.identity.remoteId !== release.remoteId || incoming.identity.remoteId !== null) {\n throw new Error(\n `Offline replica remoteId release must transition current=${String(existing.identity.remoteId)} to incoming=null for ${incoming.sourceKey}/${incoming.identity.localId}.`,\n );\n }\n return;\n }\n if (existing.identity.localId !== incoming.identity.localId) {\n throw new Error(`Offline replica localId is immutable for \"${schema.sourceKey}\".`);\n }\n if (existing.identity.remoteId !== null && existing.identity.remoteId !== incoming.identity.remoteId) {\n throw new Error(\n `Offline replica remoteId is immutable: current=${String(existing.identity.remoteId)}, incoming=${String(incoming.identity.remoteId)}.`,\n );\n }\n return;\n }\n if (schema.identity.kind === 'naturalKey') {\n if (existing.identity.kind !== 'natural' || incoming.identity.kind !== 'natural') {\n throw new Error(`Offline replica natural identity is required for \"${schema.sourceKey}\".`);\n }\n const current = canonicalOfflineRemoteIdentity(schema, { naturalKey: existing.identity.naturalKey });\n const next = canonicalOfflineRemoteIdentity(schema, { naturalKey: incoming.identity.naturalKey });\n if (current !== next) throw new Error(`Offline replica naturalKey is immutable for \"${schema.sourceKey}\".`);\n }\n }\n\n #assertValidReleaseRemoteId(remoteId: OfflineGeneratedRemoteId): void {\n if (typeof remoteId === 'number') {\n if (!Number.isSafeInteger(remoteId) || remoteId <= 0) {\n throw new Error(`Offline replica release has invalid remoteId ${String(remoteId)}.`);\n }\n return;\n }\n if (typeof remoteId !== 'string' || remoteId.length === 0) {\n throw new Error(`Offline replica release has invalid remoteId ${String(remoteId)}.`);\n }\n }\n\n #resolveReplicaEntitySchema(sourceKey: string): OfflineReplicaEntitySchema<Record<string, unknown>> {\n const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);\n if (!schema) throw new Error(`Unknown offline replica source key \"${sourceKey}\".`);\n return schema;\n }\n}\n\nfunction compareUtf8Binary(left: string, right: string): number {\n const leftBytes = new TextEncoder().encode(left);\n const rightBytes = new TextEncoder().encode(right);\n const length = Math.min(leftBytes.length, rightBytes.length);\n for (let index = 0; index < length; index += 1) {\n if (leftBytes[index] !== rightBytes[index]) return leftBytes[index]! < rightBytes[index]! ? -1 : 1;\n }\n return leftBytes.length < rightBytes.length ? -1 : leftBytes.length > rightBytes.length ? 1 : 0;\n}\n","import { inject, Injectable } from '@angular/core';\nimport {\n OFFLINE_AGGREGATE_INTENT_PROJECTOR,\n isOfflineAggregateIntentConflict,\n type OfflineAggregateIntentProjectInput,\n type OfflineAggregateIntentProjection,\n type OfflineAggregateIntentProjectResult,\n} from './offline-aggregate-intent-projector';\nimport { canonicalOfflineReplicaIdentity, commandIdentityMatchesReplicaRow, type OfflineCommandIdentity } from './offline-identity';\nimport { OFFLINE_KIT_OPTIONS } from './offline-kit-options';\nimport { OFFLINE_REPOSITORY_ATOMIC_MUTATION } from './offline-repository-concurrency';\nimport {\n OFFLINE_REPOSITORY,\n canonicalOfflineReplicaRowKey,\n type OfflineCommand,\n type OfflineReplicaRow,\n type OfflineReplicaRowKey,\n type OfflineRepository,\n type OfflineScope,\n} from './offline-repository';\nimport type { OfflineReplicaEntitySchema } from './offline-replica-schema';\n\nconst settledMutation = async (): Promise<void> => undefined;\n\n/**\n * Serializes only local replica read/derive/write critical sections. Network\n * transport must stay outside this coordinator so synchronization never holds\n * the local mutation lane while waiting on I/O.\n *\n * This coordinator is the sole caller and validator of aggregate rematerialization.\n * Invoke {@link projectAggregateIntent} only from inside {@link run}; this\n * method does not acquire the lane itself.\n */\n@Injectable({ providedIn: 'root' })\nexport class OfflineReplicaMutationCoordinator {\n readonly #repository = inject(OFFLINE_REPOSITORY, { optional: true });\n readonly #projector = inject(OFFLINE_AGGREGATE_INTENT_PROJECTOR, { optional: true });\n readonly #options = inject(OFFLINE_KIT_OPTIONS, { optional: true });\n #tail: Promise<void> = settledMutation();\n\n /** Enqueues one local replica critical section behind any in-flight mutation. */\n run<T>(operation: (repository: OfflineRepository) => Promise<T>): Promise<T> {\n const mutation = this.#tail.then(() => {\n if (!this.#repository) throw new Error('Offline repository is not configured.');\n const atomicMutation = this.#repository?.[OFFLINE_REPOSITORY_ATOMIC_MUTATION];\n return atomicMutation ? (atomicMutation.call(this.#repository, operation) as Promise<T>) : operation(this.#repository);\n });\n this.#tail = mutation.then(\n () => undefined,\n () => undefined,\n );\n return mutation;\n }\n\n /** Resolves after every currently queued replica mutation has settled. */\n async drain(): Promise<void> {\n await this.#tail;\n }\n\n /**\n * Calls the product aggregate-intent projector and validates scope, schema,\n * identity, and footprints. Throws before returning when the projector is\n * missing or the projection is unsafe to write.\n *\n * @param input - Authoritative base row, current localOnly rows, and remaining commands.\n */\n projectAggregateIntent(input: OfflineAggregateIntentProjectInput): OfflineAggregateIntentProjectResult {\n if (!this.#projector) {\n throw new Error('Offline aggregate intent projector is not configured.');\n }\n if (!this.#options) {\n throw new Error('Offline aggregate intent projector requires replica schema configuration.');\n }\n const projection = this.#projector.project(input);\n if (isOfflineAggregateIntentConflict(projection)) {\n if (input.trigger !== 'pull' || input.commands.length === 0 || projection.reason.length === 0) {\n throw new Error('Offline aggregate intent conflict is valid only for pending commands during pull.');\n }\n return projection;\n }\n this.#assertAggregateIntentProjection(input, projection);\n return projection;\n }\n\n #assertAggregateIntentProjection(input: OfflineAggregateIntentProjectInput, projection: OfflineAggregateIntentProjection): void {\n const expected = this.#expectedAggregate(input);\n const footprint = this.#localOnlyFootprint(input);\n this.#assertBaseProjection(input, projection, expected);\n this.#assertLocalOnlyProjection(input, expected.scope, footprint, projection);\n }\n\n #expectedAggregate(input: OfflineAggregateIntentProjectInput): {\n scope: OfflineScope | null;\n sourceKey: string | null;\n commandIdentity: OfflineCommandIdentity | null;\n } {\n const command = input.commands[0] ?? null;\n const base = input.baseRow;\n const local = input.localOnlyRows[0] ?? null;\n const scope = base\n ? { userId: base.userId, scopeId: base.scopeId }\n : command\n ? { userId: command.userId, scopeId: command.scopeId }\n : local\n ? { userId: local.userId, scopeId: local.scopeId }\n : null;\n return {\n scope,\n sourceKey: base?.sourceKey ?? command?.sourceKey ?? null,\n commandIdentity: command?.identity ?? null,\n };\n }\n\n #assertBaseProjection(\n input: OfflineAggregateIntentProjectInput,\n projection: OfflineAggregateIntentProjection,\n expected: {\n scope: OfflineScope | null;\n sourceKey: string | null;\n commandIdentity: OfflineCommandIdentity | null;\n },\n ): void {\n const remaining = input.commands;\n const base = input.baseRow;\n if (remaining.length === 0) {\n if (base?.confirmedValues == null) {\n if (projection.baseRow !== null) {\n throw new Error('Offline aggregate intent projector must remove a base row whose confirmedValues are null.');\n }\n return;\n }\n this.#assertBaseRowIdentity(expected, projection.baseRow, base);\n if (!sameJson(projection.baseRow!.values, base.confirmedValues)) {\n throw new Error('Offline aggregate intent projector must restore confirmed values when no commands remain.');\n }\n if (projection.baseRow!.syncState !== 'confirmed' || (projection.baseRow!.visibility ?? 'present') !== 'present') {\n throw new Error('Offline aggregate intent projector must restore a confirmed present base row when no commands remain.');\n }\n return;\n }\n if (!projection.baseRow) {\n throw new Error('Offline aggregate intent projector must return a base row while pending commands remain.');\n }\n this.#assertBaseRowIdentity(expected, projection.baseRow, base);\n const last = remaining.at(-1)!;\n if (projection.baseRow.syncState !== 'pending') {\n throw new Error('Offline aggregate intent projector must keep a pending base row while commands remain.');\n }\n const expectedVisibility = last.replicaMutation === 'delete' ? 'pending_delete' : 'present';\n if ((projection.baseRow.visibility ?? 'present') !== expectedVisibility) {\n throw new Error('Offline aggregate intent projector must match remaining replica visibility.');\n }\n }\n\n #assertBaseRowIdentity(\n expected: {\n scope: OfflineScope | null;\n sourceKey: string | null;\n commandIdentity: OfflineCommandIdentity | null;\n },\n row: OfflineReplicaRow | null,\n inputBase: OfflineReplicaRow | null,\n ): void {\n if (!row || !expected.scope || !expected.sourceKey) {\n throw new Error('Offline aggregate intent projector base row must keep the aggregate identity.');\n }\n const schema = this.#entitySchema(expected.sourceKey);\n if (schema.identity.kind === 'localOnly') {\n throw new Error(`Offline aggregate intent projector cannot rematerialize localOnly source \"${expected.sourceKey}\".`);\n }\n if (row.userId !== expected.scope.userId || row.scopeId !== expected.scope.scopeId || row.sourceKey !== expected.sourceKey) {\n throw new Error('Offline aggregate intent projector base row must use the current scope and source.');\n }\n if (inputBase) {\n if (!sameJson(row.confirmedValues, inputBase.confirmedValues) || row.serverRevision !== inputBase.serverRevision) {\n throw new Error('Offline aggregate intent projector base row must keep confirmedValues.');\n }\n if (canonicalOfflineReplicaIdentity(row.identity) !== canonicalOfflineReplicaIdentity(inputBase.identity)) {\n throw new Error('Offline aggregate intent projector base row must keep the aggregate identity.');\n }\n return;\n }\n if (row.confirmedValues !== null) {\n throw new Error('Offline aggregate intent projector base row must keep confirmedValues.');\n }\n if (!expected.commandIdentity || !commandIdentityMatchesReplicaRow(schema, row, expected.commandIdentity)) {\n throw new Error('Offline aggregate intent projector base row must keep the aggregate identity.');\n }\n }\n\n #assertLocalOnlyProjection(\n input: OfflineAggregateIntentProjectInput,\n scope: OfflineScope | null,\n footprint: ReadonlySet<string>,\n projection: OfflineAggregateIntentProjection,\n ): void {\n const currentByKey = new Map(\n input.localOnlyRows.map((row) => [canonicalOfflineReplicaRowKey(this.#entitySchema(row.sourceKey), row), row] as const),\n );\n const putRows = projection.putLocalOnlyRows ?? [];\n const removeRows = projection.removeLocalOnlyRows ?? [];\n const seen = new Set<string>();\n for (const row of putRows) {\n const key = this.#assertLocalOnlyMutation(scope, footprint, row);\n if (seen.has(key)) throw new Error(`Offline aggregate intent projector contains duplicate localOnly row ${key}.`);\n const current = currentByKey.get(key);\n if (!sameJson(row.confirmedValues, current?.confirmedValues ?? null)) {\n throw new Error('Offline aggregate intent projector localOnly rows must keep confirmedValues.');\n }\n seen.add(key);\n }\n for (const row of removeRows) {\n const key = this.#assertLocalOnlyMutation(scope, footprint, row);\n if (seen.has(key)) throw new Error(`Offline aggregate intent projector contains duplicate localOnly row ${key}.`);\n seen.add(key);\n }\n if (seen.size !== footprint.size) {\n throw new Error('Offline aggregate intent projector must cover every localOnly footprint exactly once.');\n }\n }\n\n #assertLocalOnlyMutation(scope: OfflineScope | null, footprint: ReadonlySet<string>, row: OfflineReplicaRowKey): string {\n const schema = this.#entitySchema(row.sourceKey);\n if (schema.identity.kind !== 'localOnly') {\n throw new Error(`Offline aggregate intent projector may only mutate localOnly source \"${row.sourceKey}\".`);\n }\n if (!scope || row.userId !== scope.userId || row.scopeId !== scope.scopeId || row.identity.kind !== 'local') {\n throw new Error('Offline aggregate intent projector rows must use the current scope and local identity.');\n }\n const key = canonicalOfflineReplicaRowKey(schema, row);\n if (!footprint.has(key)) {\n throw new Error(`Offline aggregate intent projector changed undeclared localOnly row ${key}.`);\n }\n return key;\n }\n\n #localOnlyFootprint(input: OfflineAggregateIntentProjectInput): Set<string> {\n const keys = new Set<string>();\n for (const row of input.localOnlyRows) {\n keys.add(canonicalOfflineReplicaRowKey(this.#entitySchema(row.sourceKey), row));\n }\n for (const command of input.commands) {\n for (const key of commandFootprintKeys(command)) {\n keys.add(canonicalOfflineReplicaRowKey(this.#entitySchema(key.sourceKey), key));\n }\n }\n return keys;\n }\n\n #entitySchema(sourceKey: string): OfflineReplicaEntitySchema<Record<string, unknown>> {\n const schema = this.#options?.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);\n if (!schema) throw new Error(`Unknown offline replica source key \"${sourceKey}\".`);\n return schema;\n }\n}\n\n/** Declared localOnly keys persisted on one Outbox command. */\nexport function commandFootprintKeys(command: Pick<OfflineCommand, 'localOnlyFootprint'>): readonly OfflineReplicaRowKey[] {\n return command.localOnlyFootprint ?? [];\n}\n\nfunction sameJson(left: unknown, right: unknown): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n","import { inject, Injectable } from '@angular/core';\nimport { isOfflineAggregateIntentConflict, offlineAggregateIntentMutations } from './offline-aggregate-intent-projector';\nimport { OFFLINE_COMMAND_HOOKS } from './offline-command-hooks';\nimport { OFFLINE_KIT_OPTIONS } from './offline-kit-options';\nimport { offlineCommandWithBaseRevision } from './offline-command-executor';\nimport { commandFootprintKeys, OfflineReplicaMutationCoordinator } from './offline-replica-mutation-coordinator';\nimport {\n OFFLINE_REPLICA_PROJECTOR,\n OFFLINE_REPLICA_PULLER,\n type OfflineReplicaChange,\n type OfflineReplicaPullPage,\n type OfflineReplicaReconciliationTarget,\n} from './offline-replica-puller';\nimport {\n canonicalOfflineCommandIdentity,\n commandIdentityFromReplicaIdentity,\n commandIdentityMatchesReplicaRow,\n offlineGeneratedReplicaIdentity,\n offlineNaturalReplicaIdentity,\n} from './offline-identity';\nimport {\n canonicalOfflineRemoteIdentity,\n normalizeOfflineNaturalKey,\n offlineNaturalKeyFromValues,\n projectOfflineReplicaValues,\n sha256OfflineReplicaSchema,\n type OfflineReplicaRemoteIdentity,\n type OfflineReplicaEntitySchema,\n} from './offline-replica-schema';\nimport {\n OFFLINE_REPOSITORY,\n canonicalOfflineReplicaRowKey,\n type OfflineCommand,\n type OfflineReplicaRow,\n type OfflineReplicaRowKey,\n type OfflineScope,\n} from './offline-repository';\n\ntype CollapsedOfflineReplicaChange = OfflineReplicaChange & {\n /** Last position in this page at which each command id was acknowledged. */\n acknowledgementOrdinals: Readonly<Record<string, number>>;\n /** Position of the authoritative last change retained by the collapse. */\n collapsedOrdinal: number;\n};\n\n/**\n * Pull handshake reported a replica schema version/hash that does not match the local Kit schema.\n *\n * Prefer `instanceof` (or {@link OfflineReplicaSchemaMismatchError.code}) over English message text.\n */\nexport class OfflineReplicaSchemaMismatchError extends Error {\n /** Stable machine-readable discriminator for fatal pull classification (pre- and post-send). */\n static readonly code = 'OFFLINE_REPLICA_SCHEMA_MISMATCH' as const;\n\n readonly code = OfflineReplicaSchemaMismatchError.code;\n\n constructor(\n readonly clientVersion: number,\n readonly clientHash: string,\n readonly serverVersion: number,\n readonly serverHash: string,\n ) {\n super(`Offline replica schema mismatch: client=${clientVersion}/${clientHash}, server=${serverVersion}/${serverHash}.`);\n this.name = 'OfflineReplicaSchemaMismatchError';\n }\n}\n\n/** Pulls authoritative server deltas into one durable local replica partition. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineReplicaPullService {\n readonly #repository = inject(OFFLINE_REPOSITORY);\n readonly #options = inject(OFFLINE_KIT_OPTIONS);\n readonly #puller = inject(OFFLINE_REPLICA_PULLER);\n readonly #projector = inject(OFFLINE_REPLICA_PROJECTOR, { optional: true });\n readonly #hooks = inject(OFFLINE_COMMAND_HOOKS);\n readonly #replicaMutations = inject(OfflineReplicaMutationCoordinator);\n #schemaHash: Promise<string> | null = null;\n\n async pull(scope: OfflineScope): Promise<void> {\n if (this.#options.mode === 'readCacheOnly') return;\n const storageSchemaHash = await (this.#schemaHash ??= sha256OfflineReplicaSchema(this.#options.replicaSchema));\n const wireProtocol = this.#options.wireProtocol ?? {\n version: this.#options.replicaSchema.version,\n hash: storageSchemaHash,\n };\n let persistedCursor = (await this.#repository.getReplicaCursor(scope))?.cursor ?? '';\n let requestCursor = persistedCursor;\n let rebaselinePending = false;\n\n for (;;) {\n const reconciliationTargets = await this.#reconciliationTargets(scope);\n const reconciliationTargetsById = new Map(reconciliationTargets.map((target) => [target.commandId, target] as const));\n const page = await this.#puller.pull({\n scope,\n cursor: requestCursor,\n schemaVersion: wireProtocol.version,\n schemaHash: wireProtocol.hash,\n reconciliationTargets,\n });\n this.#assertPullPage(page);\n this.#assertHandshake(page.schemaVersion, page.schemaHash, wireProtocol);\n if (page.hasMore && page.nextCursor === requestCursor) {\n throw new Error(`Offline replica pull cursor did not advance for scope ${scope.userId}:${scope.scopeId}.`);\n }\n if (page.changes.length === 0 && !page.hasMore && page.nextCursor === requestCursor && !rebaselinePending) {\n return;\n }\n if (page.rebaselineRequired && page.changes.length === 0 && !page.hasMore) {\n throw new Error('Offline replica rebaseline marker must lead to a snapshot page.');\n }\n if (page.rebaselineRequired && page.changes.length === 0 && page.hasMore) {\n rebaselinePending = true;\n requestCursor = page.nextCursor;\n continue;\n }\n\n const applied = await this.#replicaMutations.run(async (repository) => {\n const currentCursor = (await repository.getReplicaCursor(scope))?.cursor ?? '';\n if (currentCursor !== persistedCursor) return currentCursor;\n const scopeCommands = await repository.getCommands(scope);\n const userCommands = repository.getCommandsForUser ? await repository.getCommandsForUser(scope.userId) : scopeCommands;\n const changes = this.#collapseChanges(page.changes);\n const projection = await this.#projector?.project({\n scope,\n changes,\n });\n this.#assertProjection(scope, projection);\n const putRows: OfflineReplicaRow[] = [];\n const removeRows: OfflineReplicaRowKey[] = [];\n const putCommands = new Map<string, OfflineCommand>();\n const removeCommandIds = new Set<string>();\n const rematerializeAfter: OfflineCommand[] = [];\n if (rebaselinePending || page.rebaselineRequired) {\n removeRows.push(...(await this.#confirmedRowsForRebaseline(scope, userCommands)));\n }\n\n for (const change of changes) {\n const schema = this.#entitySchema(change.sourceKey);\n const commands = schema.scope === 'user' ? userCommands : scopeCommands;\n const acknowledged = (change.acknowledgedCommandIds ?? [])\n .map((commandId) => {\n const command = commands.find((candidate) => candidate.commandId === commandId);\n if (!command) return null;\n if (command.sourceKey !== change.sourceKey) {\n throw new Error(`Acknowledged command \"${commandId}\" does not target \"${change.sourceKey}\".`);\n }\n const requested = reconciliationTargetsById.get(commandId);\n if (command.state === 'awaiting_pull') {\n if (!requested) {\n throw new Error(`Acknowledged command \"${commandId}\" was not requested for reconciliation on this pull page.`);\n }\n const schema = this.#entitySchema(change.sourceKey);\n if (\n canonicalOfflineRemoteIdentity(schema, requested.identity) !==\n canonicalOfflineRemoteIdentity(schema, this.#identity(change))\n ) {\n throw new Error(`Acknowledged command \"${commandId}\" does not match the requested remote identity.`);\n }\n }\n return command;\n })\n .filter((command): command is OfflineCommand => command !== null);\n const acknowledgedIdentities = new Set(acknowledged.map((command) => canonicalOfflineCommandIdentity(command.identity)));\n if (acknowledgedIdentities.size > 1) {\n throw new Error(`Acknowledged commands for \"${change.sourceKey}\" target multiple replica identities.`);\n }\n const acknowledgedCommand = acknowledged[0];\n const acknowledgedScope = acknowledgedCommand\n ? { userId: acknowledgedCommand.userId, scopeId: acknowledgedCommand.scopeId }\n : scope;\n const acknowledgedRow = acknowledgedCommand\n ? await (this.#repository.getReplicaRowIncludingPendingDelete?.(\n acknowledgedScope,\n change.sourceKey,\n acknowledgedCommand.identity,\n ) ?? this.#repository.getReplicaRow(acknowledgedScope, change.sourceKey, acknowledgedCommand.identity))\n : null;\n if (acknowledgedCommand && !acknowledgedRow) {\n throw new Error(`Acknowledged command \"${acknowledgedCommand.commandId}\" has no local replica row.`);\n }\n const identity = this.#identity(change);\n const serverRow = await this.#repository.getReplicaRowByRemoteIdentity(scope, change.sourceKey, identity);\n if (\n acknowledgedRow &&\n serverRow &&\n !commandIdentityMatchesReplicaRow(schema, acknowledgedRow, commandIdentityFromReplicaIdentity(serverRow.identity))\n ) {\n if (identity.remoteId !== undefined) {\n throw new Error(`Server id ${String(identity.remoteId)} is already mapped to another local replica row.`);\n }\n throw new Error(`Remote identity for \"${change.sourceKey}\" is already mapped to another local replica row.`);\n }\n const existing = acknowledgedRow ?? serverRow;\n const related = existing\n ? commands.filter(\n (command) => command.sourceKey === change.sourceKey && commandIdentityMatchesReplicaRow(schema, existing, command.identity),\n )\n : [];\n const hasPending = related.length > 0;\n\n if (acknowledgedCommand) {\n this.#assertIdentityAssignment(schema, existing!, identity);\n this.#applyAcknowledgement(change, existing!, related, putRows, removeRows, putCommands, removeCommandIds, rematerializeAfter);\n continue;\n }\n\n if (change.deleted) {\n if (!existing) continue;\n if (!hasPending) {\n removeRows.push({ ...existing, identity: existing.identity });\n continue;\n }\n putRows.push({\n ...existing,\n confirmedValues: null,\n serverRevision: change.serverRevision,\n syncState: 'conflict',\n fetchedAt: Date.now(),\n });\n for (const command of related) {\n putCommands.set(command.commandId, { ...command, state: 'conflict', retryAt: null, lastErrorCode: 'remote_deleted' });\n }\n rematerializeAfter.push(related[0]!);\n continue;\n }\n\n const confirmedValues = this.#validatedValues(schema, change);\n if (!existing) {\n putRows.push({\n ...scope,\n sourceKey: change.sourceKey,\n identity:\n schema.identity.kind === 'naturalKey'\n ? offlineNaturalReplicaIdentity(schema, confirmedValues)\n : offlineGeneratedReplicaIdentity(crypto.randomUUID(), identity.remoteId ?? null),\n values: confirmedValues,\n confirmedValues,\n serverRevision: change.serverRevision,\n fetchedAt: Date.now(),\n syncState: 'confirmed',\n });\n continue;\n }\n\n const remaining = related.filter((command) => !removeCommandIds.has(command.commandId));\n const confirmedRow: OfflineReplicaRow = {\n ...existing,\n confirmedValues,\n serverRevision: change.serverRevision,\n fetchedAt: Date.now(),\n values: remaining.length > 0 ? existing.values : confirmedValues,\n syncState: remaining.length > 0 ? 'pending' : 'confirmed',\n };\n putRows.push(confirmedRow);\n if (remaining.length > 0) rematerializeAfter.push(remaining[0]!);\n for (const command of remaining) {\n putCommands.set(command.commandId, offlineCommandWithBaseRevision(command, change.serverRevision));\n }\n }\n\n const confirmedAndProjected = this.#mergeRowMutations([\n { putRows, removeRows },\n { putRows: projection?.putRows ?? [], removeRows: projection?.removeRows ?? [] },\n ]);\n const rematerialized = await this.#rematerializePendingAggregates(\n scope,\n userCommands,\n scopeCommands,\n confirmedAndProjected,\n putCommands,\n removeCommandIds,\n rematerializeAfter,\n );\n const finalRows = this.#mergeRowMutations([confirmedAndProjected, rematerialized]);\n const removedCommands = [...removeCommandIds]\n .map(\n (commandId) =>\n userCommands.find((command) => command.commandId === commandId) ??\n scopeCommands.find((command) => command.commandId === commandId),\n )\n .filter((command): command is OfflineCommand => command != null);\n await repository.transactReplica({\n putRows: finalRows.putRows,\n removeRows: finalRows.removeRows,\n putCommands: [...putCommands.values()],\n removeCommandIds: [...removeCommandIds],\n putCursors: [{ ...scope, cursor: page.nextCursor }],\n });\n await Promise.all(removedCommands.map((command) => this.#hooks.onCommandRemoved?.(command).catch(() => undefined)));\n return page.nextCursor;\n });\n if (applied !== page.nextCursor) {\n persistedCursor = applied;\n requestCursor = applied;\n rebaselinePending = false;\n continue;\n }\n persistedCursor = page.nextCursor;\n requestCursor = page.nextCursor;\n rebaselinePending = false;\n if (!page.hasMore) return;\n }\n }\n\n async #reconciliationTargets(scope: OfflineScope): Promise<OfflineReplicaReconciliationTarget[]> {\n const commands = (await this.#repository.getCommands(scope)).filter((command) => command.state === 'awaiting_pull');\n const targets: OfflineReplicaReconciliationTarget[] = [];\n for (const command of commands) {\n const row =\n (await this.#repository.getReplicaRowIncludingPendingDelete?.(scope, command.sourceKey, command.identity)) ??\n (await this.#repository.getReplicaRow(scope, command.sourceKey, command.identity));\n if (!row) throw new Error(`Awaiting-pull command \"${command.commandId}\" has no replica row.`);\n const identity =\n command.reconciliationIdentity ??\n (row.identity.kind === 'generated'\n ? row.identity.remoteId === null\n ? null\n : { remoteId: row.identity.remoteId }\n : row.identity.kind === 'natural'\n ? { naturalKey: row.identity.naturalKey }\n : null);\n if (!identity) throw new Error(`Awaiting-pull command \"${command.commandId}\" has no remote identity.`);\n canonicalOfflineRemoteIdentity(this.#entitySchema(command.sourceKey), identity);\n targets.push({ commandId: command.commandId, operation: command.operation, sourceKey: command.sourceKey, identity });\n }\n return targets;\n }\n\n async #confirmedRowsForRebaseline(scope: OfflineScope, commands: readonly OfflineCommand[]): Promise<OfflineReplicaRowKey[]> {\n const preserved = new Set(\n commands.flatMap((command) => {\n const identity =\n command.identity.kind === 'generated'\n ? offlineGeneratedReplicaIdentity(command.identity.localId, null)\n : { kind: 'natural' as const, naturalKey: command.identity.naturalKey };\n return [this.#rowKey({ ...command, identity }), ...commandFootprintKeys(command).map((key) => this.#rowKey(key))];\n }),\n );\n const rows = (\n await Promise.all(this.#options.replicaSchema.entities.map((entity) => this.#repository.getReplicaRows(scope, entity.sourceKey)))\n ).flat();\n return rows.filter((row) => row.syncState === 'confirmed' && !preserved.has(this.#rowKey(row)));\n }\n\n #rowKey(row: OfflineReplicaRowKey): string {\n return canonicalOfflineReplicaRowKey(this.#entitySchema(row.sourceKey), row);\n }\n\n #mergeRowMutations(\n layers: readonly {\n putRows: readonly OfflineReplicaRow[];\n removeRows: readonly OfflineReplicaRowKey[];\n }[],\n ): { putRows: OfflineReplicaRow[]; removeRows: OfflineReplicaRowKey[] } {\n const mutations = new Map<string, { kind: 'put'; row: OfflineReplicaRow } | { kind: 'remove'; row: OfflineReplicaRowKey }>();\n for (const layer of layers) {\n for (const row of layer.removeRows) mutations.set(this.#rowKey(row), { kind: 'remove', row });\n for (const row of layer.putRows) mutations.set(this.#rowKey(row), { kind: 'put', row });\n }\n const putRows: OfflineReplicaRow[] = [];\n const removeRows: OfflineReplicaRowKey[] = [];\n for (const mutation of mutations.values()) {\n if (mutation.kind === 'put') putRows.push(mutation.row);\n else removeRows.push(mutation.row);\n }\n return { putRows, removeRows };\n }\n\n #assertProjection(\n scope: OfflineScope,\n projection: { putRows?: readonly OfflineReplicaRow[]; removeRows?: readonly OfflineReplicaRowKey[] } | undefined,\n ): void {\n for (const row of [...(projection?.putRows ?? []), ...(projection?.removeRows ?? [])]) {\n const schema = this.#entitySchema(row.sourceKey);\n if (schema.identity.kind !== 'localOnly') {\n throw new Error(`Offline replica projector may only mutate localOnly source \"${row.sourceKey}\".`);\n }\n if (row.userId !== scope.userId || row.scopeId !== scope.scopeId || row.identity.kind !== 'local') {\n throw new Error('Offline replica projector rows must use the current scope and local identity.');\n }\n }\n }\n\n #assertPullPage(page: OfflineReplicaPullPage): void {\n if (typeof page.nextCursor !== 'string') {\n throw new Error('Offline replica pull page nextCursor must be a string.');\n }\n if (typeof page.hasMore !== 'boolean') {\n throw new Error('Offline replica pull page hasMore must be a boolean.');\n }\n if (!Array.isArray(page.changes)) {\n throw new Error('Offline replica pull page changes must be an array.');\n }\n if (page.rebaselineRequired !== undefined && typeof page.rebaselineRequired !== 'boolean') {\n throw new Error('Offline replica pull page rebaselineRequired must be a boolean when present.');\n }\n for (const [index, change] of page.changes.entries()) {\n this.#assertPullChange(change, index);\n }\n }\n\n async #rematerializePendingAggregates(\n scope: OfflineScope,\n userCommands: readonly OfflineCommand[],\n scopeCommands: readonly OfflineCommand[],\n currentRows: { putRows: readonly OfflineReplicaRow[]; removeRows: readonly OfflineReplicaRowKey[] },\n putCommands: Map<string, OfflineCommand>,\n removeCommandIds: ReadonlySet<string>,\n seeds: readonly OfflineCommand[],\n ): Promise<{ putRows: OfflineReplicaRow[]; removeRows: OfflineReplicaRowKey[] }> {\n const remaining = [...userCommands, ...scopeCommands]\n .filter((command, index, all) => all.findIndex((candidate) => candidate.commandId === command.commandId) === index)\n .filter((command) => !removeCommandIds.has(command.commandId))\n .map((command) => putCommands.get(command.commandId) ?? command);\n const affected = new Map<string, OfflineCommand>();\n for (const command of [...seeds, ...remaining]) {\n if (removeCommandIds.has(command.commandId) && !remaining.some((item) => this.#aggregateKey(item) === this.#aggregateKey(command))) {\n affected.set(this.#aggregateKey(command), command);\n continue;\n }\n if (!removeCommandIds.has(command.commandId) || seeds.some((seed) => seed.commandId === command.commandId)) {\n affected.set(this.#aggregateKey(command), command);\n }\n }\n const putRows: OfflineReplicaRow[] = [];\n const removeRows: OfflineReplicaRowKey[] = [];\n const overlay = new Map(currentRows.putRows.map((row) => [this.#rowKey(row), row] as const));\n const removed = new Set(currentRows.removeRows.map((row) => this.#rowKey(row)));\n for (const [key, seed] of affected) {\n const remainingForAggregate = remaining.filter((command) => this.#aggregateKey(command) === key);\n const existingConflict = remainingForAggregate.find((command) => command.state === 'conflict');\n const footprintCommands = [...remainingForAggregate, seed];\n const baseRow = await this.#overlayBaseRow(seed, overlay, removed);\n const persistedLocalOnlyRows = await this.#persistedLocalOnlyRows(footprintCommands);\n const localOnlyRows = await this.#overlayLocalOnlyRows(footprintCommands, overlay, removed);\n const projection = existingConflict\n ? { kind: 'conflict' as const, reason: existingConflict.lastErrorCode ?? 'remote_revision' }\n : this.#replicaMutations.projectAggregateIntent({\n baseRow,\n localOnlyRows,\n commands: remainingForAggregate,\n trigger: 'pull',\n incomingRevision: baseRow?.serverRevision ?? undefined,\n });\n if (isOfflineAggregateIntentConflict(projection)) {\n if (!baseRow) throw new Error('Offline aggregate conflict requires an authoritative base row.');\n putRows.push({ ...baseRow, values: baseRow.values, syncState: 'conflict' });\n for (const command of remainingForAggregate) {\n putCommands.set(command.commandId, {\n ...command,\n state: 'conflict',\n retryAt: null,\n lastErrorCode: projection.reason,\n });\n }\n const incomingByKey = new Map(localOnlyRows.map((row) => [this.#rowKey(row), row] as const));\n for (const previous of persistedLocalOnlyRows) {\n const incoming = incomingByKey.get(this.#rowKey(previous));\n putRows.push({\n ...(incoming ?? previous),\n values: previous.values,\n confirmedValues: incoming?.confirmedValues ?? null,\n syncState: 'conflict',\n visibility: previous.visibility,\n });\n }\n continue;\n }\n const mutations = offlineAggregateIntentMutations(projection, baseRow);\n putRows.push(...(mutations.putRows ?? []));\n removeRows.push(...(mutations.removeRows ?? []));\n }\n void scope;\n return { putRows, removeRows };\n }\n\n async #overlayBaseRow(\n command: OfflineCommand,\n overlay: ReadonlyMap<string, OfflineReplicaRow>,\n removed: ReadonlySet<string>,\n ): Promise<OfflineReplicaRow | null> {\n const schema = this.#entitySchema(command.sourceKey);\n const identity =\n command.identity.kind === 'generated'\n ? offlineGeneratedReplicaIdentity(command.identity.localId, null)\n : { kind: 'natural' as const, naturalKey: command.identity.naturalKey };\n const canonical = this.#rowKey({ ...command, identity });\n if (removed.has(canonical)) return null;\n const overlaid = [...overlay.values()].find(\n (row) => row.sourceKey === command.sourceKey && commandIdentityMatchesReplicaRow(schema, row, command.identity),\n );\n if (overlaid) return overlaid;\n const commandScope = { userId: command.userId, scopeId: command.scopeId };\n return (\n this.#repository.getReplicaRowIncludingPendingDelete?.(commandScope, command.sourceKey, command.identity) ??\n this.#repository.getReplicaRow(commandScope, command.sourceKey, command.identity)\n );\n }\n\n async #overlayLocalOnlyRows(\n commands: readonly OfflineCommand[],\n overlay: ReadonlyMap<string, OfflineReplicaRow>,\n removed: ReadonlySet<string>,\n ): Promise<OfflineReplicaRow[]> {\n const keys = new Map<string, OfflineReplicaRowKey>();\n for (const command of commands) {\n for (const key of commandFootprintKeys(command)) keys.set(this.#rowKey(key), key);\n }\n const rows: OfflineReplicaRow[] = [];\n for (const [canonical, key] of keys) {\n if (removed.has(canonical)) continue;\n const overlaid = overlay.get(canonical);\n if (overlaid) {\n rows.push(overlaid);\n continue;\n }\n const rowScope = { userId: key.userId, scopeId: key.scopeId };\n const row =\n (await this.#repository.getReplicaRowIncludingPendingDelete?.(rowScope, key.sourceKey, key.identity)) ??\n (await this.#repository.getReplicaRow(rowScope, key.sourceKey, key.identity));\n if (row) rows.push(row);\n }\n return rows;\n }\n\n async #persistedLocalOnlyRows(commands: readonly OfflineCommand[]): Promise<OfflineReplicaRow[]> {\n return this.#overlayLocalOnlyRows(commands, new Map(), new Set());\n }\n\n #aggregateKey(command: OfflineCommand): string {\n const schema = this.#entitySchema(command.sourceKey);\n const partition = schema.scope === 'user' ? 'user' : `partition:${command.scopeId}`;\n return `${command.userId}:${partition}:${command.sourceKey}:${canonicalOfflineCommandIdentity(command.identity)}`;\n }\n\n #assertPullChange(change: unknown, index: number): void {\n const label = `Offline replica pull page changes[${index}]`;\n if (!isPlainObject(change)) {\n throw new Error(`${label} must be a plain object.`);\n }\n if (typeof change['sourceKey'] !== 'string') {\n throw new Error(`${label}.sourceKey must be a string.`);\n }\n if (typeof change['deleted'] !== 'boolean') {\n throw new Error(`${label}.deleted must be a boolean.`);\n }\n const schema = this.#entitySchema(change['sourceKey']);\n if (schema.identity.kind === 'generated') {\n const remoteId = change['remoteId'];\n const validInteger = typeof remoteId === 'number' && Number.isSafeInteger(remoteId) && remoteId > 0;\n const validText = typeof remoteId === 'string' && remoteId.length > 0;\n if (schema.identity.affinity === 'INTEGER' ? !validInteger : !validText) {\n throw new Error(`${label}.remoteId must be a valid generated remote id.`);\n }\n if (change['naturalKey'] !== undefined) {\n throw new Error(`${label}.naturalKey must be omitted for a generated entity.`);\n }\n }\n try {\n canonicalOfflineRemoteIdentity(schema, change as unknown as OfflineReplicaRemoteIdentity);\n } catch (error) {\n throw new Error(`${label} has invalid remote identity: ${error instanceof Error ? error.message : String(error)}`);\n }\n const revision = change['serverRevision'];\n if (typeof revision !== 'string' && (typeof revision !== 'number' || !Number.isFinite(revision))) {\n throw new Error(`${label}.serverRevision must be a string or number.`);\n }\n const acknowledgedCommandIds = change['acknowledgedCommandIds'];\n if (\n (acknowledgedCommandIds !== undefined && !Array.isArray(acknowledgedCommandIds)) ||\n (Array.isArray(acknowledgedCommandIds) &&\n acknowledgedCommandIds.some((commandId) => typeof commandId !== 'string' || commandId.length === 0))\n ) {\n throw new Error(`${label}.acknowledgedCommandIds must be an array of non-empty strings.`);\n }\n if (change['deleted']) {\n if (change['values'] !== null) {\n throw new Error(`${label} with deleted=true must have null values.`);\n }\n }\n }\n\n #assertHandshake(version: number, hash: string, expected: { readonly version: number; readonly hash: string }): void {\n if (version !== expected.version || hash !== expected.hash) {\n throw new OfflineReplicaSchemaMismatchError(expected.version, expected.hash, version, hash);\n }\n }\n\n #entitySchema(sourceKey: string): OfflineReplicaEntitySchema<Record<string, unknown>> {\n const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);\n if (!schema) throw new Error(`Unknown offline replica source key \"${sourceKey}\".`);\n return schema;\n }\n\n #validatedValues(schema: OfflineReplicaEntitySchema<Record<string, unknown>>, change: OfflineReplicaChange): unknown {\n if (change.values === null) {\n throw new Error(\n change.remoteId === undefined\n ? `Offline replica change \"${change.sourceKey}\" is missing values.`\n : `Offline replica change \"${change.sourceKey}\"/${String(change.remoteId)} is missing values.`,\n );\n }\n const values = projectOfflineReplicaValues(schema, change.values);\n if (schema.identity.kind === 'naturalKey') {\n const expected = offlineNaturalKeyFromValues(schema, values)!;\n const incoming = normalizeOfflineNaturalKey(schema, change.naturalKey!);\n if (\n canonicalOfflineRemoteIdentity(schema, { naturalKey: expected }) !==\n canonicalOfflineRemoteIdentity(schema, { naturalKey: incoming })\n ) {\n throw new Error(`Offline replica change \"${change.sourceKey}\" naturalKey does not match values.`);\n }\n }\n return values;\n }\n\n #collapseChanges(changes: readonly OfflineReplicaChange[]): CollapsedOfflineReplicaChange[] {\n const collapsed = new Map<string, CollapsedOfflineReplicaChange>();\n for (const [ordinal, change] of changes.entries()) {\n const schema = this.#entitySchema(change.sourceKey);\n const key = `${change.sourceKey}:${canonicalOfflineRemoteIdentity(schema, this.#identity(change))}`;\n const previous = collapsed.get(key);\n const acknowledgedCommandIds = [...new Set([...(previous?.acknowledgedCommandIds ?? []), ...(change.acknowledgedCommandIds ?? [])])];\n const acknowledgementOrdinals = { ...(previous?.acknowledgementOrdinals ?? {}) };\n for (const commandId of change.acknowledgedCommandIds ?? []) {\n acknowledgementOrdinals[commandId] = ordinal;\n }\n collapsed.set(key, {\n ...change,\n acknowledgedCommandIds,\n acknowledgementOrdinals,\n collapsedOrdinal: ordinal,\n });\n }\n return [...collapsed.values()];\n }\n\n #applyAcknowledgement(\n change: CollapsedOfflineReplicaChange,\n row: OfflineReplicaRow,\n related: readonly OfflineCommand[],\n putRows: OfflineReplicaRow[],\n removeRows: OfflineReplicaRowKey[],\n putCommands: Map<string, OfflineCommand>,\n removeCommandIds: Set<string>,\n rematerializeAfter: OfflineCommand[],\n ): void {\n const acknowledgedIds = new Set(change.acknowledgedCommandIds ?? []);\n const lastAcknowledgedIndex = related.reduce((last, command, index) => (acknowledgedIds.has(command.commandId) ? index : last), -1);\n if (lastAcknowledgedIndex < 0) {\n throw new Error(`Replica acknowledgement does not match the local aggregate outbox.`);\n }\n if (related.slice(0, lastAcknowledgedIndex + 1).some((command) => !acknowledgedIds.has(command.commandId))) {\n throw new Error(`Replica acknowledgement skipped an earlier aggregate command.`);\n }\n const lastAcknowledgedCommand = related[lastAcknowledgedIndex]!;\n const acknowledgementSuperseded = (change.acknowledgementOrdinals[lastAcknowledgedCommand.commandId] ?? -1) < change.collapsedOrdinal;\n const following = related\n .slice(lastAcknowledgedIndex + 1)\n .map((command) =>\n acknowledgementSuperseded || change.deleted\n ? { ...command, state: 'conflict' as const, retryAt: null, lastErrorCode: change.deleted ? 'remote_deleted' : 'remote_revision' }\n : offlineCommandWithBaseRevision(command, change.serverRevision),\n );\n for (const command of following) putCommands.set(command.commandId, command);\n for (const command of related.slice(0, lastAcknowledgedIndex + 1)) {\n removeCommandIds.add(command.commandId);\n }\n rematerializeAfter.push(lastAcknowledgedCommand);\n\n if (change.deleted) {\n if (following.length > 0) {\n putRows.push({\n ...row,\n confirmedValues: null,\n serverRevision: change.serverRevision,\n syncState: 'conflict',\n visibility: following.at(-1)!.replicaMutation === 'delete' ? 'pending_delete' : 'present',\n fetchedAt: Date.now(),\n });\n } else {\n removeRows.push({ ...row, identity: row.identity });\n }\n return;\n }\n\n const schema = this.#entitySchema(change.sourceKey);\n const confirmedValues = this.#validatedValues(schema, change);\n this.#assertIdentityAssignment(schema, row, this.#identity(change));\n putRows.push({\n ...row,\n identity: row.identity.kind === 'generated' ? { ...row.identity, remoteId: change.remoteId ?? row.identity.remoteId } : row.identity,\n values: following.length > 0 ? row.values : confirmedValues,\n confirmedValues,\n serverRevision: change.serverRevision,\n fetchedAt: Date.now(),\n syncState: following.length > 0 ? (acknowledgementSuperseded ? 'conflict' : 'pending') : 'confirmed',\n visibility: following.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',\n });\n }\n\n #identity(change: OfflineReplicaChange): OfflineReplicaRemoteIdentity {\n return change.remoteId !== undefined ? { remoteId: change.remoteId } : { naturalKey: change.naturalKey! };\n }\n\n #assertIdentityAssignment(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n row: OfflineReplicaRow,\n incoming: OfflineReplicaRemoteIdentity,\n ): void {\n if (schema.identity.kind === 'generated') {\n const remoteId = incoming.remoteId!;\n if (row.identity.kind !== 'generated') {\n throw new Error(`Replica generated identity is required for \"${schema.sourceKey}\".`);\n }\n if (row.identity.remoteId !== null && row.identity.remoteId !== remoteId) {\n throw new Error(`Replica remote id is immutable: current=${String(row.identity.remoteId)}, incoming=${String(remoteId)}.`);\n }\n return;\n }\n const current = row.identity.kind === 'natural' ? row.identity.naturalKey : offlineNaturalKeyFromValues(schema, row.values);\n if (\n current !== null &&\n canonicalOfflineRemoteIdentity(schema, { naturalKey: current }) !== canonicalOfflineRemoteIdentity(schema, incoming)\n ) {\n throw new Error(`Replica naturalKey is immutable for \"${schema.sourceKey}\".`);\n }\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n","import { computed, Injectable, signal } from '@angular/core';\nimport { App } from '@capacitor/app';\nimport type { PluginListenerHandle } from '@capacitor/core';\nimport { Network } from '@capacitor/network';\n\nexport type OfflineNetworkState = 'online' | 'offline' | 'unverified';\n\n/** transport不能(status=0)だけをlocal replica fallback対象にし、HTTPエラーは隠さない。 */\nexport function isOfflineFallbackError(error: unknown): boolean {\n return typeof error === 'object' && error !== null && (error as { status?: unknown }).status === 0;\n}\n\n/** Combines operating-system connectivity with observed API reachability. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineNetworkService {\n readonly #osConnected = signal<boolean | null>(null);\n readonly #apiReachable = signal<boolean | null>(null);\n readonly #listeners: PluginListenerHandle[] = [];\n #initialized = false;\n\n readonly state = computed<OfflineNetworkState>(() => {\n if (this.#osConnected() === false || this.#apiReachable() === false) return 'offline';\n if (this.#osConnected() === true && this.#apiReachable() === true) return 'online';\n return 'unverified';\n });\n readonly connected = computed(() => this.state() !== 'offline');\n\n async initialize(): Promise<void> {\n if (this.#initialized) return;\n this.#initialized = true;\n this.#osConnected.set((await Network.getStatus()).connected);\n this.#listeners.push(\n await Network.addListener('networkStatusChange', ({ connected }) => {\n this.#osConnected.set(connected);\n this.#apiReachable.set(connected ? null : false);\n }),\n await App.addListener('appStateChange', ({ isActive }) => {\n if (isActive) void this.#refreshOsStatus();\n }),\n );\n }\n\n markApiSuccess(): void {\n this.#apiReachable.set(true);\n }\n\n markApiFailure(): void {\n this.#apiReachable.set(false);\n }\n\n async #refreshOsStatus(): Promise<void> {\n this.#osConnected.set((await Network.getStatus()).connected);\n }\n}\n","import { inject, Injectable } from '@angular/core';\nimport { OFFLINE_KIT_OPTIONS } from './offline-kit-options';\n\n/** Raised when a new durable mutation reaches Kit after mutation persistence was closed. */\nexport class OfflineMutationPersistenceDisabledError extends Error {\n constructor() {\n super('Offline mutation persistence was disabled before the mutation could be accepted.');\n this.name = 'OfflineMutationPersistenceDisabledError';\n }\n}\n\n/** Product-independent lease gate around every new durable Outbox command. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineMutationAdmissionService {\n readonly #options = inject(OFFLINE_KIT_OPTIONS);\n #accepting = this.#options.mutationPersistence === undefined;\n #active = 0;\n #idle: Promise<void> | null = null;\n #resolveIdle: (() => void) | null = null;\n\n get accepting(): boolean {\n return this.#accepting;\n }\n\n async run<T>(operation: () => Promise<T>): Promise<T> {\n if (!this.#accepting) throw new OfflineMutationPersistenceDisabledError();\n this.#active += 1;\n return new Promise<T>((resolve) => resolve(operation())).finally(() => this.#release());\n }\n\n open(): void {\n this.#accepting = true;\n }\n\n async close(): Promise<void> {\n this.#accepting = false;\n if (this.#active === 0) return;\n if (!this.#idle) {\n this.#idle = new Promise<void>((resolve) => {\n this.#resolveIdle = resolve;\n });\n }\n return this.#idle;\n }\n\n #release(): void {\n this.#active -= 1;\n if (this.#active !== 0) return;\n this.#resolveIdle?.();\n this.#idle = null;\n this.#resolveIdle = null;\n }\n}\n","import { computed, effect, ErrorHandler, inject, Injectable, InjectionToken, signal, untracked } from '@angular/core';\nimport {\n OFFLINE_COMMAND_EXECUTOR,\n OFFLINE_SYNC_CONTEXT,\n offlineCommandLookupIdentity,\n offlineCommandTargetFromReplicaRow,\n offlineCommandWithBaseRevision,\n type OfflineCommandResult,\n type EnqueueOfflineCommandIdentity,\n type OfflineSyncSession,\n} from './offline-command-executor';\nimport { OFFLINE_COMMAND_HOOKS } from './offline-command-hooks';\nimport { OFFLINE_KIT_OPTIONS } from './offline-kit-options';\nimport { OfflineNetworkService } from './offline-network.service';\nimport { OfflineMutationAdmissionService } from './offline-mutation-admission.service';\nimport { OfflineReplicaPullService, OfflineReplicaSchemaMismatchError } from './offline-replica-pull.service';\nimport { isOfflineAggregateIntentConflict, offlineAggregateIntentMutations } from './offline-aggregate-intent-projector';\nimport { commandFootprintKeys, OfflineReplicaMutationCoordinator } from './offline-replica-mutation-coordinator';\nimport type {\n OfflineCommand,\n OfflinePullAttention,\n OfflinePullAttentionReason,\n OfflineReplicaSyncState,\n OfflineReplicaRow,\n OfflineReplicaRowKey,\n OfflineReplicaTransaction,\n OfflineRepository,\n OfflineScope,\n} from './offline-repository';\nimport { canonicalOfflineReplicaRowKey, OFFLINE_REPOSITORY } from './offline-repository';\nimport {\n canonicalOfflinePrincipalId,\n canonicalOfflineCommandIdentity,\n commandIdentityFromReplicaIdentity,\n commandIdentityMatchesReplicaRow,\n offlineGeneratedReplicaIdentity,\n type OfflineCommandIdentity,\n type OfflinePrincipalId,\n} from './offline-identity';\nimport {\n assertOfflineReplicaGeneratedRemoteId,\n canonicalOfflineRemoteIdentity,\n offlineNaturalKeyFromValues,\n type OfflineGeneratedRemoteId,\n type OfflineReplicaEntitySchema,\n} from './offline-replica-schema';\n\n/** Aggregate synchronization state exposed to application UI. */\nexport type OfflineSyncState = 'idle' | 'pending' | 'syncing' | 'attention';\n\n/** Mutation appended atomically to the outbox; Kit rematerializes optimistic replica state. */\nexport interface EnqueueOfflineCommand<T = unknown> {\n scopeId: string;\n aggregateType: string;\n identity: EnqueueOfflineCommandIdentity;\n operation: string;\n payload: T;\n /**\n * Optimistically hides an existing DB row while retaining its identity and\n * confirmed baseline for durable replay, conflict handling, and discard.\n */\n replicaMutation?: 'upsert' | 'delete';\n baseRevision?: string | number | null;\n /** Declared localOnly projection rows this intent may create, update, or remove. */\n localOnlyFootprint?: readonly OfflineReplicaRowKey[];\n}\n\n/**\n * A command prepared from replica reads while enqueue/ACK projection is\n * serialized. Kit rematerializes the aggregate; the prepare callback must not\n * supply replica row images as independent truth.\n */\nexport interface PreparedOfflineCommand<T = unknown> {\n request: EnqueueOfflineCommand<T>;\n}\n\nexport interface PreparedOfflineBatchOptions {\n flush?: boolean;\n /** Product identity/scope lease asserted after all async preparation and immediately before the durable commit. */\n assertCurrent?: () => void;\n}\n\n/** Validated Outbox command ready for a rematerialized replica commit. */\ninterface MaterializedOfflineEnqueue {\n command: OfflineCommand;\n /** Identity-bearing base row used when the aggregate does not yet exist locally. */\n seedBaseRow?: OfflineReplicaRow | null;\n}\n\n/** Raised before persistence when an outbox payload is not losslessly JSON serializable. */\nexport class OfflinePayloadValidationError extends Error {\n constructor(message = 'Offline command payload must contain only JSON values') {\n super(message);\n this.name = 'OfflinePayloadValidationError';\n }\n}\n\n/** Raised before persistence when retaining another command would exceed the configured durable Outbox capacity. */\nexport class OfflineOutboxCapacityError extends Error {\n constructor(\n readonly reason: 'command_count' | 'serialized_bytes',\n readonly currentCommands: number,\n readonly currentBytes: number,\n ) {\n super(\n reason === 'command_count'\n ? 'Offline Outbox command limit reached; synchronize or discard a pending command before continuing'\n : 'Offline Outbox storage limit reached; synchronize or discard a pending command before continuing',\n );\n this.name = 'OfflineOutboxCapacityError';\n }\n}\n\n/** Raised when a discard could race a request whose server commit is unknown. */\nexport class OfflineCommandInFlightError extends Error {\n constructor(readonly commandIds: readonly string[]) {\n super('Offline commands are being synchronized and cannot be discarded until their server result is known');\n this.name = 'OfflineCommandInFlightError';\n }\n}\n\nconst MAX_PARALLEL_AGGREGATES = 3;\nconst MAX_BACKOFF_MS = 60 * 60 * 1000;\nconst POST_SEND_PULL_RETRY_MS = 1_000;\nconst DEFAULT_MAX_OUTBOX_COMMANDS_PER_USER = 1_000;\nconst DEFAULT_MAX_OUTBOX_BYTES_PER_USER = 10 * 1024 * 1024;\n\n/** Injectable `[0, 1)` source used by equal-jitter retry delay. Defaults to `Math.random`. */\nexport const OFFLINE_RETRY_RANDOM = new InjectionToken<() => number>('OFFLINE_RETRY_RANDOM', {\n factory: () => Math.random,\n});\n\n/**\n * Equal-jitter delay in `[⌊cap/2⌋, cap)` for exponential offline command backoff.\n * Keeps a positive lower bound (half the exponential cap) while still desynchronizing clients.\n *\n * @param attempts - Attempt count already recorded on the failed command (`>= 1` after a send claim).\n * @param random - Unit interval sample in `[0, 1)`.\n */\nexport function offlineRetryDelayMs(attempts: number, random: () => number = Math.random): number {\n const cap = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.max(0, attempts - 1));\n const unit = random();\n if (!(unit >= 0 && unit < 1)) {\n throw new Error('Offline retry random() must return a number in [0, 1).');\n }\n const half = cap / 2;\n return Math.floor(half + unit * half);\n}\n\n/** Maintains the optimistic local replica and synchronizes its durable outbox. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineSyncService {\n readonly #network = inject(OfflineNetworkService);\n readonly #mutationAdmission = inject(OfflineMutationAdmissionService);\n readonly #repository = inject(OFFLINE_REPOSITORY);\n readonly #executor = inject(OFFLINE_COMMAND_EXECUTOR);\n readonly #context = inject(OFFLINE_SYNC_CONTEXT);\n readonly #hooks = inject(OFFLINE_COMMAND_HOOKS);\n readonly #options = inject(OFFLINE_KIT_OPTIONS);\n readonly #pull = inject(OfflineReplicaPullService);\n readonly #replicaMutations = inject(OfflineReplicaMutationCoordinator);\n readonly #errorHandler = inject(ErrorHandler);\n readonly #retryRandom = inject(OFFLINE_RETRY_RANDOM);\n readonly #commands = signal<OfflineCommand[]>([]);\n readonly #pullAttentions = signal<OfflinePullAttention[]>([]);\n readonly #knownScopes = new Map<string, OfflineScope>();\n /** In-memory scheduling cache for scopes whose authoritative post-send pull has not completed yet. */\n readonly #pendingPullScopes = new Map<string, OfflineScope>();\n #activeUserId: OfflinePrincipalId | null = null;\n #flushPromise: Promise<void> | null = null;\n #partialFlushInFlight = false;\n #chainedFullFlush: Promise<void> | null = null;\n readonly #flushTransitions = new Set<Promise<void>>();\n #generation = 0;\n readonly #sendingTransitions = new Set<Promise<unknown>>();\n #retryTimer: ReturnType<typeof setTimeout> | null = null;\n /** When non-null, automatic flushes pull only foreground scopes plus Outbox scopes. */\n #foregroundScopePolicy: readonly string[] | null = null;\n #initialization: Promise<void> | null = null;\n #initialized = false;\n #lastCommandCreatedAt = 0;\n\n readonly pendingCommands = this.#commands.asReadonly();\n readonly pendingCount = computed(() => this.pendingCommands().length);\n readonly conflicts = computed(() => this.#commands().filter((command) => command.state === 'conflict'));\n /** Durable fatal-pull attentions for the active principal, restored across restart. */\n readonly pullAttentions = this.#pullAttentions.asReadonly();\n readonly syncState = computed<OfflineSyncState>(() => {\n if (this.#pullAttentions().length > 0) return 'attention';\n const commands = this.#commands();\n if (commands.some((command) => ['blocked_auth', 'rejected', 'conflict'].includes(command.state))) return 'attention';\n // Any non-sending ambiguous commit (including restart-normalized pending+unknown) needs attention.\n if (commands.some((command) => command.state !== 'sending' && command.serverCommitUnknown === true)) return 'attention';\n if (commands.some((command) => command.state === 'sending')) return 'syncing';\n return commands.length > 0 ? 'pending' : 'idle';\n });\n\n constructor() {\n effect(() => {\n const connected = this.#network.connected();\n // The network transition may be observed after an explicit flush has already\n // persisted a fatal pull attention. Do not let that stale transition restart\n // the intentionally stopped loop; auth/session refresh remains able to retry.\n const hasFatalPullAttention = untracked(() => this.#pullAttentions().length > 0);\n if (this.#initialized && connected && !hasFatalPullAttention) this.#flushInBackground();\n });\n }\n\n async initialize(options: { flush?: boolean } = {}): Promise<void> {\n const generation = this.#generation;\n if (!(await this.#restoreCurrentGeneration(generation))) return;\n if (options.flush !== false && this.#network.connected()) this.#flushInBackground();\n }\n\n #ensureInitialized(): Promise<void> {\n this.#initialization ??= this.#initializeOnce();\n return this.#initialization;\n }\n\n async #restoreCurrentGeneration(generation: number): Promise<boolean> {\n await this.#ensureInitialized();\n return this.#isCurrent(generation);\n }\n\n async #initializeOnce(): Promise<void> {\n await this.#repository.initialize();\n await this.#discoverScopes();\n const commands = await this.#readKnownCommands();\n await Promise.all(\n commands\n .filter((command) => command.state === 'sending')\n .map((command) =>\n this.#repository.putCommand({\n ...command,\n state: 'pending',\n serverCommitUnknown: command.serverCommitUnknown ?? true,\n }),\n ),\n );\n this.#initialized = true;\n await this.#refreshState();\n }\n\n noteScope(scope: OfflineScope): void {\n this.#knownScopes.set(this.#scopeKey(scope), scope);\n }\n\n async reloadPendingCommands(): Promise<void> {\n const generation = this.#generation;\n if (!(await this.#restoreCurrentGeneration(generation))) return;\n await this.#refreshState();\n }\n\n async refreshSession(foregroundScopeIds?: readonly string[]): Promise<void> {\n const generation = this.#generation;\n if (!(await this.#restoreCurrentGeneration(generation))) return;\n this.#setForegroundScopePolicy(foregroundScopeIds);\n await this.#discoverScopes();\n await this.#restoreInterruptedCommands();\n await this.#refreshState();\n if (this.#network.connected()) this.#flushInBackground();\n }\n\n /** Restores local outbox visibility without enabling pull or replay transport. */\n async refreshLocalSession(): Promise<void> {\n const generation = this.#generation;\n if (!(await this.#restoreCurrentGeneration(generation))) return;\n await this.#discoverLocalScopes();\n await this.#restoreInterruptedCommands();\n await this.#refreshState();\n }\n\n async resetSession(): Promise<void> {\n this.revokeSession();\n await Promise.allSettled([this.#replicaMutations.drain(), ...this.#flushTransitions]);\n await this.#waitForSendingTransitions();\n await this.#restoreInterruptedCommands();\n this.#activeUserId = null;\n this.#knownScopes.clear();\n this.#pendingPullScopes.clear();\n this.#commands.set([]);\n this.#pullAttentions.set([]);\n this.#scheduleRetry(null);\n }\n\n /** Synchronously invalidate in-flight enqueue and transport work owned by the current session. */\n revokeSession(): void {\n this.#invalidateFlush();\n this.#foregroundScopePolicy = null;\n }\n\n enqueue<T>(request: EnqueueOfflineCommand<T>, options: { flush?: boolean } = {}): Promise<string> {\n return this.#mutationAdmission.run(() => {\n const generation = this.#generation;\n return this.#serializeReplicaMutation((repository) => this.#enqueue(request, options, generation, undefined, repository));\n });\n }\n\n /**\n * Reads, derives, and commits one Outbox command, then rematerializes its\n * aggregate from confirmed replica values plus remaining FIFO intents.\n */\n enqueuePrepared<T>(\n prepare: (repository: OfflineRepository) => Promise<PreparedOfflineCommand<T>>,\n options: { flush?: boolean } = {},\n ): Promise<string> {\n return this.#mutationAdmission.run(() => {\n const generation = this.#generation;\n return this.#serializeReplicaMutation(async (repository) => {\n await this.#ensureInitialized();\n if (!this.#isCurrent(generation)) throw new Error('Offline session changed before prepared enqueue.');\n const prepared = await prepare(repository);\n return this.#enqueue(prepared.request, options, generation, undefined, repository);\n });\n });\n }\n\n /**\n * Prepares and commits multiple Outbox commands as one serialized replica\n * transaction under a single captured session generation.\n *\n * All entries are prepared and validated before any write. Empty batches,\n * overlapping aggregate intents, and overlapping replica footprints are\n * rejected with no durable state change.\n */\n enqueuePreparedBatch<T>(\n prepare: (repository: OfflineRepository) => Promise<readonly PreparedOfflineCommand<T>[]>,\n options: PreparedOfflineBatchOptions = {},\n ): Promise<readonly string[]> {\n return this.#mutationAdmission.run(() => {\n const generation = this.#generation;\n return this.#serializeReplicaMutation(async (repository) => {\n await this.#ensureInitialized();\n if (!this.#isCurrent(generation)) throw new Error('Offline session changed before prepared batch enqueue.');\n const prepared = await prepare(repository);\n return this.#enqueuePreparedBatch(prepared, options, generation, repository);\n });\n });\n }\n\n /**\n * Atomically replaces a resolved durable command with a newly prepared command.\n *\n * Use this after an authoritative conflict read. The old intent remains durable\n * until validation, capacity checks, optimistic projection and replacement\n * command preparation have all succeeded.\n */\n replacePrepared<T>(\n commandId: string,\n prepare: (repository: OfflineRepository) => Promise<PreparedOfflineCommand<T>>,\n options: { flush?: boolean } = {},\n ): Promise<string> {\n const generation = this.#generation;\n return this.#serializeReplicaMutation(async (repository) => {\n await this.#ensureInitialized();\n if (!this.#isCurrent(generation)) throw new Error('Offline session changed before prepared replacement.');\n const knownCommands = await this.#readKnownCommands();\n const replaced = knownCommands.find((command) => command.commandId === commandId);\n if (!replaced) throw new Error(`Offline command ${commandId} no longer exists.`);\n this.#assertDiscardable([replaced]);\n if (\n knownCommands.some((command) => command.commandId !== commandId && this.#aggregateKey(command) === this.#aggregateKey(replaced))\n ) {\n throw new Error('Offline replacement requires the command to be the only pending intent for its aggregate.');\n }\n const prepared = await prepare(repository);\n return this.#enqueue(prepared.request, options, generation, replaced, repository);\n });\n }\n\n /**\n * Atomically rematerializes every unresolved intent for one aggregate.\n *\n * This is the conflict-recovery boundary for ordered intent chains: the old\n * chain remains durable until every replacement has been prepared and the\n * complete chain can be committed in one replica transaction.\n */\n replacePreparedAggregate<T>(\n commandId: string,\n prepare: (repository: OfflineRepository, commands: readonly OfflineCommand[]) => Promise<readonly PreparedOfflineCommand<T>[]>,\n options: PreparedOfflineBatchOptions = {},\n ): Promise<readonly string[]> {\n const generation = this.#generation;\n return this.#serializeReplicaMutation(async (repository) => {\n await this.#ensureInitialized();\n if (!this.#isCurrent(generation)) throw new Error('Offline session changed before prepared aggregate replacement.');\n const knownCommands = await this.#readKnownCommands();\n const selected = knownCommands.find((command) => command.commandId === commandId);\n if (!selected) throw new Error(`Offline command ${commandId} no longer exists.`);\n const aggregateKey = this.#aggregateKey(selected);\n const replaced = knownCommands.filter((command) => this.#aggregateKey(command) === aggregateKey);\n this.#assertDiscardable(replaced);\n const prepared = await prepare(repository, replaced);\n if (prepared.length !== replaced.length) {\n throw new Error('Offline aggregate replacement must preserve the ordered intent count.');\n }\n const session = await this.#beginEnqueueSession(generation);\n const materializations: MaterializedOfflineEnqueue[] = [];\n for (const [index, entry] of prepared.entries()) {\n this.#assertEnqueueScope(session, entry.request.scopeId);\n materializations.push(await this.#materializeEnqueue(session.userId, entry.request, replaced[index]));\n }\n const retained = knownCommands.filter((command) => !replaced.some((item) => item.commandId === command.commandId));\n this.#assertDistinctBatchFootprints(materializations, retained, true);\n await this.#assertOutboxCapacity(\n session.userId,\n materializations.map((item) => item.command),\n replaced.map((command) => command.commandId),\n knownCommands,\n );\n options.assertCurrent?.();\n await this.#commitMaterializedEnqueues(\n materializations,\n generation,\n options,\n replaced.map((command) => command.commandId),\n repository,\n );\n return materializations.map((item) => item.command.commandId);\n });\n }\n\n /**\n * Serializes a product-owned replica projection with enqueue and command ACK\n * reconciliation. For read/derive/write cache updates, prefer\n * `runSerializedReplicaMutation` so the read is serialized as well.\n */\n async transactReplica(transaction: OfflineReplicaTransaction): Promise<void> {\n await this.runSerializedReplicaMutation(async (repository) => {\n await repository.transactReplica(transaction);\n });\n }\n\n /**\n * Runs a product cache's replica read/derive/write sequence atomically with\n * enqueue and ACK projection. Use this for any repository reads that inform\n * a later transaction; `transactReplica` alone only serializes the write.\n */\n runSerializedReplicaMutation<T>(operation: (repository: OfflineRepository) => Promise<T>): Promise<T> {\n const generation = this.#generation;\n return this.#serializeReplicaMutation(async (repository) => {\n await this.#ensureInitialized();\n if (!this.#isCurrent(generation)) throw new Error('Offline session changed before serialized replica mutation.');\n const result = await operation(repository);\n if (this.#isCurrent(generation)) await this.#refreshState(generation);\n return result;\n });\n }\n\n #serializeReplicaMutation<T>(operation: (repository: OfflineRepository) => Promise<T>): Promise<T> {\n return this.#replicaMutations.run(operation);\n }\n\n async #enqueue<T>(\n request: EnqueueOfflineCommand<T>,\n options: { flush?: boolean },\n generation: number,\n replaced?: OfflineCommand,\n repository: OfflineRepository = this.#repository,\n ): Promise<string> {\n const session = await this.#beginEnqueueSession(generation);\n this.#assertEnqueueScope(session, request.scopeId);\n const materialization = await this.#materializeEnqueue(session.userId, request, replaced);\n const currentCommands = await this.#commandsForUser(session.userId);\n const retainedCommands = replaced ? currentCommands.filter((command) => command.commandId !== replaced.commandId) : currentCommands;\n this.#assertDistinctBatchFootprints([materialization], retainedCommands);\n await this.#assertOutboxCapacity(\n session.userId,\n [materialization.command],\n replaced ? [replaced.commandId] : undefined,\n currentCommands,\n );\n await this.#commitMaterializedEnqueues([materialization], generation, options, replaced ? [replaced.commandId] : undefined, repository);\n return materialization.command.commandId;\n }\n\n async #enqueuePreparedBatch<T>(\n prepared: readonly PreparedOfflineCommand<T>[],\n options: PreparedOfflineBatchOptions,\n generation: number,\n repository: OfflineRepository,\n ): Promise<readonly string[]> {\n if (prepared.length === 0) {\n throw new Error('Prepared offline batch must contain at least one command.');\n }\n const session = await this.#beginEnqueueSession(generation);\n const currentCommands = await this.#commandsForUser(session.userId);\n this.#rememberCreatedAt(currentCommands);\n const firstCreatedAt = Math.max(Date.now(), this.#lastCommandCreatedAt + 1);\n this.#lastCommandCreatedAt = firstCreatedAt + prepared.length - 1;\n const materializations: MaterializedOfflineEnqueue[] = [];\n for (const [index, entry] of prepared.entries()) {\n this.#assertEnqueueScope(session, entry.request.scopeId);\n materializations.push(await this.#materializeEnqueue(session.userId, entry.request, undefined, firstCreatedAt + index));\n }\n this.#assertDistinctBatchFootprints(materializations, currentCommands);\n await this.#assertOutboxCapacity(\n session.userId,\n materializations.map((item) => item.command),\n undefined,\n currentCommands,\n );\n options.assertCurrent?.();\n await this.#commitMaterializedEnqueues(materializations, generation, options, undefined, repository);\n return materializations.map((item) => item.command.commandId);\n }\n\n async #beginEnqueueSession(generation: number): Promise<OfflineSyncSession> {\n await this.#ensureInitialized();\n if (this.#options.mode === 'readCacheOnly') {\n throw new Error('This offline provider is configured as a read-only cache and cannot enqueue commands.');\n }\n const session = await this.#getLocalSession();\n if (!session) throw new Error('Cannot enqueue an offline command without an authenticated user');\n this.#assertSessionPrincipalBoundary(session);\n this.#setActiveUser(session.userId);\n if (!this.#isCurrent(generation)) {\n throw new Error('Offline session changed before the command could be persisted');\n }\n return session;\n }\n\n #assertEnqueueScope(session: OfflineSyncSession, scopeId: string): void {\n if (!session.scopes.some((candidate) => candidate.userId === session.userId && candidate.scopeId === scopeId)) {\n throw new Error(`Offline sync session does not include scope \"${scopeId}\".`);\n }\n this.noteScope({ userId: session.userId, scopeId });\n }\n\n async #materializeEnqueue<T>(\n userId: OfflinePrincipalId,\n request: EnqueueOfflineCommand<T>,\n replaced?: OfflineCommand,\n createdAt?: number,\n ): Promise<MaterializedOfflineEnqueue> {\n const scope = { userId, scopeId: request.scopeId };\n this.noteScope(scope);\n const commandIdentity = offlineCommandLookupIdentity(request.identity);\n const normalized = await this.#normalizeEnqueueRequest(scope, request, commandIdentity);\n const commandId = crypto.randomUUID();\n const sourceKey = this.#hooks.entityType(request);\n const localOnlyFootprint = this.#normalizedLocalOnlyFootprint(scope, request.localOnlyFootprint);\n if (replaced) this.#assertReplacementFootprint(replaced, localOnlyFootprint);\n let command: OfflineCommand = {\n ...scope,\n commandId,\n aggregateType: request.aggregateType,\n sourceKey,\n identity: commandIdentity,\n operation: request.operation,\n payload: normalized.payload,\n replicaMutation: request.replicaMutation ?? 'upsert',\n baseRevision: normalized.baseRevision,\n state: 'pending',\n attempts: 0,\n retryAt: null,\n createdAt: replaced?.createdAt ?? createdAt ?? (await this.#nextCommandCreatedAt(userId)),\n lastErrorCode: null,\n };\n if (localOnlyFootprint.length > 0) command = { ...command, localOnlyFootprint };\n if (\n replaced &&\n (replaced.userId !== command.userId ||\n replaced.scopeId !== command.scopeId ||\n replaced.aggregateType !== command.aggregateType ||\n replaced.sourceKey !== command.sourceKey ||\n canonicalOfflineCommandIdentity(replaced.identity) !== canonicalOfflineCommandIdentity(command.identity))\n ) {\n throw new Error('Offline replacement command must address the same aggregate and replica identity.');\n }\n const entityType = command.sourceKey;\n const schema = this.#entitySchema(entityType);\n if (schema.identity.kind === 'localOnly') {\n throw new Error(`Offline replica source \"${entityType}\" is local-only and cannot be added to the Outbox.`);\n }\n if (schema.identity.kind === 'generated' && request.identity.kind !== 'generated') {\n throw new Error(`Offline replica source \"${entityType}\" requires generated identity.`);\n }\n if (schema.identity.kind === 'naturalKey' && request.identity.kind !== 'natural') {\n throw new Error(`Offline replica source \"${entityType}\" requires natural identity.`);\n }\n if (request.replicaMutation === 'delete' && !this.#repository.getReplicaRowIncludingPendingDelete) {\n throw new Error('Offline repository does not support durable replica delete tombstones.');\n }\n const existing = await this.#getReplicaRowForSync(scope, entityType, commandIdentity);\n const generatedIdentity = request.identity.kind === 'generated' ? request.identity : null;\n const initialRemoteId = this.#initialRemoteId(\n schema,\n existing?.identity.kind === 'generated' ? existing.identity.remoteId : null,\n generatedIdentity?.remoteId,\n );\n this.#assertRemoteIdHint(\n schema,\n existing?.identity.kind === 'generated' ? existing.identity.remoteId : null,\n generatedIdentity?.remoteIdHint,\n );\n const naturalKey =\n schema.identity.kind === 'naturalKey' && request.identity.kind === 'natural'\n ? request.identity.naturalKey\n : existing\n ? offlineNaturalKeyFromValues(schema, existing.values)\n : null;\n if (\n schema.identity.kind === 'naturalKey' &&\n request.identity.kind === 'natural' &&\n canonicalOfflineRemoteIdentity(schema, { naturalKey: request.identity.naturalKey }) !==\n canonicalOfflineRemoteIdentity(schema, { naturalKey: naturalKey! })\n ) {\n throw new Error(`Offline command naturalKey must match replica identity for \"${entityType}\".`);\n }\n const remoteIdentity =\n schema.identity.kind === 'generated'\n ? initialRemoteId === null\n ? null\n : { remoteId: initialRemoteId }\n : schema.identity.kind === 'naturalKey'\n ? { naturalKey: naturalKey! }\n : null;\n if (schema.identity.kind === 'naturalKey') {\n const canonicalValuesKey = canonicalOfflineRemoteIdentity(schema, remoteIdentity!);\n if (\n existing &&\n canonicalOfflineRemoteIdentity(schema, {\n naturalKey:\n existing.identity.kind === 'natural' ? existing.identity.naturalKey : offlineNaturalKeyFromValues(schema, existing.values)!,\n }) !== canonicalValuesKey\n ) {\n throw new Error(`Offline replica naturalKey is immutable and must match command identity for \"${entityType}\".`);\n }\n }\n if (remoteIdentity !== null) {\n const mapped = await this.#repository.getReplicaRowByRemoteIdentity(scope, entityType, remoteIdentity);\n if (mapped !== null && !commandIdentityMatchesReplicaRow(schema, mapped, commandIdentity)) {\n if ('remoteId' in remoteIdentity) {\n throw new Error(`Offline replica remote id ${String(remoteIdentity.remoteId)} is already mapped to another row.`);\n }\n throw new Error(`Offline replica remote identity is already mapped to another row.`);\n }\n }\n this.#canonicalJson(normalized.payload);\n const seedBaseRow = existing\n ? undefined\n : request.identity.kind === 'generated'\n ? {\n ...scope,\n sourceKey,\n identity: { kind: 'generated' as const, localId: request.identity.localId, remoteId: initialRemoteId },\n values: {},\n confirmedValues: null,\n serverRevision: null,\n fetchedAt: Date.now(),\n syncState: 'pending' as const,\n }\n : request.identity.kind === 'natural'\n ? {\n ...scope,\n sourceKey,\n identity: { kind: 'natural' as const, naturalKey: request.identity.naturalKey },\n values: { ...request.identity.naturalKey },\n confirmedValues: null,\n serverRevision: null,\n fetchedAt: Date.now(),\n syncState: 'pending' as const,\n }\n : null;\n return { command, seedBaseRow };\n }\n\n #assertDistinctBatchFootprints(\n entries: readonly MaterializedOfflineEnqueue[],\n existingCommands: readonly OfflineCommand[],\n allowOneAggregate = false,\n ): void {\n const aggregates = new Set<string>();\n const replicaKeys = new Set<string>();\n const existingFootprints = new Map<string, string>();\n for (const command of existingCommands) {\n const aggregate = this.#aggregateKey(command);\n for (const key of this.#commandFootprintKeys(command)) existingFootprints.set(key, aggregate);\n }\n for (const entry of entries) {\n const aggregate = this.#aggregateKey(entry.command);\n if (aggregates.has(aggregate) && !allowOneAggregate) {\n throw new Error('Prepared offline batch contains overlapping aggregate intents.');\n }\n aggregates.add(aggregate);\n for (const key of this.#commandFootprintKeys(entry.command)) {\n if (replicaKeys.has(key) && !allowOneAggregate) {\n throw new Error('Prepared offline batch contains overlapping replica footprints.');\n }\n const existingAggregate = existingFootprints.get(key);\n if (existingAggregate !== undefined && existingAggregate !== aggregate) {\n throw new Error('Offline commands for different aggregates cannot share a replica footprint.');\n }\n replicaKeys.add(key);\n }\n }\n }\n\n #commandFootprintKeys(command: OfflineCommand): readonly string[] {\n const identity =\n command.identity.kind === 'generated'\n ? offlineGeneratedReplicaIdentity(command.identity.localId, null)\n : ({ kind: 'natural', naturalKey: command.identity.naturalKey } as const);\n return [this.#replicaRowKey({ ...command, identity }), ...commandFootprintKeys(command).map((key) => this.#replicaRowKey(key))];\n }\n\n async #commitMaterializedEnqueues(\n entries: readonly MaterializedOfflineEnqueue[],\n generation: number,\n options: { flush?: boolean },\n removeCommandIds?: readonly string[],\n repository: OfflineRepository = this.#repository,\n ): Promise<void> {\n if (generation !== this.#generation) {\n throw new Error('Offline session changed before the command could be persisted');\n }\n const known = await this.#readKnownCommands();\n const remaining = [\n ...known.filter((command) => !(removeCommandIds ?? []).includes(command.commandId)),\n ...entries.map((entry) => entry.command),\n ].sort(compareOfflineCommands);\n const affected = new Map<string, OfflineCommand>();\n const seeds = new Map<string, OfflineReplicaRow | null>();\n for (const entry of entries) {\n affected.set(this.#aggregateKey(entry.command), entry.command);\n if (entry.seedBaseRow !== undefined) seeds.set(this.#aggregateKey(entry.command), entry.seedBaseRow);\n }\n const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, seeds);\n await repository.transactReplica({\n putRows: rematerialized.putRows,\n removeRows: rematerialized.removeRows,\n putCommands: entries.map((entry) => entry.command),\n removeCommandIds,\n });\n await this.#refreshState().catch((error) => this.#reportError(error));\n if (options.flush !== false && this.#network.connected()) this.#flushInBackground();\n }\n\n #normalizedLocalOnlyFootprint(\n scope: OfflineScope,\n footprint: readonly OfflineReplicaRowKey[] | undefined,\n ): readonly OfflineReplicaRowKey[] {\n if (!footprint || footprint.length === 0) return [];\n const seen = new Set<string>();\n return footprint.map((key) => {\n this.#assertLocalOnlyFootprintKey(scope, key);\n const canonical = this.#replicaRowKey(key);\n if (seen.has(canonical)) throw new Error(`Prepared offline enqueue contains duplicate replica row ${canonical}.`);\n seen.add(canonical);\n return this.#minimalReplicaRowKey(key);\n });\n }\n\n #assertLocalOnlyFootprintKey(scope: OfflineScope, key: OfflineReplicaRowKey): void {\n if (key.userId !== scope.userId || key.scopeId !== scope.scopeId) {\n throw new Error('Prepared offline enqueue localOnly footprint must use the command scope.');\n }\n if (this.#entitySchema(key.sourceKey).identity.kind !== 'localOnly') {\n throw new Error(`Prepared offline enqueue footprint may only declare localOnly source \"${key.sourceKey}\".`);\n }\n if (key.identity.kind !== 'local') {\n throw new Error('Prepared offline enqueue footprint must use local identity.');\n }\n }\n\n #assertReplacementFootprint(replaced: OfflineCommand, next: readonly OfflineReplicaRowKey[]): void {\n const previous = new Set(commandFootprintKeys(replaced).map((key) => this.#replicaRowKey(key)));\n const incoming = new Set(next.map((key) => this.#replicaRowKey(key)));\n if (previous.size !== incoming.size || [...previous].some((key) => !incoming.has(key))) {\n throw new Error('Offline replacement must preserve the localOnly footprint.');\n }\n }\n\n #minimalReplicaRowKey(key: OfflineReplicaRowKey): OfflineReplicaRowKey {\n return {\n userId: key.userId,\n scopeId: key.scopeId,\n sourceKey: key.sourceKey,\n identity: key.identity,\n };\n }\n\n #replicaRowKey(key: OfflineReplicaRowKey): string {\n return canonicalOfflineReplicaRowKey(this.#entitySchema(key.sourceKey), key);\n }\n\n async #assertOutboxCapacity(\n userId: OfflinePrincipalId,\n newCommands: readonly OfflineCommand[],\n excludingCommandIds?: readonly string[],\n knownCommands?: readonly OfflineCommand[],\n ): Promise<void> {\n const currentCommands = knownCommands ?? (await this.#commandsForUser(userId));\n const commands = excludingCommandIds\n ? currentCommands.filter((candidate) => !excludingCommandIds.includes(candidate.commandId))\n : currentCommands;\n const maxCommands = this.#options.outboxLimits?.maxCommandsPerUser ?? DEFAULT_MAX_OUTBOX_COMMANDS_PER_USER;\n const maxBytes = this.#options.outboxLimits?.maxBytesPerUser ?? DEFAULT_MAX_OUTBOX_BYTES_PER_USER;\n const currentBytes = this.#serializedOutboxBytes(commands);\n if (commands.length + newCommands.length > maxCommands) {\n throw new OfflineOutboxCapacityError('command_count', commands.length, currentBytes);\n }\n const nextBytes = this.#serializedOutboxBytes([...commands, ...newCommands]);\n if (nextBytes > maxBytes) {\n throw new OfflineOutboxCapacityError('serialized_bytes', commands.length, currentBytes);\n }\n }\n\n async #commandsForUser(userId: OfflinePrincipalId): Promise<OfflineCommand[]> {\n return this.#repository.getCommandsForUser\n ? this.#repository.getCommandsForUser(userId)\n : (\n await Promise.all(\n [...this.#knownScopes.values()].filter((scope) => scope.userId === userId).map((scope) => this.#repository.getCommands(scope)),\n )\n ).flat();\n }\n\n #serializedOutboxBytes(commands: readonly OfflineCommand[]): number {\n return new TextEncoder().encode(JSON.stringify(commands)).byteLength;\n }\n\n async discard(commandId: string, options: { flush?: boolean } = {}): Promise<void> {\n const generation = this.#generation;\n if (!(await this.#restoreCurrentGeneration(generation))) return;\n // A pull may have completed while transport was being cancelled. Re-read\n // and project the discard inside the same local mutation lane used by\n // enqueue, ACK, and pull application so an old before-image cannot replace\n // a newer authoritative row after its cursor has advanced.\n const command = await this.#replicaMutations.run(async (repository) => {\n const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);\n if (!current) return null;\n this.#assertDiscardable([current]);\n this.#invalidateFlush();\n await this.#discardCommands([current], repository);\n return current;\n });\n if (!command) return;\n await this.#restoreInterruptedCommands();\n await this.#refreshState();\n await this.#hooks.onCommandRemoved?.(command).catch((error) => this.#reportError(error));\n if (options.flush !== false && this.#network.connected()) this.#flushInBackground();\n }\n\n /** Clears a retry backoff/auth block selected explicitly by the user and sends the durable command now. */\n async retryNow(commandId: string): Promise<void> {\n const generation = this.#generation;\n if (!(await this.#restoreCurrentGeneration(generation))) return;\n this.#invalidateFlush();\n await this.#waitForSendingTransitions();\n await this.#restoreInterruptedCommands();\n const retried = await this.runSerializedReplicaMutation(async (repository) => {\n // Re-read only after every interrupted transport transition has settled.\n // An ACK may have removed the command while retryNow was waiting; never\n // resurrect such a command from an object captured before invalidation.\n const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);\n if (!current) return false;\n if (current.state !== 'retry_wait' && current.state !== 'blocked_auth' && current.serverCommitUnknown !== true) {\n throw new Error(`Offline command ${commandId} is not waiting for retry or reauthentication.`);\n }\n await repository.putCommand({\n ...current,\n state: 'pending',\n retryAt: null,\n lastErrorCode: null,\n });\n return true;\n });\n if (retried && this.#network.connected()) await this.flush();\n }\n\n async discardAllPending(): Promise<void> {\n const generation = this.#generation;\n if (!(await this.#restoreCurrentGeneration(generation))) return;\n const commands = await this.#replicaMutations.run(async (repository) => {\n const current = await this.#readKnownCommands();\n this.#assertDiscardable(current);\n this.#invalidateFlush();\n await this.#discardCommands(current, repository);\n return current;\n });\n await this.#refreshState();\n await Promise.all(commands.map((command) => this.#hooks.onCommandRemoved?.(command).catch((error) => this.#reportError(error))));\n }\n\n #assertDiscardable(commands: readonly OfflineCommand[]): void {\n const ambiguous = commands.filter(\n (command) => command.state === 'sending' || command.state === 'awaiting_pull' || command.serverCommitUnknown === true,\n );\n if (ambiguous.length > 0) {\n throw new OfflineCommandInFlightError(ambiguous.map((command) => command.commandId));\n }\n }\n\n #flushInBackground(): void {\n void this.#beginFlush(false).catch((error) => this.#reportError(error));\n }\n\n flush(): Promise<void> {\n const generation = this.#generation;\n return this.#flushAfterInitialization(generation);\n }\n\n async #flushAfterInitialization(generation: number): Promise<void> {\n if (!(await this.#restoreCurrentGeneration(generation))) return;\n return this.#beginFlush(true);\n }\n\n #beginFlush(explicitFull: boolean): Promise<void> {\n const isPartial = !explicitFull && this.#foregroundScopePolicy !== null;\n if (this.#flushPromise) {\n if (explicitFull && this.#partialFlushInFlight) {\n if (!this.#chainedFullFlush) {\n const generation = this.#generation;\n const partial = this.#flushPromise;\n const chain = partial\n .then(\n () => undefined,\n () => undefined,\n )\n .then(() => {\n if (!this.#isCurrent(generation)) return;\n return this.#beginFlush(true);\n })\n .finally(() => {\n if (this.#chainedFullFlush === chain) this.#chainedFullFlush = null;\n });\n this.#chainedFullFlush = chain;\n }\n return this.#chainedFullFlush;\n }\n return this.#flushPromise;\n }\n const generation = this.#generation;\n const promise = this.#runFlush(generation, explicitFull).finally(() => {\n this.#flushTransitions.delete(promise);\n if (this.#flushPromise === promise) {\n this.#flushPromise = null;\n this.#partialFlushInFlight = false;\n }\n });\n this.#flushPromise = promise;\n this.#partialFlushInFlight = isPartial;\n this.#flushTransitions.add(promise);\n return promise;\n }\n\n async #runFlush(generation: number, explicitFull: boolean): Promise<void> {\n if (!this.#isCurrent(generation)) return;\n if (!this.#network.connected()) {\n await this.#refreshState(generation);\n return;\n }\n if (!(await this.#discoverScopes(generation))) return;\n const isPartial = !explicitFull && this.#foregroundScopePolicy !== null;\n const pullScopes = isPartial\n ? this.#scopesForPartialPull(this.#foregroundScopePolicy!, await this.#readKnownCommands())\n : [...this.#knownScopes.values()];\n const prePullFailures: unknown[] = [];\n let fatalPullFailure: unknown | null = null;\n const pulledScopeKeys = new Set<string>();\n for (const scope of pullScopes) {\n if (!this.#isCurrent(generation) || !this.#network.connected()) return;\n const pullScope = async (): Promise<void> => {\n await this.#pull.pull(scope);\n await this.#markScopeReconciled(scope, generation);\n pulledScopeKeys.add(this.#scopeKey(scope));\n };\n const pull = await pullScope().then(\n () => ({ status: 'fulfilled' as const }),\n (error: unknown) => ({ status: 'rejected' as const, error }),\n );\n if (pull.status === 'rejected') {\n prePullFailures.push(pull.error);\n if (this.#isFatalPullFailure(pull.error)) {\n // Auth/upgrade-driven recovery only: stop remaining scopes immediately.\n fatalPullFailure = fatalPullFailure ?? pull.error;\n await this.#persistFatalPullAttentions(pull.error, scope, pullScopes, generation);\n break;\n }\n if (this.#pendingPullScopes.has(this.#scopeKey(scope))) {\n this.#scheduleRetry(Date.now() + POST_SEND_PULL_RETRY_MS);\n }\n }\n }\n const dirtyScopes = new Map<string, OfflineScope>();\n const sendWorkerFailures: unknown[] = [];\n while (this.#network.connected() && this.#isCurrent(generation) && fatalPullFailure === null) {\n const known = await this.#readKnownCommands();\n const groups = this.#eligibleAggregateGroups(known).filter((group) =>\n group.some(\n (command) =>\n (command.state === 'pending' || command.state === 'retry_wait') &&\n pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })),\n ),\n );\n if (!this.#isCurrent(generation)) return;\n if (groups.length === 0) break;\n const pendingBefore = known.filter((command) => command.state === 'pending' || command.state === 'retry_wait').length;\n let cursor = 0;\n const workers = Array.from({ length: Math.min(MAX_PARALLEL_AGGREGATES, groups.length) }, async () => {\n while (cursor < groups.length) {\n const group = groups[cursor++];\n if (group && this.#isCurrent(generation)) await this.#sendAggregate(group, generation, dirtyScopes, pulledScopeKeys);\n }\n });\n // Drain with allSettled so one rejecting worker cannot skip sibling settlement or post-send pull.\n const settled = await Promise.allSettled(workers);\n for (const result of settled) {\n if (result.status === 'rejected') sendWorkerFailures.push(result.reason);\n }\n if (sendWorkerFailures.length > 0) break;\n const pendingAfter = (await this.#readKnownCommands()).filter(\n (command) => command.state === 'pending' || command.state === 'retry_wait',\n ).length;\n if (pendingAfter >= pendingBefore) break;\n }\n for (const scope of dirtyScopes.values()) {\n this.#pendingPullScopes.set(this.#scopeKey(scope), scope);\n }\n const postPullFailures: unknown[] = [];\n // Fatal pre-pull skips pending post-pulls; recovery is auth/upgrade-driven, not timer retry.\n // Fatal post-send pull stops remaining pending scopes the same way (ACK preserved, no resend).\n if (fatalPullFailure === null) {\n const postPullScopes = [...this.#pendingPullScopes.values()];\n for (const scope of postPullScopes) {\n if (!this.#isCurrent(generation) || !this.#network.connected()) break;\n // A command response may contain only the aggregate's base row. Pull once per dirty scope so\n // sibling-table journal entries are visible before completed Outbox state reaches product UI.\n const pullScope = async (): Promise<void> => {\n await this.#pull.pull(scope);\n await this.#markScopeReconciled(scope, generation);\n };\n const pull = await pullScope().then(\n () => ({ status: 'fulfilled' as const }),\n (error: unknown) => ({ status: 'rejected' as const, error }),\n );\n if (pull.status === 'rejected') {\n if (this.#isFatalPullFailure(pull.error)) {\n fatalPullFailure = fatalPullFailure ?? pull.error;\n await this.#persistFatalPullAttentions(pull.error, scope, postPullScopes, generation);\n break;\n }\n postPullFailures.push(pull.error);\n }\n }\n }\n await this.#refreshState(generation);\n if (fatalPullFailure !== null) {\n // Auth/upgrade recovery only — never arm the 1s automatic flush retry.\n // Transported commands remain awaiting_pull for later auth/upgrade recovery.\n // Only the owning generation may clear the timer — a stale fatal must not disarm a\n // newer session's already-armed retry_wait / post-pull retry.\n if (this.#isCurrent(generation)) this.#scheduleRetry(null);\n throw fatalPullFailure;\n }\n const failures = [...prePullFailures, ...sendWorkerFailures, ...postPullFailures];\n if (failures.length > 0) {\n // Keep rejecting the flush promise after workers settle even when the session\n // was revoked mid-flight, so callers and ErrorHandler still observe the failure.\n if (this.#isCurrent(generation)) {\n this.#scheduleRetry(Date.now() + POST_SEND_PULL_RETRY_MS);\n }\n throw failures[0];\n }\n if (this.#isCurrent(generation)) {\n for (const command of await this.#readKnownCommands()) {\n if (command.state !== 'awaiting_pull') continue;\n const scope = { userId: command.userId, scopeId: command.scopeId };\n this.#pendingPullScopes.set(this.#scopeKey(scope), scope);\n }\n }\n }\n\n #isFatalPullFailure(error: unknown): boolean {\n const status = this.#errorStatus(error);\n // Pull-protocol HTTP 409 is schema mismatch (distinct from command-send conflict\n // classification elsewhere in this service). Same classifier for pre-pull and post-send pull.\n if (status === 401 || status === 403 || status === 409) return true;\n return error instanceof OfflineReplicaSchemaMismatchError;\n }\n\n #pullAttentionReason(error: unknown): OfflinePullAttentionReason | null {\n if (error instanceof OfflineReplicaSchemaMismatchError) return 'schema_upgrade_required';\n const status = this.#errorStatus(error);\n if (status === 409) return 'schema_upgrade_required';\n if (status === 401 || status === 403) return 'authorization_required';\n return null;\n }\n\n /**\n * Persists durable pull attentions for a current-generation fatal pull.\n * Schema/409 marks all attempted pull scopes; 401 marks every known principal scope;\n * 403 marks only the failing scope. Stale generations must not mutate a newer session.\n */\n async #persistFatalPullAttentions(\n error: unknown,\n failingScope: OfflineScope,\n attemptedScopes: readonly OfflineScope[],\n generation: number,\n ): Promise<void> {\n if (!this.#isCurrent(generation)) return;\n const reason = this.#pullAttentionReason(error);\n if (reason === null) return;\n const status = this.#errorStatus(error);\n // Snapshot synchronously before any await so a concurrent session switch cannot retarget scopes.\n const scoped =\n status === 403\n ? [failingScope]\n : status === 401\n ? [...this.#knownScopes.values()].filter((scope) => scope.userId === failingScope.userId)\n : attemptedScopes.filter((scope) => scope.userId === failingScope.userId);\n const scopes = scoped.length > 0 ? scoped : [failingScope];\n const attentions: OfflinePullAttention[] = scopes.map((scope) => {\n const attention: OfflinePullAttention = {\n userId: scope.userId,\n scopeId: scope.scopeId,\n reason,\n };\n if (status > 0) attention.status = status;\n return attention;\n });\n if (!this.#isCurrent(generation)) return;\n await this.#repository.transactReplica({ putPullAttentions: attentions });\n }\n\n #setForegroundScopePolicy(foregroundScopeIds?: readonly string[]): void {\n this.#foregroundScopePolicy = foregroundScopeIds !== undefined ? foregroundScopeIds : null;\n }\n\n #scopesForPartialPull(foregroundScopeIds: readonly string[], commands: readonly OfflineCommand[]): OfflineScope[] {\n const foregroundScopeSet = new Set(foregroundScopeIds);\n const outboxScopeKeys = new Set(commands.map((command) => this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })));\n const attentionScopeKeys = new Set(this.#pullAttentions().map((attention) => this.#scopeKey(attention)));\n return [...this.#knownScopes.values()].filter(\n (scope) =>\n foregroundScopeSet.has(scope.scopeId) ||\n outboxScopeKeys.has(this.#scopeKey(scope)) ||\n attentionScopeKeys.has(this.#scopeKey(scope)) ||\n this.#pendingPullScopes.has(this.#scopeKey(scope)),\n );\n }\n\n #eligibleAggregateGroups(commands: OfflineCommand[]): OfflineCommand[][] {\n const now = Date.now();\n const groups = new Map<string, OfflineCommand[]>();\n for (const command of commands) {\n const key = this.#aggregateKey(command);\n const group = groups.get(key) ?? [];\n group.push(command);\n groups.set(key, group);\n }\n return [...groups.values()].filter((group) =>\n group.some((command) => command.state === 'pending' || (command.state === 'retry_wait' && (command.retryAt ?? 0) <= now)),\n );\n }\n\n async #sendAggregate(\n commands: OfflineCommand[],\n generation: number,\n dirtyScopes: Map<string, OfflineScope>,\n pulledScopeKeys: ReadonlySet<string>,\n ): Promise<void> {\n for (const command of commands) {\n if (!this.#isCurrent(generation)) return;\n if (command.state === 'awaiting_pull') continue;\n if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now()) break;\n if (!['pending', 'retry_wait'].includes(command.state)) break;\n // User-scoped aggregates ignore scopeId in the FIFO key, so later commands may\n // belong to scopes that failed pre-pull even when the head was admitted.\n if (!pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId }))) break;\n let sending = await this.#claimSendingCommand(command, generation);\n if (!sending) return;\n if (!this.#isCurrent(generation)) return;\n await this.#refreshState(generation);\n if (!this.#isCurrent(generation)) return;\n const claimedCommand = sending;\n const readRow = async (): Promise<OfflineReplicaRow | null> => this.#rowForCommand(claimedCommand);\n const rowResult = await readRow().then(\n (row) => ({ status: 'fulfilled' as const, row }),\n (error: unknown) => ({ status: 'rejected' as const, error }),\n );\n if (rowResult.status === 'rejected') {\n if (!this.#isCurrent(generation)) return;\n await this.#persistFailedCommand(sending, rowResult.error, generation, null, sending.serverCommitUnknown === true);\n throw rowResult.error;\n }\n const row = rowResult.row;\n if (!row) {\n const error = new Error(\n `Offline replica row not found: ${sending.aggregateType}/${canonicalOfflineCommandIdentity(sending.identity)}`,\n );\n await this.#persistFailedCommand(sending, error, generation, null, sending.serverCommitUnknown === true);\n throw error;\n }\n const priorCommitUnknown = sending.serverCommitUnknown === true;\n const transportCommand = await this.#markTransportStarted(sending, generation);\n if (!transportCommand) return;\n sending = transportCommand;\n const executeCommand = async (): Promise<OfflineCommandResult> =>\n this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));\n const execution = await executeCommand().then(\n (result) => ({ status: 'fulfilled' as const, result }),\n (error: unknown) => ({ status: 'rejected' as const, error }),\n );\n if (execution.status === 'rejected') {\n if (!this.#isCurrent(generation)) return;\n const commitUnknown = this.#executor.provesCommandNotCommitted?.(execution.error, sending)\n ? false\n : priorCommitUnknown || this.#serverCommitCouldBeUnknown(execution.error);\n await this.#persistFailedCommand(sending, execution.error, generation, row, commitUnknown);\n if (!this.#isClassifiableTransportError(execution.error)) throw execution.error;\n break;\n }\n const result = execution.result;\n if (!this.#isCurrent(generation)) return;\n const completeCommand = async (): Promise<void> => this.#completeCommand(commands, sending, result, generation);\n const completion = await completeCommand().then(\n () => ({ status: 'fulfilled' as const }),\n (error: unknown) => ({ status: 'rejected' as const, error }),\n );\n if (completion.status === 'rejected') {\n if (!this.#isCurrent(generation)) return;\n await this.#persistFailedCommand(sending, completion.error, generation, row, true);\n throw completion.error;\n }\n if (this.#isCurrent(generation)) {\n const scope = { userId: sending.userId, scopeId: sending.scopeId };\n dirtyScopes.set(this.#scopeKey(scope), scope);\n }\n }\n }\n\n async #normalizeEnqueueRequest<T>(\n scope: OfflineScope,\n request: EnqueueOfflineCommand<T>,\n commandIdentity: OfflineCommandIdentity,\n ): Promise<{ payload: T; baseRevision: string | number | null }> {\n let baseRevision = request.baseRevision ?? null;\n const sourceKey = this.#hooks.entityType(request);\n const row = await this.#getReplicaRowForSync(scope, sourceKey, commandIdentity);\n if (row?.serverRevision != null && row.serverRevision !== baseRevision) {\n baseRevision = row.serverRevision;\n }\n return { payload: request.payload, baseRevision };\n }\n\n async #completeCommand(\n commands: OfflineCommand[],\n command: OfflineCommand,\n result: OfflineCommandResult,\n generation: number,\n ): Promise<void> {\n return this.#serializeReplicaMutation((repository) => this.#completeCommandLocked(commands, command, result, generation, repository));\n }\n\n async #completeCommandLocked(\n commands: OfflineCommand[],\n command: OfflineCommand,\n result: OfflineCommandResult,\n generation: number,\n repository: OfflineRepository,\n ): Promise<void> {\n if (result.clearRemoteId === true && result.remoteId !== undefined) {\n throw new Error('Offline command cannot return remoteId and clearRemoteId together.');\n }\n if (result.clearRemoteId === true && result.serverRevision !== undefined) {\n throw new Error('Offline command cannot return serverRevision and clearRemoteId together.');\n }\n const latestCommands = (await this.#readKnownCommands()).filter(\n (candidate) => this.#aggregateKey(candidate) === this.#aggregateKey(command),\n );\n const latestIndex = latestCommands.findIndex((candidate) => candidate.commandId === command.commandId);\n if (latestIndex < 0) return;\n const revision = result.serverRevision;\n const following = latestCommands.slice(latestIndex + 1);\n const rebased =\n result.clearRemoteId === true\n ? following.map((item) => offlineCommandWithBaseRevision(item, null))\n : revision === undefined\n ? following\n : following.map((item) => offlineCommandWithBaseRevision(item, revision));\n const current = await this.#rowForCommand(command);\n if (!this.#isCurrent(generation)) return;\n if (!current) {\n throw new Error(`Offline replica row disappeared while completing command ${command.commandId}.`);\n }\n this.#assertServerRevision(result.serverRevision);\n const removesReplica = result.removeReplica === true || command.replicaMutation === 'delete';\n if (result.clearRemoteId === true && !removesReplica) {\n throw new Error('Offline command can clear remoteId only for a confirmed replica removal.');\n }\n const schema = this.#entitySchema(current.sourceKey);\n this.#assertCommandResultIdentity(schema, current, result);\n const resolvedRemoteId = this.#resolvedRemoteId(current, result);\n const reconciliationIdentity =\n current.identity.kind === 'generated'\n ? resolvedRemoteId === null\n ? undefined\n : { remoteId: resolvedRemoteId }\n : current.identity.kind === 'natural'\n ? { naturalKey: current.identity.naturalKey }\n : undefined;\n const awaitingPull: OfflineCommand = {\n ...command,\n state: 'awaiting_pull',\n retryAt: null,\n lastErrorCode: null,\n serverCommitUnknown: false,\n ...(reconciliationIdentity ? { reconciliationIdentity } : {}),\n };\n latestCommands.splice(latestIndex, 1 + rebased.length, awaitingPull, ...rebased);\n const identityUpdatedBase: OfflineReplicaRow = {\n ...current,\n identity:\n current.identity.kind === 'generated'\n ? {\n ...current.identity,\n remoteId: result.clearRemoteId === true ? null : resolvedRemoteId,\n }\n : current.identity,\n serverRevision: result.clearRemoteId === true ? null : (revision ?? current.serverRevision),\n fetchedAt: Date.now(),\n };\n const rematerialized = await this.#rematerializeAggregate(awaitingPull, latestCommands, identityUpdatedBase);\n if (!this.#isCurrent(generation)) return;\n await repository.transactReplica({\n putRows: rematerialized.putRows,\n releaseRemoteIds:\n result.clearRemoteId === true && current.identity.kind === 'generated' && current.identity.remoteId !== null\n ? [\n {\n userId: current.userId,\n scopeId: current.scopeId,\n sourceKey: current.sourceKey,\n identity: current.identity,\n remoteId: current.identity.remoteId,\n },\n ]\n : undefined,\n removeRows: rematerialized.removeRows,\n putCommands: [awaitingPull, ...rebased],\n });\n const scope = { userId: command.userId, scopeId: command.scopeId };\n this.#pendingPullScopes.set(this.#scopeKey(scope), scope);\n commands.splice(0, commands.length, ...latestCommands);\n }\n\n async #rowForCommand(command: OfflineCommand): Promise<OfflineReplicaRow | null> {\n const scope = { userId: command.userId, scopeId: command.scopeId };\n const entityType = this.#entityType(command);\n return this.#getReplicaRowForSync(scope, entityType, command.identity);\n }\n\n #getReplicaRowForSync(scope: OfflineScope, sourceKey: string, identity: OfflineCommandIdentity): Promise<OfflineReplicaRow | null> {\n return (\n this.#repository.getReplicaRowIncludingPendingDelete?.(scope, sourceKey, identity) ??\n this.#repository.getReplicaRow(scope, sourceKey, identity)\n );\n }\n\n #replicaState(state: OfflineCommand['state']): OfflineReplicaSyncState {\n if (state === 'blocked_auth' || state === 'rejected' || state === 'conflict') return state;\n return 'pending';\n }\n\n #entityType(command: Pick<OfflineCommand, 'sourceKey'>): string {\n return command.sourceKey;\n }\n\n #entitySchema(sourceKey: string): OfflineReplicaEntitySchema<Record<string, unknown>> {\n const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);\n if (!schema) throw new Error(`Unknown offline replica source key \"${sourceKey}\".`);\n return schema;\n }\n\n async #discardCommands(discarded: readonly OfflineCommand[], repository: OfflineRepository): Promise<void> {\n const all = await this.#readKnownCommands();\n const discardedIds = new Set(discarded.map((command) => command.commandId));\n const affected = new Map<string, OfflineCommand>();\n for (const command of discarded) affected.set(this.#aggregateKey(command), command);\n const remaining = all.filter((item) => !discardedIds.has(item.commandId));\n const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining);\n await repository.transactReplica({\n putRows: rematerialized.putRows,\n removeRows: rematerialized.removeRows,\n removeCommandIds: [...discardedIds],\n });\n }\n\n async #rematerializeAffectedAggregates(\n affected: ReadonlyMap<string, OfflineCommand>,\n remaining: readonly OfflineCommand[],\n seeds: ReadonlyMap<string, OfflineReplicaRow | null> = new Map(),\n ): Promise<Pick<OfflineReplicaTransaction, 'putRows' | 'removeRows'>> {\n const putRows: OfflineReplicaRow[] = [];\n const removeRows: OfflineReplicaRowKey[] = [];\n for (const [key, command] of affected) {\n const remainingForAggregate = remaining.filter((item) => this.#aggregateKey(item) === key);\n const footprintCommands = [...remainingForAggregate, ...[...affected.values()].filter((item) => this.#aggregateKey(item) === key)];\n const rematerialized = await this.#rematerializeAggregate(\n command,\n remainingForAggregate,\n seeds.has(key) ? seeds.get(key) : undefined,\n footprintCommands,\n );\n putRows.push(...(rematerialized.putRows ?? []));\n removeRows.push(...(rematerialized.removeRows ?? []));\n }\n return { putRows, removeRows };\n }\n\n async #rematerializeAggregate(\n command: OfflineCommand,\n remaining: readonly OfflineCommand[],\n baseRow = undefined as OfflineReplicaRow | null | undefined,\n footprintCommands = remaining,\n ): Promise<Pick<OfflineReplicaTransaction, 'putRows' | 'removeRows'>> {\n const current = baseRow === undefined ? await this.#rowForCommand(command) : baseRow;\n const projection = this.#replicaMutations.projectAggregateIntent({\n baseRow: current,\n localOnlyRows: await this.#localOnlyRowsForCommands(footprintCommands),\n commands: remaining,\n trigger: 'local',\n });\n if (isOfflineAggregateIntentConflict(projection)) {\n throw new Error('Offline aggregate intent projector cannot return conflict outside pull reconciliation.');\n }\n return offlineAggregateIntentMutations(projection, current);\n }\n\n async #localOnlyRowsForCommands(commands: readonly OfflineCommand[]): Promise<OfflineReplicaRow[]> {\n const keys = new Map<string, OfflineReplicaRowKey>();\n for (const command of commands) {\n for (const key of commandFootprintKeys(command)) {\n keys.set(this.#replicaRowKey(key), key);\n }\n }\n const rows = await Promise.all([...keys.values()].map((key) => this.#getLocalOnlyRow(key)));\n return rows.filter((row): row is OfflineReplicaRow => row !== null);\n }\n\n #getLocalOnlyRow(key: OfflineReplicaRowKey): Promise<OfflineReplicaRow | null> {\n const scope = { userId: key.userId, scopeId: key.scopeId };\n return (\n this.#repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity) ??\n this.#repository.getReplicaRow(scope, key.sourceKey, key.identity)\n );\n }\n\n #aggregateKey(command: OfflineCommand): string {\n const sourceKey = this.#entityType(command);\n const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);\n if (!schema) throw new Error(`Unknown offline replica source key \"${sourceKey}\".`);\n const partition = schema.scope === 'user' ? 'user' : `partition:${command.scopeId}`;\n return `${canonicalOfflinePrincipalId(command.userId)}:${partition}:${sourceKey}:${canonicalOfflineCommandIdentity(command.identity)}`;\n }\n\n #failedCommand(command: OfflineCommand, error: unknown, serverCommitUnknown: boolean): OfflineCommand {\n const status = this.#errorStatus(error);\n if (status === 401 || status === 403) {\n return { ...command, state: 'blocked_auth', lastErrorCode: String(status), serverCommitUnknown };\n }\n if (status === 409 || status === 412) {\n return { ...command, state: 'conflict', lastErrorCode: String(status), serverCommitUnknown };\n }\n if (status >= 400 && status < 500 && status !== 429) {\n return { ...command, state: 'rejected', lastErrorCode: String(status), serverCommitUnknown };\n }\n const retryAt = Date.now() + offlineRetryDelayMs(command.attempts, this.#retryRandom);\n return {\n ...command,\n state: 'retry_wait',\n retryAt,\n lastErrorCode: status > 0 ? String(status) : 'network',\n serverCommitUnknown,\n };\n }\n\n async #persistFailedCommand(\n command: OfflineCommand,\n error: unknown,\n generation: number,\n row?: OfflineReplicaRow | null,\n serverCommitUnknown = true,\n ): Promise<void> {\n const failed = this.#failedCommand(command, error, serverCommitUnknown);\n await this.#serializeReplicaMutation(async (repository) => {\n const current = row === undefined ? await this.#rowForCommand(command) : row;\n if (!this.#isCurrent(generation)) return;\n if (current) {\n await repository.transactReplica({\n putRows: [{ ...current, syncState: this.#replicaState(failed.state) }],\n putCommands: [failed],\n });\n } else {\n await repository.putCommand(failed);\n }\n });\n if (!this.#isCurrent(generation)) return;\n if (failed.state === 'retry_wait') this.#scheduleRetry(failed.retryAt);\n await this.#refreshState(generation);\n }\n\n #errorStatus(error: unknown): number {\n if (typeof error !== 'object' || error === null) return 0;\n const status = (error as { status?: unknown }).status;\n return typeof status === 'number' ? status : 0;\n }\n\n #isClassifiableTransportError(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n const status = (error as { status?: unknown }).status;\n return typeof status === 'number' && Number.isInteger(status) && status >= 0;\n }\n\n #serverCommitCouldBeUnknown(error: unknown): boolean {\n const status = this.#errorStatus(error);\n return status === 0 || status === 429 || status >= 500;\n }\n\n #reportError(error: unknown): void {\n queueMicrotask(() => this.#dispatchError(error));\n }\n\n #dispatchError(error: unknown): void {\n let result: unknown;\n try {\n result = (this.#errorHandler.handleError as (reportedError: unknown) => unknown)(error);\n } catch {\n return;\n }\n if (result instanceof Promise) {\n void result.catch(() => undefined);\n }\n }\n\n #assertServerRevision(revision: string | number | undefined): void {\n if (typeof revision === 'number' && !Number.isFinite(revision)) {\n throw new Error(`Offline command returned invalid serverRevision ${String(revision)}.`);\n }\n }\n\n #resolvedRemoteId(current: OfflineReplicaRow, result: OfflineCommandResult): OfflineGeneratedRemoteId | null {\n if (current.identity.kind !== 'generated') return null;\n const incoming = result.remoteId;\n if (incoming === undefined) return current.identity.remoteId;\n const schema = this.#entitySchema(current.sourceKey);\n assertOfflineReplicaGeneratedRemoteId(schema, incoming);\n if (current.identity.remoteId !== null && current.identity.remoteId !== incoming) {\n throw new Error(\n `Offline replica remote id is immutable: current=${String(current.identity.remoteId)}, incoming=${String(incoming)}.`,\n );\n }\n return incoming;\n }\n\n #initialRemoteId(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n current: OfflineGeneratedRemoteId | null,\n incoming: OfflineGeneratedRemoteId | null | undefined,\n ): OfflineGeneratedRemoteId | null {\n if (incoming === null || incoming === undefined) return current;\n assertOfflineReplicaGeneratedRemoteId(schema, incoming);\n if (current !== null && current !== incoming) {\n throw new Error(`Offline replica remote id is immutable: current=${String(current)}, incoming=${String(incoming)}.`);\n }\n return incoming;\n }\n\n #assertRemoteIdHint(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n current: OfflineGeneratedRemoteId | null,\n hint: OfflineGeneratedRemoteId | null | undefined,\n ): void {\n if (hint === null || hint === undefined) return;\n assertOfflineReplicaGeneratedRemoteId(schema, hint);\n if (current !== null && current !== hint) {\n throw new Error(`Offline replica remoteId hint does not match current=${String(current)}: incoming=${String(hint)}.`);\n }\n }\n\n #assertCommandResultIdentity(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n current: OfflineReplicaRow,\n result: OfflineCommandResult,\n ): void {\n if (result.clearRemoteId === true && schema.identity.kind !== 'generated') {\n throw new Error(`Offline command cannot clear remoteId for source \"${schema.sourceKey}\".`);\n }\n if (schema.identity.kind === 'naturalKey' && result.remoteId !== undefined) {\n throw new Error(`Offline command returned generated remote id for naturalKey source \"${schema.sourceKey}\".`);\n }\n if (schema.identity.kind !== 'generated' && result.remoteId !== undefined) {\n throw new Error(`Offline command returned generated remote id for source \"${schema.sourceKey}\" without generated identity.`);\n }\n if (schema.identity.kind === 'naturalKey' && result.confirmedValues !== undefined) {\n const currentKey =\n current.identity.kind === 'natural' ? current.identity.naturalKey : offlineNaturalKeyFromValues(schema, current.values)!;\n const confirmedKey = offlineNaturalKeyFromValues(schema, result.confirmedValues)!;\n if (\n canonicalOfflineRemoteIdentity(schema, { naturalKey: currentKey }) !==\n canonicalOfflineRemoteIdentity(schema, { naturalKey: confirmedKey })\n ) {\n throw new Error(`Offline replica naturalKey is immutable for \"${schema.sourceKey}\".`);\n }\n }\n }\n\n async #discoverScopes(generation = this.#generation): Promise<boolean> {\n const session = await this.#context.getSession();\n if (!this.#isCurrent(generation)) return false;\n if (!session) {\n return false;\n }\n this.#assertSessionPrincipalBoundary(session);\n this.#setActiveUser(session.userId);\n this.#knownScopes.clear();\n for (const scope of session.scopes) this.#knownScopes.set(this.#scopeKey(scope), scope);\n await this.#restorePendingPullScopes(session.userId, generation);\n await this.#prunePullAttentions(session.userId, generation);\n return true;\n }\n\n async #discoverLocalScopes(generation = this.#generation): Promise<boolean> {\n const session = await this.#getLocalSession();\n if (!this.#isCurrent(generation)) return false;\n if (!session) {\n this.#activeUserId = null;\n this.#knownScopes.clear();\n this.#pullAttentions.set([]);\n return true;\n }\n this.#assertSessionPrincipalBoundary(session);\n this.#setActiveUser(session.userId);\n this.#knownScopes.clear();\n for (const scope of session.scopes) this.#knownScopes.set(this.#scopeKey(scope), scope);\n await this.#restorePendingPullScopes(session.userId, generation);\n await this.#prunePullAttentions(session.userId, generation);\n return true;\n }\n\n #getLocalSession(): Promise<OfflineSyncSession | null> {\n return this.#context.getLocalSession?.() ?? this.#context.getSession();\n }\n\n #setActiveUser(userId: OfflinePrincipalId): void {\n if (this.#activeUserId === userId) return;\n this.#knownScopes.clear();\n this.#pendingPullScopes.clear();\n this.#pullAttentions.set([]);\n this.#activeUserId = userId;\n this.#lastCommandCreatedAt = 0;\n }\n\n #assertSessionPrincipalBoundary(session: OfflineSyncSession): void {\n canonicalOfflinePrincipalId(session.userId);\n for (const scope of session.scopes) {\n if (scope.userId !== session.userId) {\n throw new Error('Offline sync session scope belongs to a different principal.');\n }\n }\n }\n\n async #readKnownCommands(): Promise<OfflineCommand[]> {\n const commands = (await Promise.all([...this.#knownScopes.values()].map((scope) => this.#repository.getCommands(scope))))\n .flat()\n .sort(compareOfflineCommands);\n this.#rememberCreatedAt(commands);\n return commands;\n }\n\n async #nextCommandCreatedAt(userId: OfflinePrincipalId): Promise<number> {\n const commands = await this.#commandsForUser(userId);\n this.#rememberCreatedAt(commands);\n const createdAt = Math.max(Date.now(), this.#lastCommandCreatedAt + 1);\n this.#lastCommandCreatedAt = createdAt;\n return createdAt;\n }\n\n #rememberCreatedAt(commands: readonly OfflineCommand[]): void {\n for (const command of commands) this.#lastCommandCreatedAt = Math.max(this.#lastCommandCreatedAt, command.createdAt);\n }\n\n async #refreshState(generation = this.#generation): Promise<void> {\n const commands = await this.#readKnownCommands();\n const attentions =\n this.#activeUserId !== null && this.#repository.getPullAttentions ? await this.#repository.getPullAttentions(this.#activeUserId) : [];\n if (!this.#isCurrent(generation)) return;\n this.#commands.set(commands);\n this.#pullAttentions.set(attentions);\n const nextRetry = commands\n .filter((command) => command.state === 'retry_wait' && command.retryAt !== null)\n .reduce<number | null>((earliest, command) => Math.min(earliest ?? command.retryAt!, command.retryAt!), null);\n this.#scheduleRetry(nextRetry);\n }\n\n #scheduleRetry(retryAt: number | null): void {\n if (this.#retryTimer) clearTimeout(this.#retryTimer);\n this.#retryTimer = null;\n if (retryAt === null) return;\n this.#retryTimer = setTimeout(\n () => {\n this.#retryTimer = null;\n if (this.#network.connected()) this.#flushInBackground();\n },\n Math.max(0, retryAt - Date.now()),\n );\n }\n\n #invalidateFlush(): void {\n this.#generation += 1;\n this.#flushPromise = null;\n this.#partialFlushInFlight = false;\n this.#chainedFullFlush = null;\n this.#scheduleRetry(null);\n }\n\n #isCurrent(generation: number): boolean {\n return generation === this.#generation;\n }\n\n async #restoreInterruptedCommands(): Promise<void> {\n const commands = await this.#readKnownCommands();\n await Promise.all(\n commands\n .filter((command) => command.state === 'sending')\n .map((command) =>\n this.#repository.putCommand({\n ...command,\n state: 'pending',\n serverCommitUnknown: command.serverCommitUnknown ?? true,\n }),\n ),\n );\n }\n\n #claimSendingCommand(command: OfflineCommand, generation: number): Promise<OfflineCommand | null> {\n const transition = this.#serializeReplicaMutation(async (repository) => {\n if (!this.#isCurrent(generation)) return null;\n const scope = { userId: command.userId, scopeId: command.scopeId };\n const current = (await this.#repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);\n if (!current || !['pending', 'retry_wait'].includes(current.state)) return null;\n const sending: OfflineCommand = {\n ...current,\n state: 'sending',\n attempts: current.attempts + 1,\n retryAt: null,\n lastErrorCode: null,\n };\n await repository.putCommand(sending);\n return sending;\n });\n this.#sendingTransitions.add(transition);\n void transition.then(\n () => this.#sendingTransitions.delete(transition),\n () => this.#sendingTransitions.delete(transition),\n );\n return transition;\n }\n\n #markTransportStarted(command: OfflineCommand, generation: number): Promise<OfflineCommand | null> {\n return this.#serializeReplicaMutation(async (repository) => {\n if (!this.#isCurrent(generation)) return null;\n const scope = { userId: command.userId, scopeId: command.scopeId };\n const current = (await this.#repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);\n if (!current || current.state !== 'sending') return null;\n const transportCommand = { ...current, serverCommitUnknown: true };\n await repository.putCommand(transportCommand);\n return transportCommand;\n });\n }\n\n async #restorePendingPullScopes(userId: OfflinePrincipalId, generation: number): Promise<void> {\n const commands = await this.#readKnownCommands();\n if (!this.#isCurrent(generation) || this.#activeUserId !== userId) return;\n this.#pendingPullScopes.clear();\n for (const command of commands) {\n if (command.state !== 'awaiting_pull') continue;\n const scope = { userId: command.userId, scopeId: command.scopeId };\n const key = this.#scopeKey(scope);\n this.#pendingPullScopes.set(key, scope);\n }\n }\n\n async #prunePullAttentions(userId: OfflinePrincipalId, generation: number): Promise<void> {\n if (!this.#repository.getPullAttentions) return;\n const attentions = await this.#repository.getPullAttentions(userId);\n if (!this.#isCurrent(generation) || this.#activeUserId !== userId) return;\n const currentKeys = new Set(this.#knownScopes.keys());\n const revoked = attentions.filter((attention) => !currentKeys.has(this.#scopeKey(attention)));\n if (revoked.length > 0) {\n await this.#repository.transactReplica({ removePullAttentions: revoked });\n }\n }\n\n async #markScopeReconciled(scope: OfflineScope, generation: number): Promise<void> {\n if (!this.#isCurrent(generation)) return;\n await this.#repository.transactReplica({\n removePullAttentions: [scope],\n });\n if (!this.#isCurrent(generation)) return;\n this.#pendingPullScopes.delete(this.#scopeKey(scope));\n }\n\n async #waitForSendingTransitions(): Promise<void> {\n await Promise.allSettled([...this.#sendingTransitions]);\n }\n\n #canonicalJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map((item) => this.#canonicalJson(item)).join(',')}]`;\n if (value !== null && typeof value === 'object') {\n if (Object.getPrototypeOf(value) !== Object.prototype) {\n throw new OfflinePayloadValidationError();\n }\n return `{${Object.entries(value)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n .map(([key, item]) => `${JSON.stringify(key)}:${this.#canonicalJson(item)}`)\n .join(',')}}`;\n }\n if (typeof value === 'number' && !Number.isFinite(value)) {\n throw new OfflinePayloadValidationError();\n }\n const serialized = JSON.stringify(value);\n if (typeof serialized !== 'string') {\n throw new OfflinePayloadValidationError();\n }\n return serialized;\n }\n\n #scopeKey(scope: OfflineScope): string {\n return `${canonicalOfflinePrincipalId(scope.userId)}:${scope.scopeId}`;\n }\n}\n\nfunction compareOfflineCommands(left: OfflineCommand, right: OfflineCommand): number {\n return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);\n}\n","import { computed, ErrorHandler, inject, Injectable, InjectionToken, signal } from '@angular/core';\nimport { OFFLINE_KIT_OPTIONS, type OfflineMutationPersistenceAdapter } from './offline-kit-options';\nimport { OfflineMutationAdmissionService } from './offline-mutation-admission.service';\nimport { OfflineNetworkService } from './offline-network.service';\nimport { OfflineSyncService } from './offline-sync.service';\n\n/** Raised when disabling requires pending commands to be synchronized while transport is offline. */\nexport class OfflineMutationPersistenceRequiresOnlineError extends Error {\n constructor() {\n super('Pending offline mutations must be synchronized before persistence can be disabled.');\n this.name = 'OfflineMutationPersistenceRequiresOnlineError';\n }\n}\n\n/** Raised when pending commands remain after the disable transition attempted a flush. */\nexport class OfflineMutationPersistencePendingError extends Error {\n constructor(readonly pendingCount: number) {\n super('Pending offline mutations remain after synchronization.');\n this.name = 'OfflineMutationPersistencePendingError';\n }\n}\n\ntype OfflineMutationPersistenceState = 'initializing' | 'enabled' | 'disabling' | 'disabled';\n\nconst settledMutationPersistence = async (): Promise<void> => undefined;\n\nfunction invokeMutationPersistence<T>(operation: () => Promise<T>): Promise<T> {\n return new Promise<T>((resolve) => resolve(operation()));\n}\n\nfunction reportMutationPersistenceError(errorHandler: ErrorHandler, error: unknown): void {\n try {\n errorHandler.handleError(error);\n } catch {\n // Preference failure already degraded safely to disabled. Telemetry must not stop bootstrap.\n }\n}\n\n/** Read-only mutation admission signal consumed by the HTTP interceptor. */\nexport const OFFLINE_MUTATION_PERSISTENCE_ENABLED = new InjectionToken<() => boolean>('OFFLINE_MUTATION_PERSISTENCE_ENABLED', {\n factory: () => () => true,\n});\n\n/** Product adapter used by Kit to persist the device-local mutation preference. */\nexport const OFFLINE_MUTATION_PERSISTENCE_ADAPTER = new InjectionToken<OfflineMutationPersistenceAdapter | null>(\n 'OFFLINE_MUTATION_PERSISTENCE_ADAPTER',\n { factory: () => null },\n);\n\n/** Controls whether Kit accepts new durable mutations while leaving replica reads enabled. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineMutationPersistenceService {\n readonly #options = inject(OFFLINE_KIT_OPTIONS);\n readonly #errorHandler = inject(ErrorHandler);\n readonly #persistence = inject(OFFLINE_MUTATION_PERSISTENCE_ADAPTER);\n readonly #network = inject(OfflineNetworkService);\n readonly #sync = inject(OfflineSyncService);\n readonly #admission = inject(OfflineMutationAdmissionService);\n readonly #configured = this.#options.mode !== 'readCacheOnly' && this.#options.mutationPersistence !== undefined;\n readonly #state = signal<OfflineMutationPersistenceState>(this.#configured ? 'initializing' : 'enabled');\n #initializePromise: Promise<void> | null = null;\n #transitionTail: Promise<void> = settledMutationPersistence();\n #transitionRevision = 0;\n #persistedEnabled = !this.#configured;\n #latestTransition: { enabled: boolean; promise: Promise<void>; revision: number } | null = null;\n\n /** Whether the product configured a device-local mutation persistence preference. */\n readonly available = this.#configured;\n /** Whether new durable Outbox mutations are currently accepted. */\n readonly enabled = computed(() => this.#state() === 'enabled');\n /** Whether Kit is draining accepted and pending mutations before disabling. */\n readonly changing = computed(() => this.#state() === 'disabling');\n\n /** Loads the durable preference before Kit initializes repository-backed services. */\n async initialize(): Promise<void> {\n if (!this.#configured) {\n this.#admission.open();\n return;\n }\n await (this.#initializePromise ??= this.#loadInitialPreference());\n }\n\n /**\n * Enables or disables new durable mutations.\n *\n * Disabling closes admission synchronously, waits for already admitted commits,\n * flushes existing commands, verifies an empty Outbox, and only then persists OFF.\n */\n setEnabled(enabled: boolean): Promise<void> {\n if (!this.#configured) return settledMutationPersistence();\n const initialization = this.initialize();\n const latest = this.#latestTransition;\n if (latest?.enabled === enabled) return latest.promise;\n if (!latest && ((enabled && this.#state() === 'enabled') || (!enabled && this.#state() === 'disabled'))) {\n return settledMutationPersistence();\n }\n\n const revision = ++this.#transitionRevision;\n if (!enabled) {\n this.#state.set('disabling');\n void this.#admission.close();\n }\n const transition = this.#transitionTail.then(() => initialization).then(() => this.#applyTransition(enabled, revision));\n this.#transitionTail = transition.catch(() => undefined);\n const promise = transition.finally(() => {\n if (this.#latestTransition?.revision === revision) this.#latestTransition = null;\n });\n this.#latestTransition = { enabled, promise, revision };\n return promise;\n }\n\n async #loadInitialPreference(): Promise<void> {\n const persistence = this.#requiredPersistence();\n return invokeMutationPersistence(() => persistence.loadEnabled()).then(\n (stored) => {\n this.#persistedEnabled = stored ?? this.#options.mutationPersistence?.defaultEnabled ?? true;\n if (this.#transitionRevision === 0) {\n this.#state.set(this.#persistedEnabled ? 'enabled' : 'disabled');\n if (this.#persistedEnabled) this.#admission.open();\n }\n },\n async (error: unknown) => {\n this.#persistedEnabled = false;\n if (this.#transitionRevision === 0) this.#state.set('disabled');\n await this.#admission.close();\n reportMutationPersistenceError(this.#errorHandler, error);\n },\n );\n }\n\n #applyTransition(enabled: boolean, revision: number): Promise<void> {\n if (revision !== this.#transitionRevision) return settledMutationPersistence();\n const transition = enabled ? this.#enable(revision) : this.#disable(revision);\n return transition.catch((error: unknown) => {\n if (revision === this.#transitionRevision) {\n this.#state.set(this.#persistedEnabled ? 'enabled' : 'disabled');\n if (this.#persistedEnabled) this.#admission.open();\n }\n return Promise.reject(error);\n });\n }\n\n async #enable(revision: number): Promise<void> {\n await this.#requiredPersistence().saveEnabled(true);\n this.#persistedEnabled = true;\n if (revision !== this.#transitionRevision) return;\n this.#state.set('enabled');\n this.#admission.open();\n }\n\n async #disable(revision: number): Promise<void> {\n await this.#admission.close();\n if (revision !== this.#transitionRevision) return;\n await this.#sync.initialize({ flush: false });\n if (revision !== this.#transitionRevision) return;\n const pendingBeforeFlush = this.#sync.pendingCount();\n if (pendingBeforeFlush > 0) {\n if (this.#network.state() === 'offline') throw new OfflineMutationPersistenceRequiresOnlineError();\n await this.#sync.flush();\n }\n if (revision !== this.#transitionRevision) return;\n const pendingCount = this.#sync.pendingCount();\n if (pendingCount > 0) throw new OfflineMutationPersistencePendingError(pendingCount);\n await this.#requiredPersistence().saveEnabled(false);\n this.#persistedEnabled = false;\n if (revision === this.#transitionRevision) this.#state.set('disabled');\n }\n\n #requiredPersistence(): OfflineMutationPersistenceAdapter {\n if (!this.#persistence) throw new Error('Offline mutation persistence adapter is not provided.');\n return this.#persistence;\n }\n}\n","import { inject, Injectable, signal } from '@angular/core';\nimport type { OfflineScope } from './offline-repository';\nimport type { OfflinePrincipalId } from './offline-identity';\nimport { OFFLINE_REPOSITORY } from './offline-repository';\n\n/** Persisted identity and partition boundary for one authenticated local replica. */\nexport interface OfflineSessionManifest {\n userId: OfflinePrincipalId;\n readonly scopeIds: readonly string[];\n /** Authentication-provider subject used to distinguish users on a shared device. */\n authSubject: string | null;\n updatedAt: number;\n}\n\n/** Checks the authenticated subject and optional scope against one persisted session boundary. */\nexport function offlineSessionManifestAllows(\n manifest: OfflineSessionManifest | null,\n authSubject: string | null,\n scopeId?: string,\n): manifest is OfflineSessionManifest {\n if (!manifest || manifest.authSubject !== authSubject) return false;\n return scopeId === undefined || manifest.scopeIds.includes(scopeId);\n}\n\n/** Structural lease used to reject stale asynchronous session commits. */\nexport interface OfflineSessionTransitionLease {\n isCurrent(): boolean;\n}\n\n/** Owns activation and cleanup of the authenticated local-replica boundary. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineSessionService {\n readonly #repository = inject(OFFLINE_REPOSITORY);\n readonly #activeManifest = signal<OfflineSessionManifest | null>(null);\n #initialized = false;\n #localAccessThisRun = false;\n #remoteActivatedThisRun = false;\n\n readonly activeManifest = this.#activeManifest.asReadonly();\n\n async initialize(): Promise<void> {\n if (this.#initialized) return;\n await this.#repository.initialize();\n const userId = await this.#repository.getLastUserId();\n if (userId !== null) {\n const manifest = await this.#repository.getSessionManifest<OfflineSessionManifest>(userId);\n this.#activeManifest.set(manifest ?? { userId, scopeIds: [], authSubject: null, updatedAt: 0 });\n }\n this.#initialized = true;\n }\n\n async activateSession(userId: OfflinePrincipalId, scopeIds: readonly string[], authSubject: string | null): Promise<void>;\n async activateSession(\n userId: OfflinePrincipalId,\n scopeIds: readonly string[],\n authSubject: string | null,\n lease: OfflineSessionTransitionLease,\n ): Promise<boolean>;\n async activateSession(\n userId: OfflinePrincipalId,\n scopeIds: readonly string[],\n authSubject: string | null,\n lease?: OfflineSessionTransitionLease,\n ): Promise<void | boolean> {\n await this.initialize();\n if (lease && !lease.isCurrent()) return false;\n const normalizedScopeIds = [...new Set(scopeIds)].sort((a, b) => a.localeCompare(b));\n const previousUserId = await this.#repository.getLastUserId();\n if (lease && !lease.isCurrent()) return false;\n let previous = previousUserId === userId ? ((await this.#repository.getSessionManifest<OfflineSessionManifest>(userId)) ?? null) : null;\n if (lease && !lease.isCurrent()) return false;\n // A changed provider subject is a different person even when the product reuses its numeric id.\n // This deliberately also clears legacy null -> known subject and known subject -> null transitions.\n if (previousUserId !== null && (previousUserId !== userId || previous?.authSubject !== authSubject)) {\n await this.#repository.clearUser(previousUserId);\n if (lease && !lease.isCurrent()) return false;\n previous = null;\n }\n const active = new Set(normalizedScopeIds);\n await Promise.all(\n (previous?.scopeIds ?? [])\n .filter((scopeId) => !active.has(scopeId))\n .map((scopeId) => this.#repository.clearScope({ userId, scopeId })),\n );\n if (lease && !lease.isCurrent()) return false;\n\n const manifest: OfflineSessionManifest = {\n userId,\n scopeIds: normalizedScopeIds,\n authSubject,\n updatedAt: Date.now(),\n };\n await this.#repository.setLastUserId(userId);\n if (lease && !lease.isCurrent()) return false;\n await this.#repository.putSessionManifest(userId, manifest);\n if (lease && !lease.isCurrent()) return false;\n this.#activeManifest.set(manifest);\n this.#localAccessThisRun = true;\n this.#remoteActivatedThisRun = true;\n return lease ? true : undefined;\n }\n\n async clearActiveSession(): Promise<void> {\n await this.initialize();\n const userId = await this.#repository.getLastUserId();\n if (userId !== null) await this.#repository.clearUser(userId);\n this.#activeManifest.set(null);\n this.#localAccessThisRun = false;\n this.#remoteActivatedThisRun = false;\n }\n\n /** Immediately revoke local and remote runtime access while durable cleanup is pending. */\n revokeAccess(): void {\n this.#localAccessThisRun = false;\n this.#remoteActivatedThisRun = false;\n }\n\n /** Disable remote pull/replay eligibility while retaining the verified local manifest. */\n async suspendRemoteSession(): Promise<void> {\n await this.initialize();\n this.#remoteActivatedThisRun = false;\n }\n\n /**\n * Returns the persisted identity boundary for local-only route access.\n *\n * @remarks\n * This does not activate the sync context. Call it only after the authentication authority has\n * been classified as unavailable, never after explicit sign-out or HTTP 401/403. Legacy\n * manifests without an authentication-provider subject are rejected.\n *\n * @param authSubject - A currently known provider subject. When supplied, it must match the\n * persisted subject.\n */\n async getOfflineAccessManifest(authSubject?: string | null): Promise<OfflineSessionManifest | null> {\n await this.initialize();\n const manifest = this.#activeManifest();\n if (!manifest?.authSubject || (authSubject !== undefined && manifest.authSubject !== authSubject)) {\n return null;\n }\n return { ...manifest, scopeIds: [...manifest.scopeIds] };\n }\n\n /**\n * Activates a previously verified manifest for local replica and outbox access only.\n *\n * @remarks\n * This never enables pull or command replay. A later successful remote authentication must call\n * {@link activateSession} before synchronization can use transport.\n *\n * @param authSubject - A currently known provider subject. When supplied, it must match the\n * persisted subject.\n */\n async activateOfflineSession(authSubject?: string | null, lease?: OfflineSessionTransitionLease): Promise<OfflineSessionManifest | null> {\n const manifest = await this.getOfflineAccessManifest(authSubject);\n if (lease && !lease.isCurrent()) return null;\n this.#localAccessThisRun = manifest !== null;\n this.#remoteActivatedThisRun = false;\n return manifest;\n }\n\n /** Returns the session allowed to use the local replica and append outbox commands. */\n async getLocalSession(): Promise<{ userId: OfflinePrincipalId; scopes: OfflineScope[] } | null> {\n await this.initialize();\n return this.#localAccessThisRun ? this.#sessionFromManifest() : null;\n }\n\n /** Returns the remotely authenticated session eligible for pull and command replay. */\n async getSession(): Promise<{ userId: OfflinePrincipalId; scopes: OfflineScope[] } | null> {\n await this.initialize();\n return this.#remoteActivatedThisRun ? this.#sessionFromManifest() : null;\n }\n\n #sessionFromManifest(): { userId: OfflinePrincipalId; scopes: OfflineScope[] } | null {\n const manifest = this.#activeManifest();\n return manifest\n ? { userId: manifest.userId, scopes: manifest.scopeIds.map((scopeId) => ({ userId: manifest.userId, scopeId })) }\n : null;\n }\n}\n","/**\n * Closed set of reasons local offline storage failed to become ready.\n *\n * Product policy should branch on this discriminant rather than English message text.\n */\nexport type OfflineStorageUnavailableReason =\n | 'encryption_key_unavailable'\n | 'core_schema_incompatible'\n | 'replica_schema_mismatch'\n | 'migration_missing'\n | 'storage_unavailable';\n\n/**\n * Local offline storage could not be opened or migrated without risking data loss.\n *\n * Prefer `instanceof` / {@link OfflineStorageUnavailableError.reason} over message text.\n * The original failure is preserved on {@link Error.cause}. Kit never deletes Outbox or\n * replica rows in response to this error; recovery is product-owned and explicit.\n */\nexport class OfflineStorageUnavailableError extends Error {\n /** Stable machine-readable discriminator for storage initialization failures. */\n static readonly code = 'OFFLINE_STORAGE_UNAVAILABLE' as const;\n\n readonly code = OfflineStorageUnavailableError.code;\n\n constructor(\n readonly reason: OfflineStorageUnavailableReason,\n message: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = 'OfflineStorageUnavailableError';\n }\n}\n\n/**\n * Coordinator view of encrypted local storage after app initialization.\n *\n * `unavailable` is reached only when the product opted into online-only startup via\n * `onStorageUnavailable` (or when inspecting state after a thrown failure).\n */\nexport type OfflineStorageState =\n | { readonly status: 'initializing' }\n | { readonly status: 'ready' }\n | { readonly status: 'unavailable'; readonly error: OfflineStorageUnavailableError };\n\n/** Narrows an unknown failure to {@link OfflineStorageUnavailableError}. */\nexport function isOfflineStorageUnavailableError(error: unknown): error is OfflineStorageUnavailableError {\n return error instanceof OfflineStorageUnavailableError;\n}\n","import { computed, inject, Injectable, signal } from '@angular/core';\nimport type { OfflinePrincipalId } from './offline-identity';\nimport { OFFLINE_KIT_OPTIONS } from './offline-kit-options';\nimport { OfflineNetworkService } from './offline-network.service';\nimport { OfflineMutationPersistenceService } from './offline-mutation-persistence.service';\nimport { OFFLINE_REPOSITORY } from './offline-repository';\nimport { OfflineSessionService } from './offline-session.service';\nimport type { OfflineSessionManifest, OfflineSessionTransitionLease } from './offline-session.service';\nimport { OfflineStorageUnavailableError, type OfflineStorageState } from './offline-storage';\nimport { OfflineSyncService } from './offline-sync.service';\n\n/** User choice when logout encounters unconfirmed local mutations. */\nexport type OfflineLogoutAction = 'sync' | 'discard' | 'cancel';\n\nconst settledTransition = async (): Promise<void> => undefined;\n\n/** Options for {@link OfflineCoordinatorService.resumeRemoteSession}. */\nexport interface OfflineResumeRemoteSessionOptions {\n readonly foregroundScopeIds?: readonly string[];\n}\n\n/** Coordinates local persistence, session boundaries, network state, and outbox synchronization. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineCoordinatorService {\n readonly #repository = inject(OFFLINE_REPOSITORY);\n readonly #network = inject(OfflineNetworkService);\n readonly #mutationPersistence = inject(OfflineMutationPersistenceService);\n readonly #sync = inject(OfflineSyncService);\n readonly #session = inject(OfflineSessionService);\n readonly #options = inject(OFFLINE_KIT_OPTIONS);\n readonly #storageState = signal<OfflineStorageState>({ status: 'initializing' });\n #localInitialization: Promise<void> | null = null;\n #syncInitialization: Promise<void> | null = null;\n #runtimeInitialization: Promise<void> | null = null;\n #transitionRevision = 0;\n #transitionTail: Promise<void> = settledTransition();\n\n /**\n * Local storage readiness after {@link initialize}.\n *\n * When `unavailable`, the product opted into online-only startup; replica/outbox APIs must not be used.\n */\n readonly storageState = this.#storageState.asReadonly();\n /**\n * Product-policy guard: `true` only when encrypted local storage finished initialization successfully.\n *\n * Use this (or {@link storageState}) to disable offline mutations and replica reads when storage is unavailable.\n */\n readonly isStorageReady = computed(() => this.#storageState().status === 'ready');\n\n readonly networkState = this.#network.state;\n readonly syncState = this.#sync.syncState;\n readonly pendingCount = this.#sync.pendingCount;\n readonly conflicts = this.#sync.conflicts;\n /** Device-local control for accepting new durable Outbox mutations. */\n readonly mutationPersistence = this.#mutationPersistence;\n\n /** Opens local storage and restores its persisted session boundary without waiting for network discovery. */\n initializeLocal(): Promise<void> {\n this.#localInitialization ??= this.#initializeLocal();\n return this.#localInitialization;\n }\n\n /** Opens the local substrate, starts network discovery, then initializes synchronization. */\n initialize(): Promise<void> {\n this.#runtimeInitialization ??= this.#initializeRuntime();\n return this.#runtimeInitialization;\n }\n\n async #initializeLocal(): Promise<void> {\n await this.#mutationPersistence.initialize();\n const initializeSubstrate = async (): Promise<void> => {\n await this.#repository.initialize();\n await this.#session.initialize();\n };\n const substrateReady = await initializeSubstrate().then(\n () => true,\n async (error: unknown) => {\n const typed = this.#asStorageUnavailable(error);\n this.#storageState.set({ status: 'unavailable', error: typed });\n const onUnavailable = this.#options.onStorageUnavailable;\n if (!onUnavailable) throw typed;\n await onUnavailable(typed);\n return false;\n },\n );\n if (!substrateReady) return;\n this.#storageState.set({ status: 'ready' });\n }\n\n async #initializeRuntime(): Promise<void> {\n const networkReady = this.#network.initialize();\n await Promise.all([this.#initializeSync(), networkReady]);\n }\n\n #initializeSync(): Promise<void> {\n this.#syncInitialization ??= this.#initializeSyncOnce();\n return this.#syncInitialization;\n }\n\n async #initializeSyncOnce(): Promise<void> {\n await this.initializeLocal();\n if (this.#storageUnavailable()) return;\n await this.#sync.initialize({ flush: false });\n }\n\n async activateSession(userId: OfflinePrincipalId, scopeIds: readonly string[], authSubject: string | null): Promise<void> {\n if (!(await this.prepareRemoteSession(userId, scopeIds, authSubject))) return;\n await this.resumeRemoteSession();\n }\n\n /** Installs a remotely verified identity without starting pull or outbox replay. */\n async prepareRemoteSession(\n userId: OfflinePrincipalId,\n scopeIds: readonly string[],\n authSubject: string | null,\n authLease?: OfflineSessionTransitionLease,\n ): Promise<boolean> {\n const revision = ++this.#transitionRevision;\n const lease = this.#lease(revision, authLease);\n await this.initialize();\n if (this.#storageUnavailable()) return true;\n if (!lease.isCurrent()) return false;\n return this.#enqueueTransition(async () => {\n await this.#sync.resetSession();\n await this.#session.suspendRemoteSession();\n if (!lease.isCurrent()) return false;\n return this.#session.activateSession(userId, scopeIds, authSubject, lease);\n });\n }\n\n /** Starts pull and outbox replay after the caller has published remote access. */\n async resumeRemoteSession(options?: OfflineResumeRemoteSessionOptions): Promise<void> {\n await this.initialize();\n if (this.#storageUnavailable()) return;\n await this.#sync.refreshSession(options?.foregroundScopeIds);\n }\n\n /**\n * Activates a restored identity for local replica/outbox use without enabling transport sync.\n */\n async activateOfflineSession(\n authSubject?: string | null,\n authLease?: OfflineSessionTransitionLease,\n ): Promise<OfflineSessionManifest | null> {\n const revision = ++this.#transitionRevision;\n const lease = this.#lease(revision, authLease);\n await this.#initializeSync();\n if (this.#storageUnavailable()) return null;\n if (!lease.isCurrent()) return null;\n return this.#enqueueTransition(async () => {\n await this.#sync.resetSession();\n if (!lease.isCurrent()) return null;\n const manifest = await this.#session.activateOfflineSession(authSubject, lease);\n if (manifest && lease.isCurrent()) await this.#sync.refreshLocalSession();\n return lease.isCurrent() ? manifest : null;\n });\n }\n\n async clearActiveSession(): Promise<void> {\n this.#sync.revokeSession();\n this.#session.revokeAccess();\n ++this.#transitionRevision;\n await this.#initializeSync();\n if (this.#storageUnavailable()) return;\n return this.#enqueueTransition(async () => {\n await this.#sync.resetSession();\n await this.#session.clearActiveSession();\n });\n }\n\n async prepareLogout(action: OfflineLogoutAction): Promise<boolean> {\n await this.initialize();\n if (this.#storageUnavailable()) return action !== 'cancel';\n if (action === 'cancel') return false;\n if (action === 'discard') {\n await this.#sync.discardAllPending();\n return true;\n }\n await this.#sync.flush();\n return this.#sync.pendingCount() === 0;\n }\n\n async flush(): Promise<void> {\n await this.initialize();\n if (this.#storageUnavailable()) return;\n return this.#sync.flush();\n }\n\n #asStorageUnavailable(error: unknown): OfflineStorageUnavailableError {\n if (error instanceof OfflineStorageUnavailableError) return error;\n const message = error instanceof Error ? error.message : 'Offline storage is unavailable.';\n return new OfflineStorageUnavailableError('storage_unavailable', message || 'Offline storage is unavailable.', {\n cause: error,\n });\n }\n\n #storageUnavailable(): boolean {\n return this.#storageState().status === 'unavailable';\n }\n\n #lease(revision: number, authLease?: OfflineSessionTransitionLease): OfflineSessionTransitionLease {\n return { isCurrent: () => revision === this.#transitionRevision && (authLease?.isCurrent() ?? true) };\n }\n\n #enqueueTransition<T>(operation: () => Promise<T>): Promise<T> {\n const transition = this.#transitionTail.then(operation, operation);\n this.#transitionTail = transition.then(\n () => undefined,\n () => undefined,\n );\n return transition;\n }\n}\n","import { inject } from '@angular/core';\nimport { canonicalOfflinePrincipalId, type OfflinePrincipalId } from './offline-identity';\nimport { toObservable } from '@angular/core/rxjs-interop';\nimport type { RouterStateSnapshot } from '@angular/router';\nimport type { KitAuthAccessLease, KitAuthConfig, KitRemoteAccessRecovery } from '@rdlabo/ionic-angular-kit';\nimport type { Observable } from 'rxjs';\nimport { distinctUntilChanged, map } from 'rxjs/operators';\nimport { OfflineCoordinatorService } from './offline-coordinator.service';\n\n/** Remote identity fields required to activate an offline session boundary. */\nexport interface OfflineRemoteIdentity {\n readonly userId: OfflinePrincipalId;\n readonly scopeIds: readonly string[];\n readonly authSubject: string;\n /** Scope partitions to pull eagerly on automatic resume; remaining scopes require an explicit flush. */\n readonly foregroundScopeIds?: readonly string[];\n}\n\n/** Phase that distinguishes route authorization from background remote recovery. */\nexport type OfflineAuthExchangePhase = 'authorize' | 'recover';\n\n/** Context passed to the product credential exchange callback. */\nexport interface OfflineAuthExchangeContext {\n readonly phase: OfflineAuthExchangePhase;\n readonly state?: RouterStateSnapshot;\n readonly lease: KitAuthAccessLease;\n}\n\n/** Context supplied after remote transport has resumed for the same authenticated identity. */\nexport interface OfflineAuthResumeContext<TIdentity extends OfflineRemoteIdentity> {\n readonly phase: OfflineAuthExchangePhase;\n readonly state?: RouterStateSnapshot;\n readonly lease: KitAuthAccessLease;\n readonly identity: TIdentity;\n}\n\n/** Options for {@link createOfflineAuthBridge}. */\nexport interface CreateOfflineAuthBridgeOptions<TIdentity extends OfflineRemoteIdentity = OfflineRemoteIdentity> {\n /** Coordinator override for tests or custom runtimes; otherwise injected from the current context. */\n readonly offline?: OfflineCoordinatorService;\n /**\n * Exchanges a stored or refreshed credential for a remote identity.\n *\n * @returns `null` or `false` when the product declines activation without treating it as an error.\n */\n readonly exchange: (context: OfflineAuthExchangeContext) => Promise<TIdentity | null | false>;\n /** Provider subject currently known to the product auth layer. */\n readonly currentAuthSubject: () => string | null | undefined;\n /** Classifies transport unavailability for guard fallback and recovery retry. */\n readonly isUnavailableError: (error: unknown) => boolean;\n /** Remote availability stream; defaults to `offline.networkState !== 'offline'`. */\n readonly availability?: () => Observable<boolean>;\n /** Optional stronger identity check in addition to the required auth-subject match. */\n readonly isIdentityCurrent?: (identity: TIdentity) => boolean;\n /** Optional product hook after the kit publishes remote access and transport resumes. */\n readonly onRemoteResumed?: (context: OfflineAuthResumeContext<TIdentity>) => Promise<void>;\n /** Delay before {@link KitAuthRecoveryService} retries recovery while local access remains active. */\n readonly retryDelayMs?: number;\n}\n\n/** {@link KitAuthConfig} hooks wired for offline-coordinated remote and local access. */\nexport type OfflineAuthBridgeConfig = Pick<KitAuthConfig, 'onAuthorized' | 'onUnavailable' | 'isUnavailableError' | 'remoteRecovery'>;\n\n/**\n * Builds the offline-aware {@link KitAuthConfig} fragment for guarded route activation and recovery.\n *\n * @remarks\n * The bridge owns `exchange` → {@link OfflineCoordinatorService.prepareRemoteSession} → kit\n * `grantRemote` → {@link OfflineCoordinatorService.resumeRemoteSession} ordering by returning\n * {@link KitRemoteAccessRecovery}. Product consent, error UI, and DTO mapping stay outside.\n *\n * @example\n * ```ts\n * provideKitAuth(() => ({\n * authState: () => auth.state$,\n * ...createOfflineAuthBridge({\n * exchange: async (ctx) => {\n * const identity = await auth.exchangeCredential(ctx);\n * const authSubject = auth.currentSubject();\n * return identity && authSubject ? { ...identity, authSubject } : false;\n * },\n * currentAuthSubject: () => auth.currentSubject(),\n * isUnavailableError: isOfflineFallbackError,\n * }),\n * redirects,\n * }));\n * ```\n */\nexport function createOfflineAuthBridge<TIdentity extends OfflineRemoteIdentity>(\n options: CreateOfflineAuthBridgeOptions<TIdentity>,\n): OfflineAuthBridgeConfig {\n const offline = options.offline ?? inject(OfflineCoordinatorService);\n const { exchange, currentAuthSubject, isUnavailableError, isIdentityCurrent, onRemoteResumed, retryDelayMs } = options;\n const defaultAvailability$ = options.availability\n ? undefined\n : toObservable(offline.networkState).pipe(\n map((state) => state !== 'offline'),\n distinctUntilChanged(),\n );\n const availability = options.availability ?? (() => defaultAvailability$!);\n\n const identityStillCurrent = (lease: KitAuthAccessLease, identity: TIdentity): boolean =>\n lease.isCurrent() && currentAuthSubject() === identity.authSubject && (isIdentityCurrent?.(identity) ?? true);\n\n const resolveRemoteAccess = async (\n phase: OfflineAuthExchangePhase,\n state: RouterStateSnapshot | undefined,\n lease: KitAuthAccessLease,\n ): Promise<KitRemoteAccessRecovery | false> => {\n if (!lease.isCurrent()) return false;\n const identity = await exchange({ phase, state, lease });\n if (!lease.isCurrent()) return false;\n if (identity === null || identity === false) return false;\n assertOfflineRemoteIdentity(identity);\n if (!identityStillCurrent(lease, identity)) return false;\n\n return {\n activate: async (activateLease) => {\n if (!identityStillCurrent(activateLease, identity)) return false;\n const identityLease: KitAuthAccessLease = {\n isCurrent: () => identityStillCurrent(activateLease, identity),\n };\n const prepared = await offline.prepareRemoteSession(identity.userId, identity.scopeIds, identity.authSubject, identityLease);\n return prepared && identityLease.isCurrent();\n },\n resume: async (resumeLease) => {\n const resumeStillCurrent = (): boolean =>\n (resumeLease?.isCurrent() ?? true) && currentAuthSubject() === identity.authSubject && (isIdentityCurrent?.(identity) ?? true);\n if (!resumeStillCurrent()) return;\n await offline.resumeRemoteSession(\n identity.foregroundScopeIds !== undefined ? { foregroundScopeIds: identity.foregroundScopeIds } : undefined,\n );\n if (!resumeStillCurrent()) return;\n if (onRemoteResumed) {\n await onRemoteResumed({\n phase,\n state,\n lease: resumeLease ?? lease,\n identity,\n });\n if (!resumeStillCurrent()) return;\n }\n },\n };\n };\n\n return {\n isUnavailableError,\n onAuthorized: (state, lease) => resolveRemoteAccess('authorize', state, lease),\n onUnavailable: async (_state, _error, lease) => {\n if (!lease.isCurrent()) return false;\n const manifest = await offline.activateOfflineSession(currentAuthSubject(), lease);\n if (!lease.isCurrent()) return false;\n return manifest !== null;\n },\n remoteRecovery: {\n retryDelayMs,\n availability,\n reauthenticate: (lease) => resolveRemoteAccess('recover', undefined, lease),\n },\n };\n}\n\nfunction assertOfflineRemoteIdentity(identity: OfflineRemoteIdentity): void {\n canonicalOfflinePrincipalId(identity.userId);\n if (!Array.isArray(identity.scopeIds) || identity.scopeIds.some((scopeId) => typeof scopeId !== 'string' || scopeId.length === 0)) {\n throw new Error('Offline remote identity scopeIds must contain only non-empty strings.');\n }\n if (typeof identity.authSubject !== 'string' || identity.authSubject.length === 0) {\n throw new Error('Offline remote identity authSubject must be a non-empty string.');\n }\n if (identity.foregroundScopeIds !== undefined) {\n if (\n !Array.isArray(identity.foregroundScopeIds) ||\n identity.foregroundScopeIds.some((scopeId) => typeof scopeId !== 'string' || scopeId.length === 0)\n ) {\n throw new Error('Offline remote identity foregroundScopeIds must contain only non-empty strings.');\n }\n const scopeIds = new Set(identity.scopeIds);\n for (const scopeId of identity.foregroundScopeIds) {\n if (!scopeIds.has(scopeId)) {\n throw new Error(`Offline remote identity foregroundScopeIds must be a subset of scopeIds: \"${scopeId}\".`);\n }\n }\n }\n}\n","export const COMMUNITY_SQLITE_ENCRYPTED = true;\nexport const COMMUNITY_SQLITE_MODE = 'secret';\nexport const COMMUNITY_SQLITE_VERSION = 1;\nexport const COMMUNITY_SQLITE_READONLY = false;\n","import { Capacitor } from '@capacitor/core';\nimport {\n COMMUNITY_SQLITE_ENCRYPTED,\n COMMUNITY_SQLITE_MODE,\n COMMUNITY_SQLITE_READONLY,\n COMMUNITY_SQLITE_VERSION,\n} from './offline-community-sqlite-config';\n\n/** Durable marker store used to request a cold-start local reset. */\nexport interface OfflineLocalResetMarkerStore {\n get(options: { key: string }): Promise<{ value: string | null }>;\n set(options: { key: string; value: string }): Promise<void>;\n remove(options: { key: string }): Promise<void>;\n}\n\n/** Minimal page reload surface used after a reset request is persisted. */\nexport interface OfflineLocalResetReloadTarget {\n reload(): void;\n}\n\n/** Native SQLite connection lifecycle required to delete Kit's encrypted database safely. */\nexport interface OfflineLocalResetSqliteConnection {\n checkConnectionsConsistency(): Promise<{ result?: boolean }>;\n isDatabase(database: string): Promise<{ result?: boolean }>;\n createConnection(\n database: string,\n encrypted: boolean,\n mode: string,\n version: number,\n readonly: boolean,\n ): Promise<{ delete(): Promise<void> }>;\n closeConnection(database: string, readonly: boolean): Promise<void>;\n}\n\n/** Options for {@link requestOfflineLocalReset}. */\nexport interface RequestOfflineLocalResetOptions {\n markerStore: OfflineLocalResetMarkerStore;\n markerKey: string;\n reloadTarget?: OfflineLocalResetReloadTarget;\n}\n\n/** Options for {@link recoverOfflineLocalReset}. */\nexport interface RecoverOfflineLocalResetOptions {\n markerStore: OfflineLocalResetMarkerStore;\n markerKey: string;\n sqliteConnection: OfflineLocalResetSqliteConnection;\n /**\n * Kit database followed only by product databases using Kit's same encrypted\n * secret-mode, connection-version-1, read/write lifecycle.\n * Delete databases with other connection settings in {@link additionalCleanup}.\n */\n kitCompatibleDatabaseNames: readonly [string, ...string[]];\n nativePlatform?: boolean;\n /** Product-owned cleanup, such as a media database or files, run before the marker is removed. */\n additionalCleanup?: () => Promise<void>;\n}\n\nconst OFFLINE_LOCAL_RESET_REQUESTED = 'requested';\n\n/** Persists an explicit destructive reset request, then reloads into a cold bootstrap. */\nexport async function requestOfflineLocalReset(options: RequestOfflineLocalResetOptions): Promise<void> {\n await options.markerStore.set({ key: options.markerKey, value: OFFLINE_LOCAL_RESET_REQUESTED });\n const reloadTarget = options.reloadTarget ?? globalThis.location;\n reloadTarget.reload();\n}\n\n/**\n * Recovers an explicit reset request before Angular and Kit open native SQLite.\n *\n * The marker is removed only after the Kit database and every product cleanup succeed.\n * Kit never invokes this helper automatically in response to a storage failure.\n */\nexport async function recoverOfflineLocalReset(options: RecoverOfflineLocalResetOptions): Promise<boolean> {\n if (!(options.nativePlatform ?? Capacitor.isNativePlatform())) return false;\n const marker = await options.markerStore.get({ key: options.markerKey });\n if (marker.value !== OFFLINE_LOCAL_RESET_REQUESTED) return false;\n\n await options.sqliteConnection.checkConnectionsConsistency();\n for (const databaseName of new Set(options.kitCompatibleDatabaseNames)) {\n const exists = await options.sqliteConnection.isDatabase(databaseName);\n if (exists.result) {\n const connection = await options.sqliteConnection.createConnection(\n databaseName,\n COMMUNITY_SQLITE_ENCRYPTED,\n COMMUNITY_SQLITE_MODE,\n COMMUNITY_SQLITE_VERSION,\n COMMUNITY_SQLITE_READONLY,\n );\n await deleteAndCloseOfflineDatabase(options.sqliteConnection, databaseName, connection);\n }\n }\n await options.additionalCleanup?.();\n await options.markerStore.remove({ key: options.markerKey });\n return true;\n}\n\ntype OfflineResetOperationResult = { ok: true } | { ok: false; error: unknown };\n\nasync function settleOfflineResetOperation(operation: () => Promise<void>): Promise<OfflineResetOperationResult> {\n return new Promise<void>((resolve) => resolve(operation())).then(\n () => ({ ok: true }),\n (error: unknown) => ({ ok: false, error }),\n );\n}\n\nasync function deleteAndCloseOfflineDatabase(\n sqliteConnection: OfflineLocalResetSqliteConnection,\n databaseName: string,\n connection: { delete(): Promise<void> },\n): Promise<void> {\n const deletion = await settleOfflineResetOperation(() => connection.delete());\n const closing = await settleOfflineResetOperation(() => sqliteConnection.closeConnection(databaseName, COMMUNITY_SQLITE_READONLY));\n if (!deletion.ok && !closing.ok) {\n throw new AggregateError([deletion.error, closing.error], `Offline database ${databaseName} delete and close both failed.`);\n }\n if (!deletion.ok) throw deletion.error;\n if (!closing.ok) throw closing.error;\n}\n","import { HttpErrorResponse } from '@angular/common/http';\n\n/** Identity policy for a successful offline mutation response. */\nexport type OfflineMutationEnvelopeIdPolicy = 'required' | 'optional' | 'forbidden';\n\n/** Values policy for a successful offline mutation response. */\nexport type OfflineMutationEnvelopeValuesPolicy = 'object' | 'tombstone' | 'object-or-tombstone' | 'optional-object-or-tombstone';\n\n/** Runtime validation policy for a successful offline mutation response. */\nexport interface OfflineMutationEnvelopeOptions {\n readonly id: OfflineMutationEnvelopeIdPolicy;\n readonly values: OfflineMutationEnvelopeValuesPolicy;\n readonly label?: string;\n readonly url?: string;\n}\n\n/** Canonical successful mutation response consumed by offline command adapters. */\nexport interface OfflineMutationEnvelope<T extends Record<string, unknown>> {\n readonly id: number | null;\n readonly revision: number;\n readonly values: T | null | undefined;\n}\n\n/**\n * A successful HTTP response that violates the offline mutation protocol.\n *\n * Status 502 deliberately keeps the response in the retryable server-failure class.\n */\nexport class OfflineMutationProtocolError extends HttpErrorResponse {\n constructor(message: string, url?: string) {\n super({\n error: { code: 'OFFLINE_MUTATION_PROTOCOL_ERROR', message },\n status: 502,\n statusText: 'Bad Gateway',\n url,\n });\n }\n}\n\nconst hasOwn = (value: Record<string, unknown>, key: string): boolean => Object.prototype.hasOwnProperty.call(value, key);\n\nconst isPositiveSafeInteger = (value: unknown): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/** Strictly parses the wire envelope returned by an offline mutation endpoint. */\nexport function parseOfflineMutationEnvelope<T extends Record<string, unknown> = Record<string, unknown>>(\n input: unknown,\n options: OfflineMutationEnvelopeOptions,\n): OfflineMutationEnvelope<T> {\n const label = options.label ?? 'Offline mutation response';\n const invalid = (detail: string): never => {\n throw new OfflineMutationProtocolError(`${label} ${detail}`, options.url);\n };\n\n const envelope = isRecord(input) ? input : invalid('must be an object.');\n\n let id: number | null = null;\n switch (options.id) {\n case 'required': {\n const rawId = envelope['id'];\n id = hasOwn(envelope, 'id') && isPositiveSafeInteger(rawId) ? rawId : invalid('id must be a positive safe integer.');\n break;\n }\n case 'optional': {\n if (hasOwn(envelope, 'id')) {\n const rawId = envelope['id'];\n id = isPositiveSafeInteger(rawId) ? rawId : invalid('id must be a positive safe integer when present.');\n }\n break;\n }\n case 'forbidden':\n if (['id', 'serverId', 'remoteId'].some((key) => hasOwn(envelope, key))) {\n invalid('must not contain id, serverId, or remoteId.');\n }\n break;\n }\n\n const rawRevision = envelope['revision'];\n const revision =\n hasOwn(envelope, 'revision') && isPositiveSafeInteger(rawRevision) ? rawRevision : invalid('revision must be a positive safe integer.');\n\n const values = envelope['values'];\n switch (options.values) {\n case 'object':\n if (!isRecord(values)) {\n invalid('values must be an object.');\n }\n break;\n case 'tombstone':\n if (values !== null) {\n invalid('values must be null.');\n }\n break;\n case 'object-or-tombstone':\n if (values !== null && !isRecord(values)) {\n invalid('values must be an object or null.');\n }\n break;\n case 'optional-object-or-tombstone':\n if (values !== undefined && values !== null && !isRecord(values)) {\n invalid('values must be an object, null, or undefined.');\n }\n break;\n }\n\n return { id, revision, values: values as T | null | undefined };\n}\n","import type { Provider, Type } from '@angular/core';\nimport { inject, Injectable, InjectionToken } from '@angular/core';\nimport type { HttpRequest, HttpResponse } from '@angular/common/http';\nimport { HttpContextToken } from '@angular/common/http';\n\n/** outbox再送時にoffline interceptorだけを迂回する。認証・retryは維持する。 */\nexport const OFFLINE_BYPASS = new HttpContextToken<boolean>(() => false);\n/** Header attached to synthetic local or optimistic responses. */\nexport const OFFLINE_RESPONSE_HEADER = 'X-Offline-Response';\n/** Header marking a local response as a complete collection snapshot. */\nexport const OFFLINE_RESPONSE_COMPLETE_HEADER = 'X-Offline-Response-Complete';\n/** Origin of a synthetic offline response. */\nexport type OfflineResponseSource = 'local' | 'optimistic';\n\n/** Source passed to a read policy's shared response projector. */\nexport type OfflineReadResponseSource = 'remote' | 'local';\n\n/** Value emitted by a local-first read together with its settlement metadata. */\nexport interface OfflineReadEmission<T> {\n readonly value: T;\n readonly source: OfflineReadResponseSource;\n readonly complete?: boolean;\n}\n\n/** Reads the source attached by the offline interceptor. */\nexport function offlineReadSource(response: HttpResponse<unknown>): OfflineReadResponseSource {\n return response.headers.get(OFFLINE_RESPONSE_HEADER) === 'local' ? 'local' : 'remote';\n}\n\n/** Converts an HTTP response into the shared local-first read emission contract. */\nexport function offlineReadEmission<T>(response: HttpResponse<unknown>, value: T): OfflineReadEmission<T> {\n const source = offlineReadSource(response);\n return {\n value,\n source,\n complete: source === 'remote' || response.headers.get(OFFLINE_RESPONSE_COMPLETE_HEADER) === 'true',\n };\n}\n\n/** Prevents an incomplete empty local collection from clearing usable UI state. */\nexport function shouldCommitOfflineCollection<T>(emission: OfflineReadEmission<readonly T[]>): boolean {\n return emission.source === 'remote' || emission.complete || emission.value.length > 0;\n}\n\n/** Controls GET emission order between local replica and remote transport. */\nexport type OfflineReadStrategy = 'network-first' | 'local-first';\n\n/** Product read policy backed by a local replica fallback for transport failures. */\nexport interface OfflineReadRequestPlan {\n kind: 'read';\n /**\n * Controls whether the interceptor hits the network first or emits a local\n * replica immediately and revalidates in the background. Defaults to\n * `network-first` when omitted so existing policies stay compatible.\n *\n * @remarks\n * `local-first` starts transport and `readLocal()` concurrently, emits\n * projected local first on hit, then drains the buffered remote response.\n * Callers must keep the HTTP observable subscribed through revalidation;\n * `firstValueFrom` and `take(1)` cancel in-flight transport.\n */\n readStrategy?: OfflineReadStrategy;\n /**\n * Persists and projects a remote response, or projects a local fallback.\n *\n * @remarks\n * Products may return a replacement response assembled from the local\n * replica. The source makes persistence remote-only while both paths share\n * one product-owned composer.\n */\n projectResponse?(response: HttpResponse<unknown>, source: OfflineReadResponseSource): Promise<HttpResponse<unknown>>;\n /** Reads the same request from the local replica. */\n readLocal(): Promise<HttpResponse<unknown> | null>;\n}\n\n/** Resolved offline handling strategy for an HTTP request. */\nexport type OfflineRequestPlan = OfflineReadRequestPlan;\n\n/** URL・DTO・replica key・feature flagは製品Policyだけが知る。 */\nexport interface OfflineRequestPolicy {\n resolve(request: HttpRequest<unknown>): OfflineRequestPlan | null;\n}\n\n/** A local-first mutation prepared before any HTTP transport is started. */\nexport interface OfflineMutationRequestPlan {\n kind: 'mutation';\n /**\n * Atomically updates the replica and appends its durable Outbox command,\n * then returns the optimistic response exposed to the original caller.\n */\n prepare(): Promise<HttpResponse<unknown>>;\n}\n\n/** Product policy that maps one write request to a local-first mutation. */\nexport interface OfflineMutationRequestPolicy {\n resolve(request: HttpRequest<unknown>): OfflineMutationRequestPlan | null;\n}\n\n/** Multi-provider token containing product request policies. */\nexport const OFFLINE_REQUEST_POLICIES = new InjectionToken<readonly OfflineRequestPolicy[]>('OFFLINE_REQUEST_POLICIES', {\n factory: () => [],\n});\n\n/** Multi-provider token containing product mutation policies. */\nexport const OFFLINE_MUTATION_REQUEST_POLICIES = new InjectionToken<readonly OfflineMutationRequestPolicy[]>(\n 'OFFLINE_MUTATION_REQUEST_POLICIES',\n { factory: () => [] },\n);\n\n/** Registers one product request policy with the offline interceptor. */\nexport function provideOfflineRequestPolicy(policy: Type<OfflineRequestPolicy>): Provider[] {\n return [policy, { provide: OFFLINE_REQUEST_POLICIES, useExisting: policy, multi: true }];\n}\n\n/** Registers one product mutation policy with the offline interceptor. */\nexport function provideOfflineMutationRequestPolicy(policy: Type<OfflineMutationRequestPolicy>): Provider[] {\n return [policy, { provide: OFFLINE_MUTATION_REQUEST_POLICIES, useExisting: policy, multi: true }];\n}\n\n/** Resolves the first product policy matching an HTTP request. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineRequestPolicyRegistry {\n readonly #policies = inject(OFFLINE_REQUEST_POLICIES);\n\n resolve(request: HttpRequest<unknown>): OfflineRequestPlan | null {\n for (const policy of this.#policies) {\n const plan = policy.resolve(request);\n if (plan) return plan;\n }\n return null;\n }\n}\n\n/** Raised when more than one mutation policy claims the same request. */\nexport class OfflineMutationPolicyConflictError extends Error {\n constructor(request: HttpRequest<unknown>, matchCount: number) {\n super(`${matchCount} offline mutation policies matched ${request.method} ${request.urlWithParams}`);\n this.name = 'OfflineMutationPolicyConflictError';\n }\n}\n\n/** Resolves the only product mutation policy matching a write request. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineMutationRequestPolicyRegistry {\n readonly #policies = inject(OFFLINE_MUTATION_REQUEST_POLICIES);\n\n resolve(request: HttpRequest<unknown>): OfflineMutationRequestPlan | null {\n let matched: OfflineMutationRequestPlan | null = null;\n let matchCount = 0;\n for (const policy of this.#policies) {\n const plan = policy.resolve(request);\n if (!plan) continue;\n matched = plan;\n matchCount += 1;\n }\n if (matchCount > 1) throw new OfflineMutationPolicyConflictError(request, matchCount);\n return matched;\n }\n}\n","import { inject, Injectable, InjectionToken } from '@angular/core';\nimport {\n canonicalOfflineReplicaIdentity,\n canonicalOfflinePrincipalId,\n commandIdentityFromReplicaIdentity,\n offlineGeneratedReplicaIdentity,\n offlineNaturalReplicaIdentity,\n parseOfflineCommandIdentity,\n parseOfflinePrincipalId,\n replicaAddressFromIdentity,\n serializeOfflineCommandIdentity,\n} from './offline-identity';\nimport { OFFLINE_KIT_OPTIONS } from './offline-kit-options';\nimport {\n assertOfflineReplicaGeneratedRemoteId,\n assertOfflineReplicaNaturalKeyBaseline,\n canonicalOfflineRemoteIdentity,\n decodeOfflineReplicaValues,\n encodeOfflineReplicaValues,\n normalizeOfflineNaturalKey,\n offlineNaturalKeyFromValues,\n projectOfflineReplicaValues,\n type OfflineGeneratedRemoteId,\n type OfflineReplicaEntitySchema,\n type OfflineReplicaRemoteIdentity,\n type OfflineReplicaSchemaBundle,\n sha256OfflineReplicaSchema,\n} from './offline-replica-schema';\nimport {\n OFFLINE_SCHEMA_VERSION,\n canonicalOfflineReplicaRowKey,\n type OfflineCommand,\n type OfflineCommandIdentity,\n type OfflinePrincipalId,\n type OfflinePullAttention,\n type OfflinePullAttentionReason,\n type OfflineReplicaAddress,\n type OfflineReplicaCursor,\n type OfflineReplicaIdentity,\n type OfflineReplicaRow,\n type OfflineReplicaRowKey,\n type OfflineReplicaRemoteIdRelease,\n type OfflineRepository,\n type OfflineRepositoryReader,\n type OfflineReplicaTransaction,\n type OfflineScope,\n} from './offline-repository';\nimport { OFFLINE_REPOSITORY_ATOMIC_MUTATION } from './offline-repository-concurrency';\nimport { OfflineStorageUnavailableError } from './offline-storage';\nimport {\n COMMUNITY_SQLITE_ENCRYPTED,\n COMMUNITY_SQLITE_MODE,\n COMMUNITY_SQLITE_READONLY,\n COMMUNITY_SQLITE_VERSION,\n} from './offline-community-sqlite-config';\n\n/** Minimal native SQLite driver surface required by the offline repository. */\nexport interface CommunitySqliteDriver {\n open(options: { databaseName: string; createEncryptionKey?: () => Promise<string> }): Promise<{ databaseId: string }>;\n execute(options: { databaseId: string; statement: string; values?: SQLiteValue[] }): Promise<unknown>;\n query(options: { databaseId: string; statement: string; values?: SQLiteValue[] }): Promise<{\n columns?: string[];\n rows?: unknown[];\n }>;\n beginTransaction(options: { databaseId: string }): Promise<void>;\n commitTransaction(options: { databaseId: string }): Promise<void>;\n rollbackTransaction(options: { databaseId: string }): Promise<void>;\n}\n\n/** Open community SQLite database surface used by the standard driver. */\nexport interface CommunitySqliteDatabase {\n open(): Promise<void>;\n run(statement: string, values?: unknown[], transaction?: boolean): Promise<unknown>;\n query(statement: string, values?: unknown[]): Promise<{ values?: unknown[] }>;\n beginTransaction(): Promise<unknown>;\n commitTransaction(): Promise<unknown>;\n rollbackTransaction(): Promise<unknown>;\n}\n\n/** Community SQLite connection surface used to provision encrypted databases. */\nexport interface CommunitySqliteConnection {\n isSecretStored(): Promise<{ result?: boolean }>;\n setEncryptionSecret(passphrase: string): Promise<void>;\n createConnection(\n database: string,\n encrypted: boolean,\n mode: string,\n version: number,\n readonly: boolean,\n ): Promise<CommunitySqliteDatabase>;\n}\n\n/** DI token for the native community SQLite driver. */\nexport const COMMUNITY_SQLITE = new InjectionToken<CommunitySqliteDriver | null>('COMMUNITY_SQLITE', {\n factory: () => null,\n});\n\n/**\n * Create a cryptographically random 256-bit key for a first-install offline SQLite database.\n *\n * The returned lower-case hexadecimal value is suitable for\n * `OfflineKitOptions.createEncryptionKey` and contains no device or user identifiers.\n */\nexport async function createRandomOfflineEncryptionKey(): Promise<string> {\n const bytes = crypto.getRandomValues(new Uint8Array(32));\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\nconst settledSqliteOperation = async (): Promise<void> => undefined;\n\n/** Create the standard encrypted `@capacitor-community/sqlite` driver. */\nexport function createCommunitySqliteDriver(connection: CommunitySqliteConnection): CommunitySqliteDriver {\n const databases = new Map<string, CommunitySqliteDatabase>();\n const database = (databaseId: string): CommunitySqliteDatabase => {\n const value = databases.get(databaseId);\n if (!value) throw new Error(`Offline SQLite database \"${databaseId}\" is not open`);\n return value;\n };\n return {\n async open({ databaseName, createEncryptionKey }) {\n const stored = await connection.isSecretStored();\n if (!stored.result) {\n const encryptionKey = await createEncryptionKey?.();\n if (!encryptionKey) throw new Error('Native offline storage requires a non-empty encryption key on first open');\n await connection.setEncryptionSecret(encryptionKey);\n }\n const value = await connection.createConnection(\n databaseName,\n COMMUNITY_SQLITE_ENCRYPTED,\n COMMUNITY_SQLITE_MODE,\n COMMUNITY_SQLITE_VERSION,\n COMMUNITY_SQLITE_READONLY,\n );\n await value.open();\n databases.set(databaseName, value);\n return { databaseId: databaseName };\n },\n async execute({ databaseId, statement, values = [] }) {\n await database(databaseId).run(statement, values, false);\n },\n async query({ databaseId, statement, values = [] }) {\n const result = await database(databaseId).query(statement, values);\n return { rows: result.values ?? [] };\n },\n async beginTransaction({ databaseId }) {\n await database(databaseId).beginTransaction();\n },\n async commitTransaction({ databaseId }) {\n await database(databaseId).commitTransaction();\n },\n async rollbackTransaction({ databaseId }) {\n await database(databaseId).rollbackTransaction();\n },\n };\n}\n\ntype SQLiteValue = string | number | null;\ntype SQLiteRow = Record<string, unknown>;\n\nconst SCHEMA = [\n `CREATE TABLE IF NOT EXISTS offline_metadata (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n schema_version INTEGER NOT NULL,\n last_user_id TEXT\n)`,\n `CREATE TABLE IF NOT EXISTS offline_session_manifests (\n user_id TEXT PRIMARY KEY,\n value_json TEXT NOT NULL\n)`,\n `CREATE TABLE IF NOT EXISTS offline_sync_commands (\n command_id TEXT PRIMARY KEY,\n user_id TEXT NOT NULL,\n scope_id TEXT NOT NULL,\n aggregate_type TEXT NOT NULL,\n source_key TEXT NOT NULL,\n identity_json TEXT NOT NULL,\n operation TEXT NOT NULL,\n payload_json TEXT NOT NULL,\n local_only_footprint_json TEXT,\n replica_mutation TEXT NOT NULL DEFAULT 'upsert',\n payload_hash TEXT NOT NULL,\n base_revision_json TEXT,\n state TEXT NOT NULL,\n attempts INTEGER NOT NULL,\n retry_at INTEGER,\n created_at INTEGER NOT NULL,\n last_error_code TEXT,\n server_commit_unknown INTEGER NOT NULL DEFAULT 0,\n reconciliation_identity_json TEXT\n)`,\n `CREATE INDEX IF NOT EXISTS offline_sync_commands_scope_created\n ON offline_sync_commands (user_id, scope_id, created_at)`,\n `CREATE TABLE IF NOT EXISTS offline_replica_schema_metadata (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n version INTEGER NOT NULL,\n schema_hash TEXT NOT NULL CHECK (length(schema_hash) = 64)\n)`,\n `CREATE TABLE IF NOT EXISTS offline_replica_cursors (\n user_id TEXT NOT NULL,\n scope_id TEXT NOT NULL,\n cursor TEXT NOT NULL,\n PRIMARY KEY (user_id, scope_id)\n )`,\n `CREATE TABLE IF NOT EXISTS offline_reconciliation_scopes (\n user_id TEXT NOT NULL,\n scope_id TEXT NOT NULL,\n PRIMARY KEY (user_id, scope_id)\n)`,\n `CREATE TABLE IF NOT EXISTS offline_pull_attentions (\n user_id TEXT NOT NULL,\n scope_id TEXT NOT NULL,\n reason TEXT NOT NULL,\n status INTEGER,\n PRIMARY KEY (user_id, scope_id)\n)`,\n];\n\n/** Native iOS/Android repository backed by encrypted `@capacitor-community/sqlite`. */\n@Injectable({ providedIn: 'root' })\nexport class SqliteOfflineRepository implements OfflineRepository {\n readonly #sqlite = inject(COMMUNITY_SQLITE);\n readonly #options = inject(OFFLINE_KIT_OPTIONS);\n #databaseId: string | null = null;\n #initialization: Promise<void> | null = null;\n #writes: Promise<void> = settledSqliteOperation();\n #activeReaders = 0;\n #readersIdle: Promise<void> = settledSqliteOperation();\n #resolveReadersIdle: (() => void) | null = null;\n #atomicMutationRevision: number | null = null;\n #atomicMutationCommitted = false;\n #atomicOperations: Promise<void> = settledSqliteOperation();\n #readSnapshotActive = false;\n #atomicIdle: Promise<void> = settledSqliteOperation();\n #resolveAtomicIdle: (() => void) | null = null;\n\n initialize(): Promise<void> {\n this.#initialization ??= this.#open();\n return this.#initialization;\n }\n\n async getLastUserId(): Promise<OfflinePrincipalId | null> {\n return this.#withCommittedRead(() => this.#readLastUserId());\n }\n\n async setLastUserId(userId: OfflinePrincipalId): Promise<void> {\n await this.#write(\n `INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, ?)\n ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version, last_user_id = excluded.last_user_id`,\n [OFFLINE_SCHEMA_VERSION, canonicalOfflinePrincipalId(userId)],\n );\n }\n\n async getSessionManifest<T>(userId: OfflinePrincipalId): Promise<T | null> {\n return this.#withCommittedRead(() => this.#readSessionManifest<T>(userId));\n }\n\n async putSessionManifest<T>(userId: OfflinePrincipalId, value: T): Promise<void> {\n await this.#write(\n `INSERT INTO offline_session_manifests (user_id, value_json) VALUES (?, ?)\n ON CONFLICT(user_id) DO UPDATE SET value_json = excluded.value_json`,\n [canonicalOfflinePrincipalId(userId), JSON.stringify(value)],\n );\n }\n\n async getReplicaRow<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n return this.#withCommittedRead(async () => {\n const row = await this.#queryReplicaRow(scope, sourceKey, identity, false);\n return row as OfflineReplicaRow<TValues> | null;\n });\n }\n\n async getReplicaRowIncludingPendingDelete<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n return this.#withCommittedRead(async () => {\n const row = await this.#queryReplicaRow(scope, sourceKey, identity, true);\n return row as OfflineReplicaRow<TValues> | null;\n });\n }\n\n async getReplicaRows<TValues = unknown>(scope: OfflineScope, sourceKey: string): Promise<OfflineReplicaRow<TValues>[]> {\n return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey));\n }\n\n async getReplicaRowByRemoteId<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n remoteId: OfflineGeneratedRemoteId,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated') return null;\n return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });\n }\n\n async getReplicaRowByRemoteIdentity<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaRemoteIdentity,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n return this.#withCommittedRead(() => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity));\n }\n\n async getReplicaCursor(scope: OfflineScope): Promise<OfflineReplicaCursor | null> {\n return this.#withCommittedRead(() => this.#readReplicaCursor(scope));\n }\n\n async getPullAttentions(userId: OfflinePrincipalId): Promise<OfflinePullAttention[]> {\n return this.#withCommittedRead(() => this.#readPullAttentions(userId));\n }\n\n async getCommands(scope: OfflineScope): Promise<OfflineCommand[]> {\n return this.#withCommittedRead(() => this.#readCommands(scope));\n }\n\n async getCommandsForUser(userId: OfflinePrincipalId): Promise<OfflineCommand[]> {\n return this.#withCommittedRead(() => this.#readCommandsForUser(userId));\n }\n\n async runReadSnapshot<T>(read: (reader: OfflineRepositoryReader) => Promise<T>): Promise<T> {\n if (this.#atomicMutationRevision !== null) {\n throw new Error('Use the repository passed to an atomic mutation for snapshot reads.');\n }\n return this.#transaction(async () => {\n this.#readSnapshotActive = true;\n const executeRead = async (): Promise<T> => read(this.#reader());\n return executeRead().finally(() => (this.#readSnapshotActive = false));\n });\n }\n\n async [OFFLINE_REPOSITORY_ATOMIC_MUTATION]<T>(operation: (repository: OfflineRepository) => Promise<T>): Promise<T> {\n await this.initialize();\n await this.#writes;\n if (this.#atomicMutationRevision !== null) {\n throw new Error('Nested offline replica atomic mutations are not supported.');\n }\n this.#beginReaders();\n const executeAtomicMutation = async (): Promise<T> => {\n const databaseId = await this.#databaseConnection();\n this.#atomicOperations = settledSqliteOperation();\n this.#atomicMutationCommitted = false;\n this.#atomicIdle = new Promise<void>((resolve) => {\n this.#resolveAtomicIdle = resolve;\n });\n this.#atomicMutationRevision = await this.#nativeTransaction(databaseId, () => this.#dataVersion(databaseId));\n const result = await operation(this.#atomicRepository());\n await this.#atomicOperations;\n if (!this.#atomicMutationCommitted) {\n await this.#queueAtomicOperation(() => this.#atomicTransaction(databaseId, async () => undefined, false));\n }\n return result;\n };\n return executeAtomicMutation().finally(() => {\n this.#atomicMutationRevision = null;\n this.#endReaders();\n this.#resolveAtomicIdle?.();\n this.#resolveAtomicIdle = null;\n this.#atomicIdle = settledSqliteOperation();\n });\n }\n\n async putCommand(command: OfflineCommand): Promise<void> {\n await this.#queueWrite((databaseId) => this.#putCommand(databaseId, command));\n }\n\n replaceCommand(command: OfflineCommand): Promise<void> {\n return this.putCommand(command);\n }\n\n async removeCommand(commandId: string): Promise<void> {\n await this.#write('DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId]);\n }\n\n async putPullAttention(attention: OfflinePullAttention): Promise<void> {\n await this.#write(\n `INSERT INTO offline_pull_attentions (user_id, scope_id, reason, status) VALUES (?, ?, ?, ?)\n ON CONFLICT(user_id, scope_id) DO UPDATE SET reason = excluded.reason, status = excluded.status`,\n [\n canonicalOfflinePrincipalId(attention.userId),\n attention.scopeId,\n attention.reason,\n attention.status === undefined ? null : attention.status,\n ],\n );\n }\n\n async removePullAttention(scope: OfflineScope): Promise<void> {\n await this.#write('DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', [\n canonicalOfflinePrincipalId(scope.userId),\n scope.scopeId,\n ]);\n }\n\n async clearUser(userId: OfflinePrincipalId): Promise<void> {\n await this.#transaction((database) => this.#clearUser(database, userId));\n }\n\n async #clearUser(database: string, userId: OfflinePrincipalId): Promise<void> {\n const principal = canonicalOfflinePrincipalId(userId);\n await this.#execute(database, 'DELETE FROM offline_session_manifests WHERE user_id = ?', [principal]);\n await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ?', [principal]);\n await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ?', [principal]);\n await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ?', [principal]);\n await this.#execute(database, 'DELETE FROM offline_pull_attentions WHERE user_id = ?', [principal]);\n for (const entity of this.#options.replicaSchema.entities) {\n await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [principal]);\n }\n await this.#execute(database, 'UPDATE offline_metadata SET last_user_id = NULL WHERE id = 1 AND last_user_id = ?', [principal]);\n }\n\n async clearScope(scope: OfflineScope): Promise<void> {\n await this.#transaction((database) => this.#clearScope(database, scope));\n }\n\n async #clearScope(database: string, scope: OfflineScope): Promise<void> {\n const values = [canonicalOfflinePrincipalId(scope.userId), scope.scopeId];\n const partitionSourceKeys = this.#options.replicaSchema.entities\n .filter((entity) => entity.scope === 'partition')\n .map((entity) => entity.sourceKey);\n if (partitionSourceKeys.length > 0) {\n await this.#execute(\n database,\n `DELETE FROM offline_sync_commands\n WHERE user_id = ? AND scope_id = ? AND source_key IN (${partitionSourceKeys.map(() => '?').join(', ')})`,\n [...values, ...partitionSourceKeys],\n );\n }\n await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', values);\n await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ? AND scope_id = ?', values);\n await this.#execute(database, 'DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', values);\n for (const entity of this.#options.replicaSchema.entities) {\n if (entity.scope !== 'partition') continue;\n await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ? AND _offline_scope_id = ?`, values);\n }\n }\n\n async transactReplica(transaction: OfflineReplicaTransaction): Promise<void> {\n for (const row of transaction.putRows ?? []) this.#validateReplicaRow(row);\n const apply = (databaseId: string): Promise<void> => this.#applyReplicaTransaction(databaseId, transaction);\n await this.#transaction(apply);\n }\n\n async #applyReplicaTransaction(databaseId: string, transaction: OfflineReplicaTransaction): Promise<void> {\n const releases = new Map<string, OfflineReplicaRemoteIdRelease>();\n for (const release of transaction.releaseRemoteIds ?? []) {\n this.#assertValidReleaseRemoteId(release.remoteId);\n const key = this.#replicaRowKey(release);\n if (releases.has(key)) {\n throw new Error(\n `Offline replica remoteId release is duplicated for ${release.sourceKey}/${canonicalOfflineReplicaIdentity(release.identity)}.`,\n );\n }\n releases.set(key, release);\n }\n const consumedReleases = new Set<string>();\n for (const row of transaction.putRows ?? []) {\n const key = this.#replicaRowKey(row);\n const release = releases.get(key);\n await this.#putReplicaRow(databaseId, row, release);\n if (release) consumedReleases.add(key);\n }\n if (consumedReleases.size !== releases.size) {\n throw new Error('Offline replica remoteId release must match an existing row in putRows.');\n }\n for (const row of transaction.removeRows ?? []) await this.#removeReplicaRow(databaseId, row);\n for (const command of transaction.putCommands ?? []) await this.#putCommand(databaseId, command);\n for (const commandId of transaction.removeCommandIds ?? []) {\n await this.#execute(databaseId, 'DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId]);\n }\n for (const cursor of transaction.putCursors ?? []) await this.#putReplicaCursor(databaseId, cursor);\n for (const attention of transaction.putPullAttentions ?? []) {\n await this.#execute(\n databaseId,\n `INSERT INTO offline_pull_attentions (user_id, scope_id, reason, status) VALUES (?, ?, ?, ?)\n ON CONFLICT(user_id, scope_id) DO UPDATE SET reason = excluded.reason, status = excluded.status`,\n [\n canonicalOfflinePrincipalId(attention.userId),\n attention.scopeId,\n attention.reason,\n attention.status === undefined ? null : attention.status,\n ],\n );\n }\n for (const scope of transaction.removePullAttentions ?? []) {\n await this.#execute(databaseId, 'DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', [\n canonicalOfflinePrincipalId(scope.userId),\n scope.scopeId,\n ]);\n }\n }\n\n async #open(): Promise<void> {\n await this.#openDatabase().catch((error: unknown) => {\n throw this.#mapInitializationError(error);\n });\n }\n\n async #openDatabase(): Promise<void> {\n if (!this.#sqlite) {\n throw new OfflineStorageUnavailableError('storage_unavailable', 'Native offline storage requires a community SQLite connection');\n }\n const { databaseId } = await this.#sqlite.open({\n databaseName: this.#options.databaseName,\n createEncryptionKey: this.#wrapCreateEncryptionKey(this.#options.createEncryptionKey),\n });\n this.#databaseId = databaseId;\n for (const statement of SCHEMA) await this.#execute(databaseId, statement);\n const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');\n if (metadata.length === 0) {\n await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [\n OFFLINE_SCHEMA_VERSION,\n ]);\n } else {\n const storedVersion = this.#number(metadata[0]!['schema_version']);\n if (storedVersion !== OFFLINE_SCHEMA_VERSION) {\n throw new OfflineStorageUnavailableError(\n 'core_schema_incompatible',\n `Unsupported offline storage schema version ${storedVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +\n 'A lossless core schema migration is required before this database can be opened.',\n );\n }\n }\n await this.#initializeReplicaSchema(databaseId);\n }\n\n async #initializeReplicaSchema(databaseId: string): Promise<void> {\n const bundle = this.#options.replicaSchema;\n const targetVersion = bundle.version;\n const targetHash = await sha256OfflineReplicaSchema(bundle);\n const rows = await this.#queryDatabase(databaseId, 'SELECT version, schema_hash FROM offline_replica_schema_metadata WHERE id = 1');\n const storedVersion = rows[0] ? this.#number(rows[0]['version']) : null;\n const storedHash = rows[0] ? this.#string(rows[0]['schema_hash']) : null;\n\n if (storedVersion === null) {\n await this.#nativeTransaction(databaseId, async () => {\n await this.#executeReplicaCreateStatements(databaseId, bundle);\n await this.#upsertReplicaSchemaMetadata(databaseId, targetVersion, targetHash);\n });\n return;\n }\n\n if (storedVersion === targetVersion && storedHash === targetHash) {\n return;\n }\n\n if (storedVersion === targetVersion) {\n throw new OfflineStorageUnavailableError(\n 'replica_schema_mismatch',\n `Offline replica schema hash mismatch at version ${targetVersion}. Reinstall the application or bump replicaSchema.version after intentional schema changes.`,\n );\n }\n\n if (storedVersion > targetVersion) {\n throw new OfflineStorageUnavailableError(\n 'replica_schema_mismatch',\n `Offline replica schema version ${storedVersion} is newer than application version ${targetVersion}. Upgrade the application before opening this database.`,\n );\n }\n\n await this.#nativeTransaction(databaseId, async () => {\n for (let version = storedVersion; version < targetVersion; version++) {\n const migration = bundle.migrations.find((candidate) => candidate.fromVersion === version);\n if (!migration) {\n throw new OfflineStorageUnavailableError(\n 'migration_missing',\n `Missing offline replica schema migration from version ${version} to ${version + 1}.`,\n );\n }\n for (const statement of migration.statements) {\n await this.#execute(databaseId, statement);\n }\n }\n await this.#executeReplicaCreateStatements(databaseId, bundle);\n await this.#upsertReplicaSchemaMetadata(databaseId, targetVersion, targetHash);\n });\n }\n\n #wrapCreateEncryptionKey(createEncryptionKey: (() => Promise<string>) | undefined): (() => Promise<string>) | undefined {\n if (!createEncryptionKey) return undefined;\n return () => {\n const create = async (): Promise<string> => {\n const encryptionKey = await createEncryptionKey();\n if (!encryptionKey) {\n throw new OfflineStorageUnavailableError(\n 'encryption_key_unavailable',\n 'Native offline storage requires a non-empty encryption key on first open',\n );\n }\n return encryptionKey;\n };\n return create().catch((error: unknown) => {\n if (error instanceof OfflineStorageUnavailableError) throw error;\n throw new OfflineStorageUnavailableError(\n 'encryption_key_unavailable',\n error instanceof Error ? error.message : 'Offline encryption key is unavailable.',\n { cause: error },\n );\n });\n };\n }\n\n #mapInitializationError(error: unknown): OfflineStorageUnavailableError {\n if (error instanceof OfflineStorageUnavailableError) return error;\n const message = error instanceof Error ? error.message : 'Offline storage is unavailable.';\n if (message.includes('non-empty encryption key on first open')) {\n return new OfflineStorageUnavailableError('encryption_key_unavailable', message, { cause: error });\n }\n return new OfflineStorageUnavailableError('storage_unavailable', message || 'Offline storage is unavailable.', {\n cause: error,\n });\n }\n\n async #executeReplicaCreateStatements(databaseId: string, bundle: OfflineReplicaSchemaBundle): Promise<void> {\n for (const entity of bundle.entities) {\n for (const statement of entity.createTableSql) {\n await this.#execute(databaseId, statement);\n }\n }\n }\n\n async #upsertReplicaSchemaMetadata(databaseId: string, version: number, schemaHash: string): Promise<void> {\n await this.#execute(\n databaseId,\n `INSERT INTO offline_replica_schema_metadata (id, version, schema_hash) VALUES (1, ?, ?)\n ON CONFLICT(id) DO UPDATE SET version = excluded.version, schema_hash = excluded.schema_hash`,\n [version, schemaHash],\n );\n }\n\n async #nativeTransaction<T>(databaseId: string, run: () => Promise<T>): Promise<T> {\n await this.#sqlite!.beginTransaction({ databaseId });\n const execute = async (): Promise<T> => run();\n return execute()\n .then(async (result) => {\n await this.#sqlite!.commitTransaction({ databaseId });\n return result;\n })\n .catch(async (error: unknown) => {\n const rollback = await this.#sqlite!.rollbackTransaction({ databaseId }).then(\n () => ({ status: 'fulfilled' as const }),\n (rollbackError: unknown) => ({ status: 'rejected' as const, rollbackError }),\n );\n if (rollback.status === 'rejected') {\n throw new AggregateError([error, rollback.rollbackError], 'Offline SQLite transaction and rollback both failed.', {\n cause: error,\n });\n }\n throw error;\n });\n }\n\n async #databaseConnection(): Promise<string> {\n await this.initialize();\n if (!this.#databaseId) throw new Error('Offline SQLite database is not initialized');\n return this.#databaseId;\n }\n\n async #readLastUserId(): Promise<OfflinePrincipalId | null> {\n const rows = await this.#query('SELECT last_user_id FROM offline_metadata WHERE id = 1');\n const value = this.#stringOrNull(rows[0]?.['last_user_id']);\n return value === null ? null : parseOfflinePrincipalId(value);\n }\n\n async #readSessionManifest<T>(userId: OfflinePrincipalId): Promise<T | null> {\n const rows = await this.#query('SELECT value_json FROM offline_session_manifests WHERE user_id = ?', [\n canonicalOfflinePrincipalId(userId),\n ]);\n const row = rows[0];\n return row ? this.#parse<T>(row['value_json']) : null;\n }\n\n async #readReplicaRows<TValues>(scope: OfflineScope, sourceKey: string): Promise<OfflineReplicaRow<TValues>[]> {\n const schema = this.#resolveReplicaEntitySchema(sourceKey);\n const predicates = ['_offline_user_id = ?'];\n const values: SQLiteValue[] = [canonicalOfflinePrincipalId(scope.userId)];\n if (schema.scope === 'partition') {\n predicates.push('_offline_scope_id = ?');\n values.push(scope.scopeId);\n }\n const orderBy =\n schema.identity.kind === 'naturalKey'\n ? schema.identity.sourceKeys.map((key) => schema.fields.find((field) => field.sourceKey === key)!.sqliteColumnName!).join(', ')\n : 'local_id ASC';\n const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY ${orderBy}`, values);\n return rows\n .filter((row) => (row['_offline_visibility'] ?? 'present') !== 'pending_delete')\n .map((row) => this.#replicaRowFromSqliteRow<TValues>(schema, scope, sourceKey, row));\n }\n\n async #readReplicaRowByRemoteIdentity<TValues>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaRemoteIdentity,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n const schema = this.#resolveReplicaEntitySchema(sourceKey);\n canonicalOfflineRemoteIdentity(schema, identity);\n if (schema.identity.kind === 'generated') {\n const predicates = ['server_id = ?', '_offline_user_id = ?'];\n const values: SQLiteValue[] = [identity.remoteId!, canonicalOfflinePrincipalId(scope.userId)];\n if (schema.scope === 'partition') {\n predicates.push('_offline_scope_id = ?');\n values.push(scope.scopeId);\n }\n const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);\n const row = rows[0];\n return row ? this.#replicaRowFromSqliteRow<TValues>(schema, scope, sourceKey, row) : null;\n }\n const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey!);\n const predicates = ['_offline_user_id = ?'];\n const values: SQLiteValue[] = [canonicalOfflinePrincipalId(scope.userId)];\n if (schema.scope === 'partition') {\n predicates.push('_offline_scope_id = ?');\n values.push(scope.scopeId);\n }\n for (const sourceKeyPart of schema.identity.sourceKeys) {\n const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart)!;\n predicates.push(`${field.sqliteColumnName!} = ?`);\n values.push(naturalKey[sourceKeyPart]!);\n }\n const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);\n const row = rows[0];\n return row ? this.#replicaRowFromSqliteRow<TValues>(schema, scope, sourceKey, row) : null;\n }\n\n async #readReplicaCursor(scope: OfflineScope): Promise<OfflineReplicaCursor | null> {\n const rows = await this.#query('SELECT cursor FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', [\n canonicalOfflinePrincipalId(scope.userId),\n scope.scopeId,\n ]);\n const row = rows[0];\n if (!row) return null;\n return { ...scope, cursor: this.#string(row['cursor']) };\n }\n\n async #readPullAttentions(userId: OfflinePrincipalId): Promise<OfflinePullAttention[]> {\n const rows = await this.#query('SELECT scope_id, reason, status FROM offline_pull_attentions WHERE user_id = ? ORDER BY scope_id', [\n canonicalOfflinePrincipalId(userId),\n ]);\n return rows.map((row) => {\n const status = row['status'];\n const attention: OfflinePullAttention = {\n userId,\n scopeId: this.#string(row['scope_id']),\n reason: this.#string(row['reason']) as OfflinePullAttentionReason,\n };\n if (status !== null && status !== undefined) attention.status = this.#number(status);\n return attention;\n });\n }\n\n async #readCommands(scope: OfflineScope): Promise<OfflineCommand[]> {\n const rows = await this.#query(\n 'SELECT * FROM offline_sync_commands WHERE user_id = ? AND scope_id = ? ORDER BY created_at ASC, command_id ASC',\n [canonicalOfflinePrincipalId(scope.userId), scope.scopeId],\n );\n return rows.map((row) => this.#command(row));\n }\n\n async #readCommandsForUser(userId: OfflinePrincipalId): Promise<OfflineCommand[]> {\n const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? ORDER BY created_at ASC, command_id ASC', [\n canonicalOfflinePrincipalId(userId),\n ]);\n return rows.map((row) => this.#command(row));\n }\n\n #reader(): OfflineRepositoryReader {\n return {\n getLastUserId: () => this.#readLastUserId(),\n getSessionManifest: (userId) => this.#readSessionManifest(userId),\n getReplicaRow: async <TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null> =>\n (await this.#queryReplicaRow(scope, sourceKey, identity, false)) as OfflineReplicaRow<TValues> | null,\n getReplicaRowIncludingPendingDelete: async <TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null> =>\n (await this.#queryReplicaRow(scope, sourceKey, identity, true)) as OfflineReplicaRow<TValues> | null,\n getReplicaRows: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey),\n getReplicaRowByRemoteId: async (scope, sourceKey, remoteId) => {\n if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated') return null;\n return this.#readReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });\n },\n getReplicaRowByRemoteIdentity: (scope, sourceKey, identity) => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity),\n getReplicaCursor: (scope) => this.#readReplicaCursor(scope),\n getPullAttentions: (userId) => this.#readPullAttentions(userId),\n getCommands: (scope) => this.#readCommands(scope),\n getCommandsForUser: (userId) => this.#readCommandsForUser(userId),\n };\n }\n\n #atomicRepository(): OfflineRepository {\n const reader = this.#reader();\n const atomicTransaction = <T>(run: (databaseId: string) => Promise<T>, marksCommit = true): Promise<T> =>\n this.#queueAtomicOperation(() => this.#atomicTransaction(this.#databaseId!, run, marksCommit));\n return {\n initialize: settledSqliteOperation,\n ...reader,\n runReadSnapshot: (read) =>\n this.#queueAtomicOperation(() =>\n this.#nativeTransaction(this.#databaseId!, async () => {\n this.#readSnapshotActive = true;\n const executeRead = async () => read(reader);\n return executeRead().finally(() => (this.#readSnapshotActive = false));\n }),\n ),\n putCommand: (command) => atomicTransaction((databaseId) => this.#putCommand(databaseId, command)),\n replaceCommand: (command) => atomicTransaction((databaseId) => this.#putCommand(databaseId, command)),\n removeCommand: (commandId) =>\n atomicTransaction((databaseId) => this.#execute(databaseId, 'DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId])),\n putPullAttention: (attention) =>\n atomicTransaction((databaseId) => this.#applyReplicaTransaction(databaseId, { putPullAttentions: [attention] })),\n removePullAttention: (scope) =>\n atomicTransaction((databaseId) => this.#applyReplicaTransaction(databaseId, { removePullAttentions: [scope] })),\n setLastUserId: (userId) =>\n atomicTransaction((databaseId) =>\n this.#execute(\n databaseId,\n `INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, ?)\n ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version, last_user_id = excluded.last_user_id`,\n [OFFLINE_SCHEMA_VERSION, canonicalOfflinePrincipalId(userId)],\n ),\n ),\n putSessionManifest: (userId, value) =>\n atomicTransaction((databaseId) =>\n this.#execute(\n databaseId,\n `INSERT INTO offline_session_manifests (user_id, value_json) VALUES (?, ?)\n ON CONFLICT(user_id) DO UPDATE SET value_json = excluded.value_json`,\n [canonicalOfflinePrincipalId(userId), JSON.stringify(value)],\n ),\n ),\n clearUser: (userId) => atomicTransaction((databaseId) => this.#clearUser(databaseId, userId)),\n clearScope: (scope) => atomicTransaction((databaseId) => this.#clearScope(databaseId, scope)),\n transactReplica: (transaction) => {\n for (const row of transaction.putRows ?? []) this.#validateReplicaRow(row);\n return atomicTransaction((databaseId) => this.#applyReplicaTransaction(databaseId, transaction));\n },\n };\n }\n\n async #withCommittedRead<T>(operation: () => Promise<T>): Promise<T> {\n await this.initialize();\n if (this.#readSnapshotActive) {\n return operation();\n }\n if (this.#atomicMutationRevision !== null) {\n return this.#queueAtomicOperation(operation);\n }\n await this.#writes;\n this.#beginReaders();\n const read = async (): Promise<T> => operation();\n return read().finally(() => this.#endReaders());\n }\n\n #beginReaders(): void {\n if (this.#activeReaders === 0) {\n this.#readersIdle = new Promise<void>((resolve) => {\n this.#resolveReadersIdle = resolve;\n });\n }\n this.#activeReaders += 1;\n }\n\n #endReaders(): void {\n this.#activeReaders -= 1;\n if (this.#activeReaders === 0) {\n this.#resolveReadersIdle?.();\n this.#resolveReadersIdle = null;\n this.#readersIdle = settledSqliteOperation();\n }\n }\n\n async #query(statement: string, values: SQLiteValue[] = []): Promise<SQLiteRow[]> {\n return this.#queryDatabase(await this.#databaseConnection(), statement, values);\n }\n\n #write(statement: string, values: SQLiteValue[]): Promise<void> {\n return this.#queueWrite((databaseId) => this.#execute(databaseId, statement, values));\n }\n\n #queueWrite(run: (databaseId: string) => Promise<void>): Promise<void> {\n if (this.#atomicMutationRevision !== null) {\n return this.#atomicIdle.then(() => this.#queueWrite(run));\n }\n const write = this.#writes.then(async (): Promise<void> => {\n if (this.#activeReaders > 0) await this.#readersIdle;\n await run(await this.#databaseConnection());\n });\n this.#writes = write.catch((): void => undefined);\n return write;\n }\n\n #transaction<T>(run: (databaseId: string) => Promise<T>): Promise<T> {\n if (this.#atomicMutationRevision !== null) {\n return this.#atomicIdle.then(() => this.#transaction(run));\n }\n const transaction = this.#writes.then(async (): Promise<T> => {\n if (this.#activeReaders > 0) await this.#readersIdle;\n const databaseId = await this.#databaseConnection();\n return this.#nativeTransaction(databaseId, () => run(databaseId));\n });\n this.#writes = transaction.then(\n () => undefined,\n () => undefined,\n );\n return transaction;\n }\n\n async #atomicTransaction<T>(databaseId: string, run: (databaseId: string) => Promise<T>, marksCommit = true): Promise<T> {\n const expected = this.#atomicMutationRevision;\n if (expected === null) throw new Error('Offline replica atomic mutation is not active.');\n const result = await this.#nativeTransaction(databaseId, async () => {\n // A write, even when it leaves the value unchanged, obtains SQLite's\n // RESERVED lock before the revision check. No second connection can\n // commit between this check and the transaction commit.\n await this.#execute(databaseId, 'UPDATE offline_metadata SET schema_version = schema_version WHERE id = 1');\n const actual = await this.#dataVersion(databaseId);\n if (actual !== expected) {\n throw new Error('Offline replica changed through another SQLite connection; retry the operation from fresh state.');\n }\n return run(databaseId);\n });\n if (marksCommit) this.#atomicMutationCommitted = true;\n return result;\n }\n\n #queueAtomicOperation<T>(run: () => Promise<T>): Promise<T> {\n const operation = this.#atomicOperations.then(run);\n this.#atomicOperations = operation.then(\n () => undefined,\n () => undefined,\n );\n return operation;\n }\n\n async #dataVersion(databaseId: string): Promise<number> {\n const rows = await this.#queryDatabase(databaseId, 'PRAGMA data_version');\n return this.#number(rows[0]?.['data_version']);\n }\n\n #command(row: SQLiteRow): OfflineCommand {\n return {\n commandId: this.#string(row['command_id']),\n userId: parseOfflinePrincipalId(this.#string(row['user_id'])),\n scopeId: this.#string(row['scope_id']),\n aggregateType: this.#string(row['aggregate_type']),\n sourceKey: this.#string(row['source_key']),\n identity: parseOfflineCommandIdentity(this.#parse(row['identity_json'])),\n operation: this.#string(row['operation']),\n payload: this.#parse(row['payload_json']),\n ...(row['local_only_footprint_json'] === null || row['local_only_footprint_json'] === undefined\n ? {}\n : { localOnlyFootprint: this.#parse(row['local_only_footprint_json']) }),\n replicaMutation: this.#string(row['replica_mutation']) as 'upsert' | 'delete',\n baseRevision: this.#parseNullable(row['base_revision_json']),\n state: this.#string(row['state']) as OfflineCommand['state'],\n attempts: this.#number(row['attempts']),\n retryAt: this.#numberOrNull(row['retry_at']),\n createdAt: this.#number(row['created_at']),\n lastErrorCode: this.#stringOrNull(row['last_error_code']),\n serverCommitUnknown: this.#numberOrNull(row['server_commit_unknown']) === 1,\n ...(row['reconciliation_identity_json'] === null || row['reconciliation_identity_json'] === undefined\n ? {}\n : { reconciliationIdentity: this.#parse(row['reconciliation_identity_json']) as OfflineCommand['reconciliationIdentity'] }),\n };\n }\n\n #putCommand(databaseId: string, command: OfflineCommand): Promise<void> {\n return this.#execute(\n databaseId,\n `INSERT INTO offline_sync_commands\n (command_id, user_id, scope_id, aggregate_type, source_key, identity_json, operation, payload_json,\n local_only_footprint_json, replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code,\n server_commit_unknown, reconciliation_identity_json)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(command_id) DO UPDATE SET\n user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,\n source_key = excluded.source_key,\n identity_json = excluded.identity_json, operation = excluded.operation, payload_json = excluded.payload_json,\n local_only_footprint_json = excluded.local_only_footprint_json,\n replica_mutation = excluded.replica_mutation,\n payload_hash = excluded.payload_hash,\n base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,\n retry_at = excluded.retry_at, created_at = excluded.created_at, last_error_code = excluded.last_error_code,\n server_commit_unknown = excluded.server_commit_unknown,\n reconciliation_identity_json = excluded.reconciliation_identity_json`,\n [\n command.commandId,\n canonicalOfflinePrincipalId(command.userId),\n command.scopeId,\n command.aggregateType,\n command.sourceKey,\n serializeOfflineCommandIdentity(command.identity),\n command.operation,\n JSON.stringify(command.payload),\n command.localOnlyFootprint === undefined ? null : JSON.stringify(command.localOnlyFootprint),\n command.replicaMutation ?? 'upsert',\n '',\n this.#stringifyNullable(command.baseRevision),\n command.state,\n command.attempts,\n command.retryAt,\n command.createdAt,\n command.lastErrorCode,\n command.serverCommitUnknown === true ? 1 : 0,\n command.reconciliationIdentity === undefined ? null : JSON.stringify(command.reconciliationIdentity),\n ],\n );\n }\n\n async #queryReplicaRow(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n includePendingDelete: boolean,\n ): Promise<OfflineReplicaRow | null> {\n const schema = this.#resolveReplicaEntitySchema(sourceKey);\n const predicates = ['_offline_user_id = ?'];\n const values: SQLiteValue[] = [canonicalOfflinePrincipalId(scope.userId)];\n if (schema.scope === 'partition') {\n predicates.push('_offline_scope_id = ?');\n values.push(scope.scopeId);\n }\n if (identity.kind === 'generated' || identity.kind === 'local') {\n if (\n (identity.kind === 'generated' && schema.identity.kind !== 'generated') ||\n (identity.kind === 'local' && schema.identity.kind !== 'localOnly')\n ) {\n return null;\n }\n predicates.push('local_id = ?');\n values.push(identity.localId);\n } else {\n const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey);\n for (const sourceKeyPart of schema.identity.sourceKeys) {\n const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart)!;\n predicates.push(`${field.sqliteColumnName!} = ?`);\n values.push(naturalKey[sourceKeyPart]!);\n }\n }\n const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);\n const row = rows[0];\n if (!row || (!includePendingDelete && (row['_offline_visibility'] ?? 'present') === 'pending_delete')) return null;\n return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row);\n }\n\n async #putReplicaRow(databaseId: string, row: OfflineReplicaRow, release: OfflineReplicaRemoteIdRelease | undefined): Promise<void> {\n const schema = this.#resolveReplicaEntitySchema(row.sourceKey);\n if (row.identity.kind === 'generated') {\n assertOfflineReplicaGeneratedRemoteId(schema, row.identity.remoteId);\n }\n if (schema.identity.kind === 'naturalKey') {\n if (row.identity.kind !== 'natural') {\n throw new Error(`Offline replica source \"${row.sourceKey}\" requires natural identity.`);\n }\n const valuesIdentity = offlineNaturalKeyFromValues(schema, row.values)!;\n if (\n canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) !==\n canonicalOfflineRemoteIdentity(schema, { naturalKey: valuesIdentity })\n ) {\n throw new Error(`Offline replica identity naturalKey must match values for \"${schema.sourceKey}\".`);\n }\n }\n const encoded = encodeOfflineReplicaValues(schema, row.values);\n if (row.confirmedValues !== null) encodeOfflineReplicaValues(schema, row.confirmedValues);\n assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);\n const existing = await this.#queryReplicaRow(row, row.sourceKey, replicaAddressFromIdentity(row.identity), true);\n if (!existing && release) {\n throw new Error(\n `Offline replica remoteId release requires an existing row for ${row.sourceKey}/${canonicalOfflineReplicaIdentity(row.identity)}.`,\n );\n }\n if (existing) this.#assertReplicaIdentityAssignment(schema, existing, row, release);\n const confirmedValues = row.confirmedValues === null ? null : projectOfflineReplicaValues(schema, row.confirmedValues);\n const { sql, domainColumns } = this.#buildReplicaUpsertStatement(schema);\n const values: SQLiteValue[] = [];\n if (schema.identity.kind === 'generated' || schema.identity.kind === 'localOnly') {\n const expectedKind = schema.identity.kind === 'generated' ? 'generated' : 'local';\n if (row.identity.kind !== expectedKind) {\n throw new Error(`Offline replica source \"${row.sourceKey}\" requires ${expectedKind} identity.`);\n }\n values.push(row.identity.localId);\n }\n values.push(canonicalOfflinePrincipalId(row.userId));\n if (schema.scope === 'partition') values.push(row.scopeId);\n if (schema.identity.kind === 'generated') {\n if (row.identity.kind !== 'generated') {\n throw new Error(`Offline replica source \"${row.sourceKey}\" requires generated identity.`);\n }\n values.push(row.identity.remoteId);\n }\n values.push(\n confirmedValues === null ? null : JSON.stringify(confirmedValues),\n row.serverRevision == null ? null : JSON.stringify(row.serverRevision),\n row.syncState,\n row.visibility ?? 'present',\n row.fetchedAt,\n ...domainColumns.map((column) => encoded[column] ?? null),\n );\n await this.#execute(databaseId, sql, values);\n }\n\n #removeReplicaRow(databaseId: string, key: OfflineReplicaRowKey): Promise<void> {\n const schema = this.#resolveReplicaEntitySchema(key.sourceKey);\n const predicates = ['_offline_user_id = ?'];\n const values: SQLiteValue[] = [canonicalOfflinePrincipalId(key.userId)];\n if (schema.scope === 'partition') {\n predicates.push('_offline_scope_id = ?');\n values.push(key.scopeId);\n }\n if (key.identity.kind === 'generated' || key.identity.kind === 'local') {\n predicates.push('local_id = ?');\n values.push(key.identity.localId);\n } else {\n for (const sourceKeyPart of schema.identity.sourceKeys) {\n const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart)!;\n predicates.push(`${field.sqliteColumnName!} = ?`);\n values.push(key.identity.naturalKey[sourceKeyPart]!);\n }\n }\n return this.#execute(databaseId, `DELETE FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);\n }\n\n #putReplicaCursor(databaseId: string, cursor: OfflineReplicaCursor): Promise<void> {\n return this.#execute(\n databaseId,\n `INSERT INTO offline_replica_cursors (user_id, scope_id, cursor) VALUES (?, ?, ?)\n ON CONFLICT(user_id, scope_id) DO UPDATE SET cursor = excluded.cursor`,\n [canonicalOfflinePrincipalId(cursor.userId), cursor.scopeId, cursor.cursor],\n );\n }\n\n #buildReplicaUpsertStatement(schema: OfflineReplicaEntitySchema<Record<string, unknown>>): {\n sql: string;\n domainColumns: readonly string[];\n } {\n const insertColumns = ['_offline_user_id'];\n const updateSets = ['_offline_user_id = excluded._offline_user_id'];\n const conflictTarget: string[] = ['_offline_user_id'];\n if (schema.scope === 'partition') {\n insertColumns.push('_offline_scope_id');\n updateSets.push('_offline_scope_id = excluded._offline_scope_id');\n conflictTarget.push('_offline_scope_id');\n }\n if (schema.identity.kind === 'generated') {\n insertColumns.unshift('local_id');\n insertColumns.push('server_id');\n updateSets.push('server_id = excluded.server_id');\n conflictTarget.push('local_id');\n } else if (schema.identity.kind === 'naturalKey') {\n for (const sourceKey of schema.identity.sourceKeys) {\n const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKey)!;\n conflictTarget.push(field.sqliteColumnName!);\n }\n } else {\n insertColumns.unshift('local_id');\n conflictTarget.push('local_id');\n }\n insertColumns.push(\n '_offline_confirmed_json',\n '_offline_server_revision_json',\n '_offline_sync_state',\n '_offline_visibility',\n '_offline_fetched_at',\n );\n updateSets.push(\n '_offline_confirmed_json = excluded._offline_confirmed_json',\n '_offline_server_revision_json = excluded._offline_server_revision_json',\n '_offline_sync_state = excluded._offline_sync_state',\n '_offline_visibility = excluded._offline_visibility',\n '_offline_fetched_at = excluded._offline_fetched_at',\n );\n const domainColumns: string[] = [];\n for (const field of schema.fields) {\n if (field.policy !== 'column' || field.sqliteColumnName === null) continue;\n insertColumns.push(field.sqliteColumnName);\n updateSets.push(`${field.sqliteColumnName} = excluded.${field.sqliteColumnName}`);\n domainColumns.push(field.sqliteColumnName);\n }\n const placeholders = insertColumns.map(() => '?').join(', ');\n return {\n sql: `INSERT INTO ${schema.tableName} (${insertColumns.join(', ')})\n VALUES (${placeholders})\n ON CONFLICT(${conflictTarget.join(', ')}) DO UPDATE SET ${updateSets.join(', ')}`,\n domainColumns,\n };\n }\n\n #replicaRowFromSqliteRow<TValues>(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n scope: OfflineScope,\n sourceKey: string,\n row: SQLiteRow,\n ): OfflineReplicaRow<TValues> {\n const identity = this.#identityFromSqliteRow(schema, row);\n return {\n ...scope,\n sourceKey,\n identity,\n values: decodeOfflineReplicaValues(schema, row) as TValues,\n confirmedValues: this.#parseNullable<TValues>(row['_offline_confirmed_json']),\n serverRevision: this.#parseNullable<string | number>(row['_offline_server_revision_json']),\n fetchedAt: this.#number(row['_offline_fetched_at']),\n syncState: this.#string(row['_offline_sync_state']) as OfflineReplicaRow['syncState'],\n visibility: (row['_offline_visibility'] ?? 'present') as 'present' | 'pending_delete',\n };\n }\n\n #identityFromSqliteRow(schema: OfflineReplicaEntitySchema<Record<string, unknown>>, row: SQLiteRow): OfflineReplicaIdentity {\n if (schema.identity.kind === 'naturalKey') {\n return offlineNaturalReplicaIdentity(schema, decodeOfflineReplicaValues(schema, row));\n }\n const localId = this.#string(row['local_id']);\n if (schema.identity.kind === 'localOnly') return { kind: 'local', localId };\n const remoteId = row['server_id'];\n if (remoteId == null) return offlineGeneratedReplicaIdentity(localId, null);\n if (schema.identity.kind === 'generated' && schema.identity.affinity === 'TEXT') {\n return offlineGeneratedReplicaIdentity(localId, this.#string(remoteId));\n }\n return offlineGeneratedReplicaIdentity(localId, this.#number(remoteId));\n }\n\n #resolveReplicaEntitySchema(sourceKey: string): OfflineReplicaEntitySchema<Record<string, unknown>> {\n const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);\n if (!schema) throw new Error(`Unknown offline replica source key \"${sourceKey}\".`);\n return schema;\n }\n\n #validateReplicaRow(row: OfflineReplicaRow): void {\n const schema = this.#resolveReplicaEntitySchema(row.sourceKey);\n if (schema.identity.kind === 'localOnly') {\n if (row.identity.kind !== 'local') {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" requires local identity.`);\n }\n } else if (schema.identity.kind === 'generated') {\n if (row.identity.kind !== 'generated') {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" requires generated identity.`);\n }\n assertOfflineReplicaGeneratedRemoteId(schema, row.identity.remoteId);\n } else {\n if (row.identity.kind !== 'natural') {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" requires natural identity.`);\n }\n const fromValues = offlineNaturalKeyFromValues(schema, row.values)!;\n if (\n canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) !==\n canonicalOfflineRemoteIdentity(schema, { naturalKey: fromValues })\n ) {\n throw new Error(`Offline replica identity naturalKey must match values for \"${schema.sourceKey}\".`);\n }\n }\n encodeOfflineReplicaValues(schema, row.values);\n if (row.confirmedValues !== null) encodeOfflineReplicaValues(schema, row.confirmedValues);\n assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);\n }\n\n #replicaRowKey(row: OfflineReplicaRowKey): string {\n const schema = this.#resolveReplicaEntitySchema(row.sourceKey);\n return canonicalOfflineReplicaRowKey(schema, row);\n }\n\n #assertReplicaIdentityAssignment(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n existing: OfflineReplicaRow,\n incoming: OfflineReplicaRow,\n release: OfflineReplicaRemoteIdRelease | undefined,\n ): void {\n if (release && schema.identity.kind !== 'generated') {\n throw new Error(`Offline replica remoteId release is unsupported for source \"${incoming.sourceKey}\".`);\n }\n if (schema.identity.kind === 'localOnly') {\n if (existing.identity.kind !== 'local' || incoming.identity.kind !== 'local') {\n throw new Error(`Offline replica local identity is required for \"${incoming.sourceKey}\".`);\n }\n if (existing.identity.localId !== incoming.identity.localId) {\n throw new Error(`Offline replica localId is immutable for \"${schema.sourceKey}\".`);\n }\n return;\n }\n if (schema.identity.kind === 'generated') {\n if (existing.identity.kind !== 'generated' || incoming.identity.kind !== 'generated') {\n throw new Error(`Offline replica generated identity is required for \"${incoming.sourceKey}\".`);\n }\n if (release) {\n if (existing.identity.remoteId !== release.remoteId || incoming.identity.remoteId !== null) {\n throw new Error(\n `Offline replica remoteId release must transition current=${String(existing.identity.remoteId)} to incoming=null for ${incoming.sourceKey}/${incoming.identity.localId}.`,\n );\n }\n return;\n }\n if (existing.identity.localId !== incoming.identity.localId) {\n throw new Error(`Offline replica localId is immutable for \"${schema.sourceKey}\".`);\n }\n if (existing.identity.remoteId !== null && existing.identity.remoteId !== incoming.identity.remoteId) {\n throw new Error(\n `Offline replica remoteId is immutable: current=${String(existing.identity.remoteId)}, incoming=${String(incoming.identity.remoteId)}.`,\n );\n }\n return;\n }\n if (schema.identity.kind === 'naturalKey') {\n if (existing.identity.kind !== 'natural' || incoming.identity.kind !== 'natural') {\n throw new Error(`Offline replica natural identity is required for \"${schema.sourceKey}\".`);\n }\n const current = canonicalOfflineRemoteIdentity(schema, { naturalKey: existing.identity.naturalKey });\n const next = canonicalOfflineRemoteIdentity(schema, { naturalKey: incoming.identity.naturalKey });\n if (current !== next) throw new Error(`Offline replica naturalKey is immutable for \"${schema.sourceKey}\".`);\n }\n }\n\n #assertValidReleaseRemoteId(remoteId: import('./offline-replica-schema').OfflineGeneratedRemoteId): void {\n if (typeof remoteId === 'number') {\n if (!Number.isSafeInteger(remoteId) || remoteId <= 0) {\n throw new Error(`Offline replica release has invalid remoteId ${String(remoteId)}.`);\n }\n return;\n }\n if (typeof remoteId !== 'string' || remoteId.length === 0) {\n throw new Error(`Offline replica release has invalid remoteId ${String(remoteId)}.`);\n }\n }\n\n async #execute(databaseId: string, statement: string, values: SQLiteValue[] = []): Promise<void> {\n await this.#sqlite!.execute({ databaseId, statement, values });\n }\n\n async #queryDatabase(databaseId: string, statement: string, values: SQLiteValue[] = []): Promise<SQLiteRow[]> {\n const result = await this.#sqlite!.query({ databaseId, statement, values });\n return (result.rows ?? []).map((row) => {\n if (!Array.isArray(row)) return row as SQLiteRow;\n return Object.fromEntries(row.map((value, index) => [result.columns?.[index] ?? String(index), value]));\n });\n }\n\n #parse<T>(value: unknown): T {\n if (typeof value !== 'string') throw new Error('Invalid JSON value in offline SQLite database');\n return JSON.parse(value) as T;\n }\n\n #parseNullable<T>(value: unknown): T | null {\n return value == null ? null : this.#parse<T>(value);\n }\n\n #stringifyNullable(value: unknown): string | null {\n return value == null ? null : JSON.stringify(value);\n }\n\n #number(value: unknown): number {\n if (typeof value !== 'number') throw new Error('Invalid numeric value in offline SQLite database');\n return value;\n }\n\n #numberOrNull(value: unknown): number | null {\n return value == null ? null : this.#number(value);\n }\n\n #string(value: unknown): string {\n if (typeof value !== 'string') throw new Error('Invalid string value in offline SQLite database');\n return value;\n }\n\n #stringOrNull(value: unknown): string | null {\n return value == null ? null : this.#string(value);\n }\n}\n","import type { EnvironmentProviders, Provider, Type } from '@angular/core';\nimport { ErrorHandler, inject, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';\nimport { Capacitor } from '@capacitor/core';\nimport type { OfflineCommandExecutor, OfflineCommandResult } from './offline-command-executor';\nimport { OFFLINE_COMMAND_EXECUTOR, OFFLINE_SYNC_CONTEXT } from './offline-command-executor';\nimport type { OfflineCommandHooks } from './offline-command-hooks';\nimport { OFFLINE_COMMAND_HOOKS } from './offline-command-hooks';\nimport type { OfflineKitOptions } from './offline-kit-options';\nimport { OFFLINE_KIT_OPTIONS } from './offline-kit-options';\nimport { OfflineCoordinatorService } from './offline-coordinator.service';\nimport {\n OFFLINE_MUTATION_PERSISTENCE_ADAPTER,\n OFFLINE_MUTATION_PERSISTENCE_ENABLED,\n OfflineMutationPersistenceService,\n} from './offline-mutation-persistence.service';\nimport {\n IonicOfflineRepository,\n OFFLINE_REPOSITORY,\n selectOfflineRepository,\n supportsSynchronizedOfflineRepository,\n} from './offline-repository';\nimport type { OfflineMutationRequestPolicy, OfflineRequestPolicy } from './offline-request-policy';\nimport { provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy } from './offline-request-policy';\nimport type { OfflineAggregateIntentProjector } from './offline-aggregate-intent-projector';\nimport { OFFLINE_AGGREGATE_INTENT_PROJECTOR } from './offline-aggregate-intent-projector';\nimport type { OfflineReplicaProjector, OfflineReplicaPuller } from './offline-replica-puller';\nimport { OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER } from './offline-replica-puller';\nimport { OfflineSessionService } from './offline-session.service';\nimport {\n COMMUNITY_SQLITE,\n type CommunitySqliteConnection,\n createCommunitySqliteDriver,\n SqliteOfflineRepository,\n} from './sqlite-offline-repository';\n\n/** Configuration for the standard offline repository, outbox, and request-policy runtime. */\ninterface ProvideOfflineOptionsBase extends OfflineKitOptions {\n /** Product policies that map URLs and DTOs to generic replica/outbox operations. */\n requestPolicies: readonly Type<OfflineRequestPolicy>[];\n /** Optional product hooks for entity projection and command cleanup. */\n commandHooks?: Type<OfflineCommandHooks>;\n /** Optional additional providers required by product adapters. */\n providers?: readonly Provider[];\n /** Optional pure adapter for product-owned local-only projections applied inside the Kit pull transaction. */\n replicaProjector?: Type<OfflineReplicaProjector>;\n /** Application-installed `@capacitor-community/sqlite` connection. Required only on iOS and Android. */\n sqliteConnection?: CommunitySqliteConnection;\n}\n\n/** Full replica pull and durable Outbox synchronization. */\nexport interface ProvideSynchronizedOfflineOptions extends ProvideOfflineOptionsBase {\n mode?: 'synchronized';\n /** Creates the encrypted native database key on first install. */\n createEncryptionKey: () => Promise<string>;\n /** Product policies that replace matched writes with atomic local-first mutations. */\n mutationPolicies?: readonly Type<OfflineMutationRequestPolicy>[];\n /** Product adapter that sends opaque commands to its API. */\n commandExecutor: Type<OfflineCommandExecutor>;\n /** Product transport for explicit cursor-based server delta pulls. */\n replicaPuller: Type<OfflineReplicaPuller>;\n /**\n * Required pure adapter that rematerializes one aggregate from its\n * authoritative confirmed base/localOnly values and remaining Outbox intents.\n *\n * Kit calls it inside {@link OfflineReplicaMutationCoordinator} after enqueue,\n * replacement, discard, transport success, and pull acknowledgement. Do not\n * call the projector from product code.\n */\n aggregateIntentProjector: Type<OfflineAggregateIntentProjector>;\n}\n\n/** Server- or external-source read cache with no mutation transport or Outbox. */\nexport interface ProvideReadCacheOfflineOptions extends ProvideOfflineOptionsBase {\n mode: 'readCacheOnly';\n /** Creates the encrypted native cache database key on first install. Unused by the web repository. */\n createEncryptionKey: () => Promise<string>;\n mutationPolicies?: never;\n mutationPersistence?: never;\n commandExecutor?: never;\n replicaPuller?: never;\n}\n\nexport type ProvideOfflineOptions = ProvideSynchronizedOfflineOptions | ProvideReadCacheOfflineOptions;\n\nconst READ_CACHE_ONLY_COMMAND_EXECUTOR: OfflineCommandExecutor = {\n execute: async (): Promise<OfflineCommandResult> => {\n throw new Error('This offline provider is configured as a read-only cache.');\n },\n};\n\nconst READ_CACHE_ONLY_REPLICA_PULLER: OfflineReplicaPuller = {\n pull: async (request) => ({\n schemaVersion: request.schemaVersion,\n schemaHash: request.schemaHash,\n changes: [],\n nextCursor: request.cursor,\n hasMore: false,\n }),\n};\n\n/**\n * Provide the standard scoped offline runtime.\n *\n * @remarks\n * Web uses Ionic Storage. Native iOS/Android uses encrypted `@capacitor-community/sqlite`. The application owns\n * URL/DTO policy and command execution; the kit owns persistence, ordering, retries, and session\n * isolation.\n *\n * Optional {@link OfflineKitOptions.onStorageUnavailable} opts into online-only startup when\n * local storage cannot be opened; without it, the app initializer still throws.\n */\nexport function provideOffline(options: ProvideOfflineOptions): EnvironmentProviders {\n const synchronized = options.mode !== 'readCacheOnly';\n return makeEnvironmentProviders([\n ...(synchronized ? [options.commandExecutor, options.replicaPuller] : []),\n {\n provide: OFFLINE_KIT_OPTIONS,\n useValue: {\n mode: options.mode ?? 'synchronized',\n databaseName: options.databaseName,\n createEncryptionKey: options.createEncryptionKey,\n replicaSchema: options.replicaSchema,\n wireProtocol: options.wireProtocol,\n outboxLimits: options.outboxLimits,\n mutationPersistence: options.mutationPersistence,\n onStorageUnavailable: options.onStorageUnavailable,\n },\n },\n {\n provide: COMMUNITY_SQLITE,\n useValue: options.sqliteConnection ? createCommunitySqliteDriver(options.sqliteConnection) : null,\n },\n {\n provide: OFFLINE_REPOSITORY,\n useFactory: () => selectOfflineRepository(Capacitor.getPlatform(), inject(IonicOfflineRepository), inject(SqliteOfflineRepository)),\n },\n {\n provide: OFFLINE_MUTATION_PERSISTENCE_ENABLED,\n useFactory: () => inject(OfflineMutationPersistenceService).enabled,\n },\n ...(options.mutationPersistence\n ? [\n options.mutationPersistence.adapter,\n { provide: OFFLINE_MUTATION_PERSISTENCE_ADAPTER, useExisting: options.mutationPersistence.adapter },\n ]\n : []),\n { provide: OFFLINE_SYNC_CONTEXT, useExisting: OfflineSessionService },\n synchronized\n ? { provide: OFFLINE_COMMAND_EXECUTOR, useExisting: options.commandExecutor }\n : { provide: OFFLINE_COMMAND_EXECUTOR, useValue: READ_CACHE_ONLY_COMMAND_EXECUTOR },\n synchronized\n ? { provide: OFFLINE_REPLICA_PULLER, useExisting: options.replicaPuller }\n : { provide: OFFLINE_REPLICA_PULLER, useValue: READ_CACHE_ONLY_REPLICA_PULLER },\n ...(options.commandHooks ? [options.commandHooks, { provide: OFFLINE_COMMAND_HOOKS, useExisting: options.commandHooks }] : []),\n ...(options.replicaProjector\n ? [options.replicaProjector, { provide: OFFLINE_REPLICA_PROJECTOR, useExisting: options.replicaProjector }]\n : []),\n ...(synchronized && 'aggregateIntentProjector' in options && options.aggregateIntentProjector\n ? [options.aggregateIntentProjector, { provide: OFFLINE_AGGREGATE_INTENT_PROJECTOR, useExisting: options.aggregateIntentProjector }]\n : []),\n ...options.requestPolicies.flatMap((policy) => provideOfflineRequestPolicy(policy)),\n ...(options.mutationPolicies ?? []).flatMap((policy) => provideOfflineMutationRequestPolicy(policy)),\n ...(options.providers ?? []),\n provideAppInitializer(() => {\n assertSupportedOfflineMode(Capacitor.getPlatform(), options.mode ?? 'synchronized');\n const coordinator = inject(OfflineCoordinatorService);\n const errorHandler = inject(ErrorHandler);\n const localInitialization = coordinator.initializeLocal();\n void coordinator.initialize().catch(async (error: unknown) => {\n const localSucceeded = await localInitialization.then(\n () => true,\n () => false,\n );\n if (!localSucceeded) return;\n try {\n errorHandler.handleError(error);\n } catch {\n // Error reporting must not create an unhandled background rejection.\n }\n });\n return localInitialization;\n }),\n ]);\n}\n\n/** Prevents unsupported multi-tab Web writes from silently losing Outbox state. */\nexport function assertSupportedOfflineMode(platform: string, mode: 'synchronized' | 'readCacheOnly'): void {\n if (!supportsSynchronizedOfflineRepository(platform) && mode === 'synchronized') {\n throw new Error(\n 'Offline synchronized mode is supported only by native repositories. Use readCacheOnly until the selected repository provides cross-context locking.',\n );\n }\n}\n","import type { HttpEvent, HttpInterceptorFn, HttpRequest } from '@angular/common/http';\nimport { HttpResponse as AngularHttpResponse } from '@angular/common/http';\nimport { ErrorHandler, inject, Injectable } from '@angular/core';\nimport type { Notification, Observable, ObservableNotification } from 'rxjs';\nimport {\n catchError,\n concat,\n concatMap,\n connect,\n defer,\n dematerialize,\n EMPTY,\n from,\n map,\n materialize,\n of,\n ReplaySubject,\n take,\n tap,\n throwError,\n} from 'rxjs';\nimport { isOfflineFallbackError, OfflineNetworkService } from './offline-network.service';\nimport { OFFLINE_MUTATION_PERSISTENCE_ENABLED } from './offline-mutation-persistence.service';\nimport {\n OFFLINE_BYPASS,\n OFFLINE_RESPONSE_HEADER,\n OfflineMutationRequestPolicyRegistry,\n OfflineRequestPolicyRegistry,\n type OfflineReadRequestPlan,\n} from './offline-request-policy';\n\nconst LOCAL_FIRST_MUTATION_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);\n\ntype MaterializedTransport = Notification<HttpEvent<unknown>> & ObservableNotification<HttpEvent<unknown>>;\n\n/** Applies product read and local-first mutation policies while observing real API reachability. */\nexport const offlineInterceptor: HttpInterceptorFn = (request, next) => {\n const network = inject(OfflineNetworkService);\n const transport = () => observeTransport(next(request), network);\n if (request.context.get(OFFLINE_BYPASS)) return transport();\n if (request.method === 'GET') {\n const registry = inject(OfflineRequestPolicyRegistry);\n const fallback = inject(OfflineRequestFallbackService);\n const plan = registry.resolve(request);\n if (!plan) return transport();\n if (plan.readStrategy === 'local-first') {\n return readLocalFirst(request, plan, transport, fallback, inject(ErrorHandler));\n }\n return readNetworkFirst(request, plan, transport, fallback);\n }\n if (LOCAL_FIRST_MUTATION_METHODS.has(request.method)) {\n if (!inject(OFFLINE_MUTATION_PERSISTENCE_ENABLED)()) return transport();\n const plan = inject(OfflineMutationRequestPolicyRegistry).resolve(request);\n if (plan) {\n return defer(() => from(plan.prepare())).pipe(\n map((response) => response.clone({ headers: response.headers.set(OFFLINE_RESPONSE_HEADER, 'optimistic') })),\n );\n }\n }\n return transport();\n};\n\nfunction readNetworkFirst(\n request: HttpRequest<unknown>,\n plan: OfflineReadRequestPlan,\n transport: () => Observable<HttpEvent<unknown>>,\n fallback: OfflineRequestFallbackService,\n): Observable<HttpEvent<unknown>> {\n return defer(transport).pipe(\n catchError((error: unknown) => fallback.handle(request, error, plan) ?? throwError(() => error)),\n concatMap((event) => projectReadResponse(event, plan)),\n );\n}\n\n/**\n * Stale-while-revalidate local-first GET handling.\n *\n * @remarks\n * Starts raw transport and `readLocal()` concurrently at outer subscription,\n * buffers materialized remote notifications until the local attempt settles,\n * emits a projected local response first on hit, then drains/projects the\n * buffered transport. Remote projection begins only after the local decision.\n *\n * Consumers must keep the returned observable subscribed through revalidation;\n * `firstValueFrom` and `take(1)` cancel in-flight transport and suppress\n * further emissions.\n */\nfunction readLocalFirst(\n request: HttpRequest<unknown>,\n plan: OfflineReadRequestPlan,\n transport: () => Observable<HttpEvent<unknown>>,\n fallback: OfflineRequestFallbackService,\n errorHandler: ErrorHandler,\n): Observable<HttpEvent<unknown>> {\n return defer(transport).pipe(\n materialize(),\n connect(\n (bufferedTransport$) =>\n resolveLocalAttempt(plan, errorHandler).pipe(\n concatMap((localResponse) =>\n localResponse\n ? concat(of(localResponse), drainRemoteAfterLocal(bufferedTransport$, plan))\n : drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback),\n ),\n ),\n { connector: () => new ReplaySubject<MaterializedTransport>() },\n ),\n );\n}\n\nfunction resolveLocalAttempt(plan: OfflineReadRequestPlan, errorHandler: ErrorHandler): Observable<HttpEvent<unknown> | null> {\n return defer(() =>\n from(plan.readLocal()).pipe(\n catchError((localError: unknown) => {\n errorHandler.handleError(localError);\n return of(null);\n }),\n ),\n ).pipe(\n concatMap((local) => (local ? tryProjectLocal(local, plan, errorHandler) : of(null))),\n take(1),\n );\n}\n\nfunction tryProjectLocal(\n cached: AngularHttpResponse<unknown>,\n plan: OfflineReadRequestPlan,\n errorHandler: ErrorHandler,\n): Observable<HttpEvent<unknown> | null> {\n return emitTaggedLocalResponse(cached, plan).pipe(\n catchError((error: unknown) => {\n errorHandler.handleError(error);\n return of(null);\n }),\n );\n}\n\nfunction emitTaggedLocalResponse(cached: AngularHttpResponse<unknown>, plan: OfflineReadRequestPlan): Observable<HttpEvent<unknown>> {\n return projectReadResponse(cached.clone({ headers: cached.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }), plan);\n}\n\nfunction drainRemoteAfterLocal(\n bufferedTransport$: Observable<MaterializedTransport>,\n plan: OfflineReadRequestPlan,\n): Observable<HttpEvent<unknown>> {\n return bufferedTransport$.pipe(\n dematerialize(),\n catchError((error: unknown) => (isOfflineFallbackError(error) ? EMPTY : throwError(() => error))),\n concatMap((event) => projectReadResponse(event, plan)),\n );\n}\n\nfunction drainRemoteNetworkFirst(\n bufferedTransport$: Observable<MaterializedTransport>,\n request: HttpRequest<unknown>,\n plan: OfflineReadRequestPlan,\n fallback: OfflineRequestFallbackService,\n): Observable<HttpEvent<unknown>> {\n return bufferedTransport$.pipe(\n dematerialize(),\n catchError((error: unknown) => fallback.handle(request, error, plan) ?? throwError(() => error)),\n concatMap((event) => projectReadResponse(event, plan)),\n );\n}\n\nfunction projectReadResponse(event: HttpEvent<unknown>, plan: OfflineReadRequestPlan): Observable<HttpEvent<unknown>> {\n if (!(event instanceof AngularHttpResponse) || !plan.projectResponse) return of(event);\n const source = event.headers.get(OFFLINE_RESPONSE_HEADER) === 'local' ? 'local' : 'remote';\n return from(plan.projectResponse(event, source)).pipe(\n map((response) =>\n source === 'local' ? response.clone({ headers: response.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }) : response,\n ),\n );\n}\n\nfunction observeTransport(source: Observable<HttpEvent<unknown>>, network: OfflineNetworkService): Observable<HttpEvent<unknown>> {\n return source.pipe(\n tap({\n next: (event) => {\n if (!(event instanceof AngularHttpResponse)) return;\n if (event.headers.get(OFFLINE_RESPONSE_HEADER) === 'local') {\n network.markApiFailure();\n return;\n }\n network.markApiSuccess();\n },\n error: (error: unknown) => {\n if (isOfflineFallbackError(error)) network.markApiFailure();\n },\n }),\n );\n}\n\n/** Resolves transport failures from the local replica without hiding HTTP errors. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineRequestFallbackService {\n readonly #registry = inject(OfflineRequestPolicyRegistry);\n readonly #errorHandler = inject(ErrorHandler);\n\n handle(\n request: HttpRequest<unknown>,\n error: unknown,\n resolvedPlan?: ReturnType<OfflineRequestPolicyRegistry['resolve']>,\n ): Observable<HttpEvent<unknown>> | null {\n if (request.context.get(OFFLINE_BYPASS) || request.method !== 'GET' || !isOfflineFallbackError(error)) return null;\n const plan = resolvedPlan ?? this.#registry.resolve(request);\n if (!plan || plan.kind !== 'read') return null;\n return defer(() => from(plan.readLocal())).pipe(\n catchError((localError: unknown) => {\n this.#errorHandler.handleError(localError);\n return throwError(() => error);\n }),\n concatMap((cached) =>\n cached ? of(cached.clone({ headers: cached.headers.set(OFFLINE_RESPONSE_HEADER, 'local') })) : throwError(() => error),\n ),\n );\n }\n}\n","/** Standard scoped local replica and outbox runtime for offline-capable Ionic applications. */\nexport * from './lib/offline-replica-schema';\nexport * from './lib/offline-identity';\nexport * from './lib/offline-aggregate-intent-projector';\nexport * from './lib/offline-replica-puller';\nexport * from './lib/offline-replica-pull.service';\nexport * from './lib/offline-replica-mutation-coordinator';\nexport * from './lib/offline-command-executor';\nexport * from './lib/offline-command-hooks';\nexport * from './lib/offline-auth-bridge';\nexport * from './lib/offline-coordinator.service';\nexport * from './lib/offline-kit-options';\nexport * from './lib/offline-local-reset';\nexport * from './lib/offline-mutation-envelope';\nexport { OfflineMutationPersistenceDisabledError } from './lib/offline-mutation-admission.service';\nexport {\n OfflineMutationPersistencePendingError,\n OfflineMutationPersistenceRequiresOnlineError,\n OfflineMutationPersistenceService,\n} from './lib/offline-mutation-persistence.service';\nexport * from './lib/offline-network.service';\nexport * from './lib/offline-provider';\nexport * from './lib/offline-repository';\nexport * from './lib/offline-request-policy';\nexport * from './lib/offline-session.service';\nexport * from './lib/offline-storage';\nexport * from './lib/offline-sync.service';\nexport * from './lib/offline.interceptor';\nexport * from './lib/sqlite-offline-repository';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":["isPlainObject","compareOfflineCommands","map","AngularHttpResponse"],"mappings":";;;;;;;;;;;AAmBA,MAAM,kCAAkC,GAAG,IAAI;AA6J/C,MAAM,kBAAkB,GAAG,mBAAmB;AAC9C,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC;IACpC,UAAU;IACV,kBAAkB;IAClB,mBAAmB;IACnB,WAAW;IACX,yBAAyB;IACzB,+BAA+B;IAC/B,qBAAqB;IACrB,qBAAqB;AACtB,CAAA,CAAC;AAEF;;;;;;AAMG;SACa,mBAAmB,GAAA;IACjC,OAAO,SAAS,yBAAyB,CAEvC,UAA4D,EAAA;AAC5D,QAAA,OAAO,+BAA+B,CAAU;YAC9C,KAAK,EAAE,UAAU,CAAC,KAAK;YACvB,SAAS,EAAE,UAAU,CAAC,SAAS;YAC/B,KAAK,EAAE,UAAU,CAAC,KAAK;YACvB,QAAQ,EA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B,6BAA6B,EAAA,UAAA,EAAA,CAAA;kBADzC,UAAU;mBAAC,EAAE,UAAU,EAAE,MAAM,EAAE;;;AClMlC;;ACAA;;AAEG;;;;"}
|
|
1
|
+
{"version":3,"file":"rdlabo-ionic-angular-kit-offline.mjs","sources":["../../../projects/kit/offline/src/lib/offline-replica-schema.ts","../../../projects/kit/offline/src/lib/offline-identity.ts","../../../projects/kit/offline/src/lib/offline-aggregate-intent-projector.ts","../../../projects/kit/offline/src/lib/offline-replica-puller.ts","../../../projects/kit/offline/src/lib/offline-command-hooks.ts","../../../projects/kit/offline/src/lib/offline-kit-options.ts","../../../projects/kit/offline/src/lib/offline-command-executor.ts","../../../projects/kit/offline/src/lib/offline-repository-concurrency.ts","../../../projects/kit/offline/src/lib/offline-repository.ts","../../../projects/kit/offline/src/lib/offline-replica-mutation-coordinator.ts","../../../projects/kit/offline/src/lib/offline-replica-pull.service.ts","../../../projects/kit/offline/src/lib/offline-network.service.ts","../../../projects/kit/offline/src/lib/offline-mutation-admission.service.ts","../../../projects/kit/offline/src/lib/offline-sync.service.ts","../../../projects/kit/offline/src/lib/offline-mutation-persistence.service.ts","../../../projects/kit/offline/src/lib/offline-session.service.ts","../../../projects/kit/offline/src/lib/offline-storage.ts","../../../projects/kit/offline/src/lib/offline-coordinator.service.ts","../../../projects/kit/offline/src/lib/offline-auth-bridge.ts","../../../projects/kit/offline/src/lib/offline-community-sqlite-config.ts","../../../projects/kit/offline/src/lib/offline-local-reset.ts","../../../projects/kit/offline/src/lib/offline-mutation-envelope.ts","../../../projects/kit/offline/src/lib/offline-request-policy.ts","../../../projects/kit/offline/src/lib/sqlite-offline-repository.ts","../../../projects/kit/offline/src/lib/offline-provider.ts","../../../projects/kit/offline/src/lib/offline.interceptor.ts","../../../projects/kit/offline/src/public-api.ts","../../../projects/kit/offline/src/rdlabo-ionic-angular-kit-offline.ts"],"sourcesContent":["/** SQLite storage affinity for a replicated entity column. */\nexport type OfflineReplicaSqliteAffinity = 'TEXT' | 'INTEGER' | 'REAL';\n\n/**\n * Logical storage kind for a replicated column, independent of SQLite affinity.\n *\n * For example, {@link booleanColumn} and {@link datetime} both use INTEGER/TEXT affinity\n * but remain distinguishable at runtime through this marker.\n */\nexport type OfflineReplicaStorageKind = 'text' | 'integer' | 'real' | 'booleanColumn' | 'json' | 'datetime';\n\n/** Scope partition persisted on every replica table row. */\nexport type OfflineReplicaEntityScope = 'user' | 'partition';\n\n/** Field projection policy for a source-model property. */\nexport type OfflineReplicaFieldPolicy = 'column' | 'remoteId' | 'ignored';\n\n/** Canonical value types accepted in a composite server-side natural key. */\nexport type OfflineNaturalKeyValue = string | number;\nconst MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES = 1024;\n\n/** Ordered natural-key values keyed by source-model field name. */\nexport type OfflineNaturalKey = Readonly<Record<string, OfflineNaturalKeyValue>>;\n\n/** Server-assigned remote identifier for a generated-identity entity. */\nexport type OfflineGeneratedRemoteId = number | string;\n\n/** Remote row identity. Exactly one variant is valid for a replicated entity. */\nexport type OfflineReplicaRemoteIdentity =\n | { readonly remoteId: OfflineGeneratedRemoteId; readonly naturalKey?: never }\n | { readonly remoteId?: never; readonly naturalKey: OfflineNaturalKey };\n\n/** Runtime identity policy materialized into an entity schema. */\nexport type OfflineReplicaIdentityDescriptor =\n | { readonly kind: 'localOnly'; readonly sourceKeys: readonly [] }\n | { readonly kind: 'generated'; readonly sourceKeys: readonly [string]; readonly affinity: OfflineReplicaSqliteAffinity }\n | { readonly kind: 'naturalKey'; readonly sourceKeys: readonly string[] };\n\n/** Runtime descriptor for one mapped source property. */\nexport interface OfflineReplicaFieldDescriptor {\n /** Source-model property name from the select shape. */\n readonly sourceKey: string;\n /** How the property is projected into SQLite. */\n readonly policy: OfflineReplicaFieldPolicy;\n /** Physical SQLite column name, or null when {@link policy} is `ignored`. */\n readonly sqliteColumnName: string | null;\n /** SQLite affinity for column policies, otherwise null. */\n readonly affinity: OfflineReplicaSqliteAffinity | null;\n /** Logical storage kind for column policies, otherwise null. */\n readonly storageKind: OfflineReplicaStorageKind | null;\n /** Whether the SQLite column accepts NULL. */\n readonly nullable: boolean;\n /** Human-readable reason when {@link policy} is `ignored`. */\n readonly ignoredReason: string | null;\n}\n\n/** Materialized replica entity schema used to create and fingerprint SQLite tables. */\nexport interface OfflineReplicaEntitySchema<TSelect extends Record<string, unknown>> {\n /** Validated SQLite table name. */\n readonly tableName: string;\n /** Stable source key used by sync and repository layers. */\n readonly sourceKey: string;\n /** Whether rows are partitioned by user only or user plus scope partition. */\n readonly scope: OfflineReplicaEntityScope;\n /** Remote identity policy used by repository and pull reconciliation. */\n readonly identity: OfflineReplicaIdentityDescriptor;\n /** Ordered field descriptors derived from the DSL definition. */\n readonly fields: readonly OfflineReplicaFieldDescriptor[];\n /** Deterministic DDL statements for the replica table and indexes. */\n readonly createTableSql: readonly string[];\n /** Canonical string input for schema fingerprinting; hashing is left to callers. */\n readonly schemaFingerprintInput: string;\n /** Phantom marker tying the schema to its select shape. */\n readonly __select?: TSelect;\n}\n\ndeclare const replicaNullableBrand: unique symbol;\n\n/** Phantom nullability brand carried by column builders. */\ninterface ReplicaNullableBrand {\n readonly [replicaNullableBrand]: 'nullable' | 'required';\n}\n\n/** Column builder definition with compile-time nullability tracking. */\nexport interface OfflineReplicaColumnDef<\n TValue = unknown,\n TNullable extends ReplicaNullableBrand = { readonly [replicaNullableBrand]: 'required' },\n> {\n readonly kind: 'column';\n readonly affinity: OfflineReplicaSqliteAffinity;\n readonly storageKind: OfflineReplicaStorageKind;\n readonly columnName?: string;\n readonly nullable?: boolean;\n readonly __types?: { readonly value: TValue; readonly nullable: TNullable[typeof replicaNullableBrand] };\n}\n\n/** Builder marking a source property as the server-assigned generated identifier. */\nexport interface OfflineReplicaRemoteIdDef<TAffinity extends OfflineReplicaSqliteAffinity = OfflineReplicaSqliteAffinity> {\n readonly kind: 'remoteId';\n readonly affinity: TAffinity;\n readonly __types?: TAffinity extends 'INTEGER' ? { readonly value: number } : { readonly value: string };\n}\n\n/** Builder excluding a source property from SQLite projection. */\nexport interface OfflineReplicaIgnoredDef {\n readonly kind: 'ignored';\n readonly reason: string;\n}\n\n/** Builder selecting non-null source columns as a composite remote identity. */\nexport interface OfflineReplicaNaturalKeyDef<TKey extends string = string> {\n readonly kind: 'naturalKey';\n readonly sourceKeys: readonly TKey[];\n}\n\n/** Explicit identity for a projection that is never synchronized to a remote row. */\nexport interface OfflineReplicaLocalOnlyDef {\n readonly kind: 'localOnly';\n}\n\ntype OfflineReplicaFieldDef = OfflineReplicaColumnDef | OfflineReplicaRemoteIdDef | OfflineReplicaIgnoredDef;\n\ntype StripNullish<T> = Exclude<T, null | undefined>;\n\ntype NormalizeReplicaColumnValue<T> = T extends string\n ? string\n : T extends number\n ? number\n : T extends boolean\n ? boolean\n : T extends Date\n ? string | Date\n : T;\n\ntype StrictNullChecksEnabled = undefined extends null ? false : true;\n\ntype ReplicaColumnNullabilityForSelect<T> = StrictNullChecksEnabled extends true\n ? null extends T\n ? ReplicaNullableBrand & { readonly [replicaNullableBrand]: 'nullable' }\n : undefined extends T\n ? ReplicaNullableBrand & { readonly [replicaNullableBrand]: 'nullable' }\n : ReplicaNullableBrand & { readonly [replicaNullableBrand]: 'required' }\n : ReplicaNullableBrand;\n\ntype OfflineReplicaColumnDefForValue<T> = OfflineReplicaColumnDef<\n NormalizeReplicaColumnValue<StripNullish<T>>,\n ReplicaColumnNullabilityForSelect<T>\n>;\n\ntype OfflineReplicaRemoteIdDefForValue<T> =\n StripNullish<T> extends number\n ? OfflineReplicaRemoteIdDef<'INTEGER'>\n : StripNullish<T> extends string\n ? OfflineReplicaRemoteIdDef<'TEXT'>\n : never;\n\ntype OfflineReplicaFieldDefForKey<TSelect extends Record<string, unknown>, K extends keyof TSelect> =\n | OfflineReplicaRemoteIdDefForValue<TSelect[K]>\n | OfflineReplicaIgnoredDef\n | OfflineReplicaColumnDefForValue<TSelect[K]>;\n\ntype ExactSelectKeys<TSelect extends Record<string, unknown>, TFields> =\n Exclude<keyof TFields, keyof TSelect> extends never ? (Exclude<keyof TSelect, keyof TFields> extends never ? TFields : never) : never;\n\n/** Configuration accepted by {@link defineReplicaEntity}. */\nexport interface OfflineReplicaEntityDefinition<\n TSelect extends Record<string, unknown>,\n TFields extends { readonly [K in keyof TSelect]: OfflineReplicaFieldDefForKey<TSelect, K> },\n> {\n readonly table: string;\n readonly sourceKey: string;\n readonly scope: OfflineReplicaEntityScope;\n readonly identity?: OfflineReplicaNaturalKeyDef<Extract<keyof TSelect, string>> | OfflineReplicaLocalOnlyDef;\n readonly fields: ExactSelectKeys<TSelect, TFields> & TFields;\n}\n\nconst IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/;\nconst RESERVED_COLUMN_NAMES = new Set([\n 'local_id',\n '_offline_user_id',\n '_offline_scope_id',\n 'server_id',\n '_offline_confirmed_json',\n '_offline_server_revision_json',\n '_offline_sync_state',\n '_offline_fetched_at',\n]);\n\n/**\n * Begins a type-safe replica entity schema definition for the given select shape.\n *\n * Every key in `TSelect` must appear exactly once in `fields`, and column nullability\n * must match the select property nullability. An entity may map at most one field with\n * {@link generatedId}; omit it for local-only projections that have no remote row identity.\n */\nexport function defineReplicaEntity<TSelect extends Record<string, unknown>>() {\n return function defineReplicaEntityConfig<\n const TFields extends { readonly [K in keyof TSelect]: OfflineReplicaFieldDefForKey<TSelect, K> },\n >(definition: OfflineReplicaEntityDefinition<TSelect, TFields>): OfflineReplicaEntitySchema<TSelect> {\n return buildOfflineReplicaEntitySchema<TSelect>({\n table: definition.table,\n sourceKey: definition.sourceKey,\n scope: definition.scope,\n identity: definition.identity,\n fields: definition.fields as Record<string, OfflineReplicaFieldDef>,\n });\n };\n}\n\nfunction requiredColumn<TValue>(\n affinity: OfflineReplicaSqliteAffinity,\n storageKind: OfflineReplicaStorageKind,\n): OfflineReplicaColumnDef<TValue> {\n return { kind: 'column', affinity, storageKind, nullable: false };\n}\n\n/** Maps a non-null string source property to a TEXT column. */\nexport function text(): OfflineReplicaColumnDef<string> {\n return requiredColumn<string>('TEXT', 'text');\n}\n\n/** Maps a non-null integer source property to an INTEGER column. */\nexport function integer(): OfflineReplicaColumnDef<number> {\n return requiredColumn<number>('INTEGER', 'integer');\n}\n\n/** Maps a non-null floating-point source property to a REAL column. */\nexport function real(): OfflineReplicaColumnDef<number> {\n return requiredColumn<number>('REAL', 'real');\n}\n\n/** Maps a non-null boolean source property to an INTEGER column. */\nexport function booleanColumn(): OfflineReplicaColumnDef<boolean> {\n return requiredColumn<boolean>('INTEGER', 'booleanColumn');\n}\n\n/** Maps a non-null JSON-serializable source property to a TEXT column. */\nexport function json<T>(): OfflineReplicaColumnDef<T> {\n return requiredColumn<T>('TEXT', 'json');\n}\n\n/** Maps a non-null datetime source property to a canonical ISO-8601 TEXT column. */\nexport function datetime(): OfflineReplicaColumnDef<string | Date> {\n return requiredColumn<string | Date>('TEXT', 'datetime');\n}\n\n/** Marks a column builder as nullable for nullable select properties. */\nexport function nullable<TValue>(\n column: OfflineReplicaColumnDef<TValue, { readonly [replicaNullableBrand]: 'required' }>,\n): OfflineReplicaColumnDef<TValue, { readonly [replicaNullableBrand]: 'nullable' }> {\n return {\n kind: 'column',\n affinity: column.affinity,\n storageKind: column.storageKind,\n nullable: true,\n ...(column.columnName !== undefined ? { columnName: column.columnName } : {}),\n };\n}\n\n/** Maps a source property to the nullable generated remote-id column. */\nexport function generatedId(kind: 'integer'): OfflineReplicaRemoteIdDef<'INTEGER'>;\nexport function generatedId(kind: 'text'): OfflineReplicaRemoteIdDef<'TEXT'>;\nexport function generatedId(kind: 'integer' | 'text'): OfflineReplicaRemoteIdDef {\n return { kind: 'remoteId', affinity: kind === 'integer' ? 'INTEGER' : 'TEXT' };\n}\n\n/** Declares an ordered remote natural key used directly as the scoped SQLite primary key. */\nexport function naturalKey<const TKey extends string>(sourceKeys: readonly TKey[]): OfflineReplicaNaturalKeyDef<TKey> {\n return { kind: 'naturalKey', sourceKeys };\n}\n\n/** Declares a projection with a local UUID address and no Outbox identity. */\nexport function localOnly(): OfflineReplicaLocalOnlyDef {\n return { kind: 'localOnly' };\n}\n/** Rejects a generated remote id on a local-only or natural-key projection before it reaches platform storage. */\nexport function assertOfflineReplicaGeneratedRemoteId(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n value: OfflineGeneratedRemoteId | null,\n): void {\n if (schema.identity.kind !== 'generated' && value !== null) {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" does not define a generated remote id field.`);\n }\n if (value === null) return;\n assertValidGeneratedRemoteId(schema, value);\n}\n\n/** Extracts and validates an entity's natural key in declared component order. */\nexport function offlineNaturalKeyFromValues(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n values: unknown,\n): OfflineNaturalKey | null {\n if (schema.identity.kind !== 'naturalKey') return null;\n if (!isPlainObject(values)) {\n throw new Error(`Offline replica values for \"${schema.sourceKey}\" must be a plain object.`);\n }\n return Object.fromEntries(\n schema.identity.sourceKeys.map((sourceKey) => {\n const value = values[sourceKey];\n const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKey)!;\n if (\n (field.storageKind === 'text' && typeof value !== 'string') ||\n (field.storageKind === 'integer' && (typeof value !== 'number' || !Number.isSafeInteger(value) || !Number.isFinite(value)))\n ) {\n throw new Error(`Offline replica naturalKey field \"${sourceKey}\" has an invalid value.`);\n }\n if (typeof value === 'string') assertNaturalKeyText(sourceKey, value);\n return [sourceKey, value as OfflineNaturalKeyValue];\n }),\n );\n}\n\n/** Validates a supplied natural key and returns it in schema-declared order. */\nexport function normalizeOfflineNaturalKey(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n naturalKey: OfflineNaturalKey,\n): OfflineNaturalKey {\n if (schema.identity.kind !== 'naturalKey') {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" does not define a naturalKey identity.`);\n }\n if (!isPlainObject(naturalKey)) {\n throw new Error(`Offline replica naturalKey for \"${schema.sourceKey}\" must be a plain object.`);\n }\n const actualKeys = Object.keys(naturalKey);\n if (\n actualKeys.length !== schema.identity.sourceKeys.length ||\n actualKeys.some((key) => !(schema.identity.sourceKeys as readonly string[]).includes(key))\n ) {\n throw new Error(`Offline replica naturalKey for \"${schema.sourceKey}\" must contain exactly its declared fields.`);\n }\n return offlineNaturalKeyFromValues(schema, naturalKey)!;\n}\n\n/** Stable, type-tagged identity key used by web uniqueness and pull collapse. */\nexport function canonicalOfflineRemoteIdentity(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n identity: OfflineReplicaRemoteIdentity,\n): string {\n if (schema.identity.kind === 'generated') {\n if (!('remoteId' in identity) || 'naturalKey' in identity) {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" requires generated remote id identity.`);\n }\n assertValidGeneratedRemoteId(schema, identity.remoteId);\n return typeof identity.remoteId === 'string' ? `remoteId:s:${identity.remoteId}` : `remoteId:n:${identity.remoteId}`;\n }\n if (schema.identity.kind === 'naturalKey') {\n if (!('naturalKey' in identity) || 'remoteId' in identity) {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" requires naturalKey identity.`);\n }\n const key = normalizeOfflineNaturalKey(schema, identity.naturalKey);\n return `naturalKey:${JSON.stringify(\n schema.identity.sourceKeys.map((sourceKey) => {\n const value = key[sourceKey]!;\n return [sourceKey, typeof value === 'number' ? 'n' : 's', value];\n }),\n )}`;\n }\n throw new Error(`Offline replica source \"${schema.sourceKey}\" is local-only.`);\n}\n\n/** Enforces one immutable natural identity across optimistic and confirmed row values. */\nexport function assertOfflineReplicaNaturalKeyBaseline(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n values: unknown,\n confirmedValues: unknown | null,\n): void {\n if (schema.identity.kind !== 'naturalKey' || confirmedValues === null) return;\n const current = canonicalOfflineRemoteIdentity(schema, { naturalKey: offlineNaturalKeyFromValues(schema, values)! });\n const confirmed = canonicalOfflineRemoteIdentity(schema, {\n naturalKey: offlineNaturalKeyFromValues(schema, confirmedValues)!,\n });\n if (current !== confirmed) {\n throw new Error(`Offline replica confirmedValues naturalKey must match values for \"${schema.sourceKey}\".`);\n }\n}\n\nfunction assertValidGeneratedRemoteId(schema: OfflineReplicaEntitySchema<Record<string, unknown>>, value: OfflineGeneratedRemoteId): void {\n if (schema.identity.kind !== 'generated') {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" does not define a generated remote id field.`);\n }\n if (schema.identity.affinity === 'INTEGER') {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {\n throw new Error('Offline replica generated remote id must be a positive integer.');\n }\n return;\n }\n if (typeof value !== 'string' || value.length === 0) {\n throw new Error('Offline replica generated remote id must be a non-empty string.');\n }\n assertNaturalKeyText('remoteId', value);\n}\n\nfunction assertNaturalKeyText(sourceKey: string, value: string): void {\n if (value.includes('\\0')) {\n throw new Error(`Offline replica naturalKey field \"${sourceKey}\" must not contain NUL.`);\n }\n if (/[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(^|[^\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/u.test(value)) {\n throw new Error(`Offline replica naturalKey field \"${sourceKey}\" must contain well-formed Unicode.`);\n }\n if (new TextEncoder().encode(value).byteLength > MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES) {\n throw new Error(`Offline replica naturalKey field \"${sourceKey}\" must not exceed ${MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES} UTF-8 bytes.`);\n }\n}\n\n/** Excludes a source property from SQLite while retaining it in the select shape. */\nexport function ignored(reason: string): OfflineReplicaIgnoredDef {\n return { kind: 'ignored', reason };\n}\n\nfunction buildOfflineReplicaEntitySchema<TSelect extends Record<string, unknown>>(definition: {\n readonly table: string;\n readonly sourceKey: string;\n readonly scope: OfflineReplicaEntityScope;\n readonly identity?: OfflineReplicaNaturalKeyDef | OfflineReplicaLocalOnlyDef;\n readonly fields: Record<string, OfflineReplicaFieldDef>;\n}): OfflineReplicaEntitySchema<TSelect> {\n validateIdentifier(definition.table, 'table');\n validateIdentifier(definition.sourceKey, 'source key');\n\n const sourceKeys = Object.keys(definition.fields).sort();\n const remoteIdCount = sourceKeys.filter((sourceKey) => definition.fields[sourceKey]?.kind === 'remoteId').length;\n if (remoteIdCount > 1) throw new Error('Replica entity must define at most one remoteId field.');\n const fields: OfflineReplicaFieldDescriptor[] = sourceKeys.map((sourceKey) => {\n const fieldDef = definition.fields[sourceKey as keyof TSelect] as OfflineReplicaFieldDef;\n return materializeFieldDescriptor(sourceKey, fieldDef);\n });\n const identity = materializeIdentity(definition.identity, fields);\n\n const createTableSql = buildCreateTableSql(definition.table, definition.scope, fields, identity);\n const schemaFingerprintInput = buildSchemaFingerprintInput(definition.table, definition.sourceKey, definition.scope, fields, identity);\n\n return {\n tableName: definition.table,\n sourceKey: definition.sourceKey,\n scope: definition.scope,\n identity,\n fields,\n createTableSql,\n schemaFingerprintInput,\n };\n}\n\nfunction materializeIdentity(\n definition: OfflineReplicaNaturalKeyDef | OfflineReplicaLocalOnlyDef | undefined,\n fields: readonly OfflineReplicaFieldDescriptor[],\n): OfflineReplicaIdentityDescriptor {\n const serverField = fields.find((field) => field.policy === 'remoteId');\n if (definition && serverField) throw new Error('Replica entity cannot combine a generated id field with another identity.');\n if (serverField) return { kind: 'generated', sourceKeys: [serverField.sourceKey], affinity: serverField.affinity! };\n if (!definition) throw new Error('Replica entity without a generated id field must declare identity explicitly.');\n if (definition.kind === 'localOnly') return { kind: 'localOnly', sourceKeys: [] };\n if (definition.sourceKeys.length === 0) throw new Error('Replica naturalKey must contain at least one source field.');\n if (new Set(definition.sourceKeys).size !== definition.sourceKeys.length) {\n throw new Error('Replica naturalKey source fields must be unique.');\n }\n for (const sourceKey of definition.sourceKeys) {\n const field = fields.find((candidate) => candidate.sourceKey === sourceKey);\n if (!field) throw new Error(`Replica naturalKey field \"${sourceKey}\" is not defined.`);\n if (field.policy !== 'column' || field.nullable || !['text', 'integer'].includes(field.storageKind ?? '')) {\n throw new Error(`Replica naturalKey field \"${sourceKey}\" must be a required text or integer column.`);\n }\n }\n return { kind: 'naturalKey', sourceKeys: [...definition.sourceKeys] };\n}\n\nfunction materializeFieldDescriptor(sourceKey: string, fieldDef: OfflineReplicaFieldDef): OfflineReplicaFieldDescriptor {\n if (fieldDef.kind === 'ignored') {\n if (!fieldDef.reason.trim()) throw new Error(`Replica ignored field \"${sourceKey}\" requires a reason.`);\n return {\n sourceKey,\n policy: 'ignored',\n sqliteColumnName: null,\n affinity: null,\n storageKind: null,\n nullable: false,\n ignoredReason: fieldDef.reason,\n };\n }\n\n if (fieldDef.kind === 'remoteId') {\n return {\n sourceKey,\n policy: 'remoteId',\n sqliteColumnName: 'server_id',\n affinity: fieldDef.affinity,\n storageKind: null,\n nullable: true,\n ignoredReason: null,\n };\n }\n\n const sqliteColumnName = fieldDef.columnName ?? toSnakeCase(sourceKey);\n validateIdentifier(sqliteColumnName, 'column');\n if (RESERVED_COLUMN_NAMES.has(sqliteColumnName)) {\n throw new Error(`Replica column \"${sqliteColumnName}\" is reserved.`);\n }\n\n return {\n sourceKey,\n policy: 'column',\n sqliteColumnName,\n affinity: fieldDef.affinity,\n storageKind: fieldDef.storageKind,\n nullable: fieldDef.nullable === true,\n ignoredReason: null,\n };\n}\n\nfunction buildCreateTableSql(\n tableName: string,\n scope: OfflineReplicaEntityScope,\n fields: readonly OfflineReplicaFieldDescriptor[],\n identity: OfflineReplicaIdentityDescriptor,\n): readonly string[] {\n const columnLines = ['_offline_user_id TEXT NOT NULL'];\n if (scope === 'partition') {\n columnLines.push('_offline_scope_id TEXT NOT NULL');\n }\n if (identity.kind === 'generated') {\n columnLines.push('local_id TEXT NOT NULL', `server_id ${identity.affinity}`);\n } else if (identity.kind === 'localOnly') {\n columnLines.push('local_id TEXT NOT NULL');\n }\n columnLines.push(\n '_offline_confirmed_json TEXT',\n '_offline_server_revision_json TEXT',\n '_offline_sync_state TEXT NOT NULL',\n \"_offline_visibility TEXT NOT NULL DEFAULT 'present'\",\n '_offline_fetched_at INTEGER NOT NULL',\n );\n\n for (const field of fields) {\n if (field.policy !== 'column') {\n continue;\n }\n const nullability = field.nullable ? '' : ' NOT NULL';\n columnLines.push(`${field.sqliteColumnName} ${field.affinity}${nullability}`);\n }\n\n const pkColumns = [\n '_offline_user_id',\n ...(scope === 'partition' ? ['_offline_scope_id'] : []),\n ...(identity.kind === 'naturalKey'\n ? identity.sourceKeys.map((sourceKey) => fields.find((field) => field.sourceKey === sourceKey)!.sqliteColumnName!)\n : ['local_id']),\n ];\n\n const statements = [\n `CREATE TABLE IF NOT EXISTS ${tableName} (\\n ${columnLines.join(',\\n ')},\\n PRIMARY KEY (${pkColumns.join(', ')})\\n)`,\n ];\n\n if (identity.kind === 'generated') {\n const indexColumns = scope === 'partition' ? '_offline_user_id, _offline_scope_id, server_id' : '_offline_user_id, server_id';\n statements.push(\n `CREATE UNIQUE INDEX IF NOT EXISTS uq_${tableName}_server_id ON ${tableName} (${indexColumns}) WHERE server_id IS NOT NULL`,\n );\n }\n\n return statements;\n}\n\nfunction buildSchemaFingerprintInput(\n tableName: string,\n sourceKey: string,\n scope: OfflineReplicaEntityScope,\n fields: readonly OfflineReplicaFieldDescriptor[],\n identity: OfflineReplicaIdentityDescriptor,\n): string {\n const fieldParts = fields.map((field) => {\n if (field.policy === 'ignored') {\n return `${field.sourceKey}:ignored:${field.ignoredReason ?? ''}`;\n }\n if (field.policy === 'remoteId') {\n return `${field.sourceKey}:remoteId:server_id:${field.affinity}:nullable`;\n }\n return `${field.sourceKey}:column:${field.sqliteColumnName}:${field.affinity}:${field.storageKind}:${field.nullable ? 'nullable' : 'required'}`;\n });\n\n return [\n `table=${tableName}`,\n `source=${sourceKey}`,\n `scope=${scope}`,\n ...(identity.kind === 'naturalKey'\n ? [`identity=naturalKey:${identity.sourceKeys.join(',')}`, 'identityCodec=v2']\n : identity.kind === 'generated'\n ? [`identity=generated:${identity.sourceKeys[0]}:${identity.affinity}`, 'identityCodec=v2']\n : ['identity=localOnly', 'identityCodec=v2']),\n `fields=${fieldParts.join(';')}`,\n ].join('|');\n}\n\nfunction validateIdentifier(value: string, kind: 'table' | 'column' | 'source key'): void {\n if (!IDENTIFIER_PATTERN.test(value)) {\n throw new Error(`Replica ${kind} \"${value}\" must match ${IDENTIFIER_PATTERN.source}.`);\n }\n}\n\nfunction toSnakeCase(value: string): string {\n return value\n .replace(/([A-Z])/g, '_$1')\n .replace(/^_/, '')\n .toLowerCase();\n}\n\n/**\n * Validates and encodes a source-model row into SQLite-bound column values.\n *\n * Only {@link OfflineReplicaFieldPolicy} `column` fields are emitted, keyed by\n * {@link OfflineReplicaFieldDescriptor.sqliteColumnName} in descriptor order.\n * Source properties mapped as `remoteId` or `ignored` may be present but are not encoded.\n */\nexport function encodeOfflineReplicaValues(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n values: unknown,\n): Readonly<Record<string, string | number | null>> {\n if (!isPlainObject(values)) {\n throw new Error('Replica row values must be a plain object.');\n }\n\n const sourceValues = values;\n const allowedSourceKeys = new Set(schema.fields.map((field) => field.sourceKey));\n\n for (const sourceKey of Object.keys(sourceValues)) {\n if (!allowedSourceKeys.has(sourceKey)) {\n throw new Error(`Replica row contains unknown source key \"${sourceKey}\".`);\n }\n }\n\n const encoded: Record<string, string | number | null> = {};\n\n for (const field of schema.fields) {\n if (field.policy !== 'column') {\n continue;\n }\n\n const sqliteColumnName = field.sqliteColumnName;\n if (sqliteColumnName === null) {\n continue;\n }\n\n if (!Object.prototype.hasOwnProperty.call(sourceValues, field.sourceKey)) {\n throw new Error(`Replica row is missing required source key \"${field.sourceKey}\".`);\n }\n\n const rawValue = sourceValues[field.sourceKey];\n if (rawValue === null) {\n if (!field.nullable) {\n throw new Error(`Replica row source key \"${field.sourceKey}\" must not be null.`);\n }\n encoded[sqliteColumnName] = null;\n continue;\n }\n\n if (rawValue === undefined) {\n throw new Error(`Replica row source key \"${field.sourceKey}\" must not be undefined.`);\n }\n\n encoded[sqliteColumnName] = encodeReplicaColumnValue(field, rawValue);\n }\n\n return encoded;\n}\n\n/**\n * Validates and decodes SQLite column values into a source-model row.\n *\n * Only {@link OfflineReplicaFieldPolicy} `column` fields are emitted, keyed by\n * {@link OfflineReplicaFieldDescriptor.sourceKey} in descriptor order.\n * Physical columns such as `server_id`, sync metadata, and scope keys may be\n * present in `row` but are not decoded.\n */\nexport function decodeOfflineReplicaValues(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n row: unknown,\n): Readonly<Record<string, unknown>> {\n if (!isPlainObject(row)) {\n throw new Error('Replica SQLite row must be a plain object.');\n }\n\n const decoded: Record<string, unknown> = {};\n\n for (const field of schema.fields) {\n if (field.policy !== 'column') {\n continue;\n }\n\n const sqliteColumnName = field.sqliteColumnName;\n if (sqliteColumnName === null) {\n continue;\n }\n\n if (!Object.prototype.hasOwnProperty.call(row, sqliteColumnName)) {\n throw new Error(`Replica SQLite row is missing required column \"${sqliteColumnName}\".`);\n }\n\n const rawValue = row[sqliteColumnName];\n if (rawValue === null) {\n if (!field.nullable) {\n throw new Error(`Replica SQLite column \"${sqliteColumnName}\" must not be null.`);\n }\n decoded[field.sourceKey] = null;\n continue;\n }\n\n if (rawValue === undefined) {\n throw new Error(`Replica SQLite column \"${sqliteColumnName}\" must not be undefined.`);\n }\n\n decoded[field.sourceKey] = decodeReplicaColumnValue(field, rawValue);\n }\n\n return decoded;\n}\n\n/**\n * Validates a source-model row and returns the canonical domain projection persisted by every repository.\n *\n * Fields mapped as `remoteId` or `ignored` are intentionally omitted. This keeps web and native row shapes\n * identical; the server identifier remains available through the replica row's dedicated `remoteId` field.\n */\nexport function projectOfflineReplicaValues(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n values: unknown,\n): Readonly<Record<string, unknown>> {\n return decodeOfflineReplicaValues(schema, encodeOfflineReplicaValues(schema, values));\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction encodeReplicaColumnValue(field: OfflineReplicaFieldDescriptor, value: unknown): string | number {\n switch (field.storageKind) {\n case 'text':\n return encodeReplicaTextValue(field.sourceKey, value);\n case 'integer':\n return encodeReplicaIntegerValue(field.sourceKey, value);\n case 'real':\n return encodeReplicaRealValue(field.sourceKey, value);\n case 'booleanColumn':\n return encodeReplicaBooleanValue(field.sourceKey, value);\n case 'json':\n return encodeReplicaJsonValue(field.sourceKey, value);\n case 'datetime':\n return encodeReplicaDatetimeValue(field.sourceKey, value);\n default:\n throw new Error(`Replica row source key \"${field.sourceKey}\" has no storage kind.`);\n }\n}\n\nfunction decodeReplicaColumnValue(field: OfflineReplicaFieldDescriptor, value: unknown): unknown {\n switch (field.storageKind) {\n case 'text':\n return decodeReplicaTextValue(field.sourceKey, value);\n case 'integer':\n return decodeReplicaIntegerValue(field.sourceKey, value);\n case 'real':\n return decodeReplicaRealValue(field.sourceKey, value);\n case 'booleanColumn':\n return decodeReplicaBooleanValue(field.sourceKey, value);\n case 'json':\n return decodeReplicaJsonValue(field.sourceKey, value);\n case 'datetime':\n return decodeReplicaDatetimeValue(field.sourceKey, value);\n default:\n throw new Error(`Replica row source key \"${field.sourceKey}\" has no storage kind.`);\n }\n}\n\nfunction encodeReplicaTextValue(sourceKey: string, value: unknown): string {\n if (typeof value !== 'string') {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a string.`);\n }\n return value;\n}\n\nfunction encodeReplicaIntegerValue(sourceKey: string, value: unknown): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isSafeInteger(value)) {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a finite safe integer.`);\n }\n return value;\n}\n\nfunction encodeReplicaRealValue(sourceKey: string, value: unknown): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a finite number.`);\n }\n return value;\n}\n\nfunction encodeReplicaBooleanValue(sourceKey: string, value: unknown): 0 | 1 {\n if (typeof value !== 'boolean') {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a boolean.`);\n }\n return value ? 1 : 0;\n}\n\nfunction encodeReplicaJsonValue(sourceKey: string, value: unknown): string {\n assertJsonSerializable(sourceKey, value);\n return JSON.stringify(value);\n}\n\nfunction encodeReplicaDatetimeValue(sourceKey: string, value: unknown): string {\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a valid Date.`);\n }\n return value.toISOString();\n }\n\n if (typeof value === 'string') {\n return value;\n }\n\n throw new Error(`Replica row source key \"${sourceKey}\" must be a Date or string.`);\n}\n\nfunction decodeReplicaTextValue(sourceKey: string, value: unknown): string {\n if (typeof value !== 'string') {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a string.`);\n }\n return value;\n}\n\nfunction decodeReplicaIntegerValue(sourceKey: string, value: unknown): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isSafeInteger(value)) {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a finite safe integer.`);\n }\n return value;\n}\n\nfunction decodeReplicaRealValue(sourceKey: string, value: unknown): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a finite number.`);\n }\n return value;\n}\n\nfunction decodeReplicaBooleanValue(sourceKey: string, value: unknown): boolean {\n if (value !== 0 && value !== 1) {\n throw new Error(`Replica row source key \"${sourceKey}\" must be boolean integer 0 or 1.`);\n }\n return value === 1;\n}\n\nfunction decodeReplicaJsonValue(sourceKey: string, value: unknown): unknown {\n if (typeof value !== 'string') {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a JSON string.`);\n }\n\n try {\n return JSON.parse(value);\n } catch {\n throw new Error(`Replica row source key \"${sourceKey}\" must be valid JSON.`);\n }\n}\n\nfunction decodeReplicaDatetimeValue(sourceKey: string, value: unknown): string {\n if (typeof value !== 'string') {\n throw new Error(`Replica row source key \"${sourceKey}\" must be a string.`);\n }\n return value;\n}\n\nfunction assertJsonSerializable(sourceKey: string, value: unknown, seen = new WeakSet<object>()): void {\n if (value === null || typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {\n return;\n }\n\n if (typeof value === 'undefined') {\n throw new Error(`Replica row source key \"${sourceKey}\" must be JSON-serializable without undefined.`);\n }\n\n if (typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint') {\n throw new Error(`Replica row source key \"${sourceKey}\" must be JSON-serializable without functions.`);\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n assertJsonSerializable(sourceKey, item, seen);\n }\n return;\n }\n\n if (typeof value === 'object') {\n if (seen.has(value)) {\n throw new Error(`Replica row source key \"${sourceKey}\" must be JSON-serializable without cycles.`);\n }\n seen.add(value);\n for (const key of Object.keys(value)) {\n assertJsonSerializable(sourceKey, (value as Record<string, unknown>)[key], seen);\n }\n }\n}\n\n/** Domain payload transformed during web replica schema migration. Identity and sync metadata stay outside this shape. */\nexport interface OfflineReplicaWebMigrationRow {\n readonly sourceKey: string;\n readonly values: Readonly<Record<string, unknown>>;\n readonly confirmedValues: Readonly<Record<string, unknown>> | null;\n}\n\n/** Result of {@link OfflineReplicaMigration.migrateWebRow}; `null` deletes the stored row. */\nexport type OfflineReplicaWebMigrationResult = OfflineReplicaWebMigrationRow | null;\n\n/** Transforms one replica row's domain projection during a web schema migration step. */\nexport type OfflineReplicaWebMigrationCallback = (\n row: OfflineReplicaWebMigrationRow,\n) => OfflineReplicaWebMigrationResult | Promise<OfflineReplicaWebMigrationResult>;\n\n/** One explicit schema-version step applied during offline SQLite and web replica migrations. */\nexport interface OfflineReplicaMigration {\n /** Source schema version; the migration advances to {@link fromVersion} + 1. */\n readonly fromVersion: number;\n /** Non-empty DDL/DML statements executed in order on native SQLite for this step. Web ignores these. */\n readonly statements: readonly string[];\n /**\n * Transforms one row's domain projection for web storage during this step.\n * The callback receives only {@link OfflineReplicaWebMigrationRow}; it must not read or mutate\n * `localId`, `remoteId`, scope, revision, or `syncState`. Return `null` to delete the row.\n */\n readonly migrateWebRow: OfflineReplicaWebMigrationCallback;\n}\n\n/** Versioned product replica schema bundle with entities and migration path. */\nexport interface OfflineReplicaSchemaBundle {\n /** Current bundle schema version. */\n readonly version: number;\n /** Entity schemas sorted by {@link OfflineReplicaEntitySchema.sourceKey}. */\n readonly entities: readonly OfflineReplicaEntitySchema<Record<string, unknown>>[];\n /** Migrations sorted by {@link OfflineReplicaMigration.fromVersion}. */\n readonly migrations: readonly OfflineReplicaMigration[];\n /** Canonical fingerprint input spanning version and every entity fingerprint. */\n readonly schemaFingerprintInput: string;\n}\n\n/** Input accepted by {@link defineOfflineReplicaSchema}. */\nexport interface OfflineReplicaSchemaDefinition {\n /** Current bundle schema version. */\n readonly version: number;\n /** Entity schemas for the bundle version. */\n readonly entities: readonly OfflineReplicaEntitySchema<Record<string, unknown>>[];\n /** Ordered one-step migrations from older bundle versions. */\n readonly migrations: readonly OfflineReplicaMigration[];\n}\n\n/**\n * Validates and materializes a versioned offline replica schema bundle.\n *\n * Entity `tableName` and `sourceKey` values must each be unique within the bundle.\n * Migrations must advance one version at a time without duplicates or gaps.\n */\nexport function defineOfflineReplicaSchema(definition: OfflineReplicaSchemaDefinition): OfflineReplicaSchemaBundle {\n assertPositiveInteger(definition.version, 'schema version');\n\n const entities = [...definition.entities].sort((left, right) =>\n left.sourceKey < right.sourceKey ? -1 : left.sourceKey > right.sourceKey ? 1 : 0,\n );\n const tableNames = new Set<string>();\n const sourceKeys = new Set<string>();\n for (const entity of entities) {\n if (tableNames.has(entity.tableName)) {\n throw new Error(`Duplicate replica entity table \"${entity.tableName}\".`);\n }\n tableNames.add(entity.tableName);\n\n if (sourceKeys.has(entity.sourceKey)) {\n throw new Error(`Duplicate replica entity source key \"${entity.sourceKey}\".`);\n }\n sourceKeys.add(entity.sourceKey);\n }\n\n const migrations = normalizeOfflineReplicaMigrations(definition.migrations, definition.version);\n const schemaFingerprintInput = buildBundleSchemaFingerprintInput(definition.version, entities, migrations);\n\n return {\n version: definition.version,\n entities,\n migrations,\n schemaFingerprintInput,\n };\n}\n\n/**\n * Computes a lowercase SHA-256 hex digest of {@link OfflineReplicaSchemaBundle.schemaFingerprintInput}.\n */\nexport async function sha256OfflineReplicaSchema(bundle: OfflineReplicaSchemaBundle): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(bundle.schemaFingerprintInput));\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\nfunction normalizeOfflineReplicaMigrations(\n migrations: readonly OfflineReplicaMigration[],\n bundleVersion: number,\n): readonly OfflineReplicaMigration[] {\n const sorted = [...migrations].sort((left, right) => left.fromVersion - right.fromVersion);\n const seenFromVersions = new Set<number>();\n\n for (const migration of sorted) {\n assertPositiveInteger(migration.fromVersion, 'migration fromVersion');\n\n const targetVersion = migration.fromVersion + 1;\n if (targetVersion > bundleVersion) {\n throw new Error(\n `Replica migration from version ${migration.fromVersion} targets version ${targetVersion}, which exceeds bundle version ${bundleVersion}.`,\n );\n }\n\n if (seenFromVersions.has(migration.fromVersion)) {\n throw new Error(`Duplicate replica migration from version ${migration.fromVersion}.`);\n }\n seenFromVersions.add(migration.fromVersion);\n\n if (typeof migration.migrateWebRow !== 'function') {\n throw new Error(`Replica migration from version ${migration.fromVersion} requires migrateWebRow.`);\n }\n\n if (migration.statements.length === 0) {\n throw new Error(`Replica migration from version ${migration.fromVersion} requires at least one SQL statement.`);\n }\n\n for (const [index, statement] of migration.statements.entries()) {\n if (!statement.trim()) {\n throw new Error(`Replica migration from version ${migration.fromVersion} statement ${index + 1} must not be empty.`);\n }\n }\n }\n\n for (let index = 1; index < sorted.length; index++) {\n const previous = sorted[index - 1]!;\n const current = sorted[index]!;\n if (current.fromVersion !== previous.fromVersion + 1) {\n throw new Error(\n `Replica migrations must advance consecutive schema versions; expected fromVersion ${previous.fromVersion + 1}, received ${current.fromVersion}.`,\n );\n }\n }\n\n if (sorted.length > 0 && sorted[0]!.fromVersion !== 1) {\n throw new Error(\n `Replica migrations must advance consecutive schema versions; expected fromVersion 1, received ${sorted[0]!.fromVersion}.`,\n );\n }\n\n const finalRequiredFromVersion = bundleVersion - 1;\n if (finalRequiredFromVersion > 0 && sorted.at(-1)?.fromVersion !== finalRequiredFromVersion) {\n const firstMissingVersion = (sorted.at(-1)?.fromVersion ?? 0) + 1;\n throw new Error(\n `Missing offline replica schema migration from version ${firstMissingVersion} to ${firstMissingVersion + 1}.`,\n );\n }\n\n return sorted;\n}\n\nfunction buildBundleSchemaFingerprintInput(\n version: number,\n entities: readonly OfflineReplicaEntitySchema<Record<string, unknown>>[],\n migrations: readonly OfflineReplicaMigration[],\n): string {\n const entityFingerprints = entities.map((entity) => entity.schemaFingerprintInput).join(';');\n const migrationFingerprints = migrations\n .map((migration) => `from=${migration.fromVersion}|statements=${migration.statements.join('\\n')}`)\n .join(';');\n return `version=${version}|entities=${entityFingerprints}|migrations=${migrationFingerprints}`;\n}\n\nfunction assertPositiveInteger(value: number, label: string): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new Error(`Replica ${label} must be a positive integer.`);\n }\n}\n","import {\n canonicalOfflineRemoteIdentity,\n normalizeOfflineNaturalKey,\n offlineNaturalKeyFromValues,\n type OfflineGeneratedRemoteId,\n type OfflineNaturalKey,\n type OfflineReplicaEntitySchema,\n type OfflineReplicaRemoteIdentity,\n} from './offline-replica-schema';\n\n/** Product-agnostic authenticated principal identifier. */\nexport type OfflinePrincipalId = string | number;\n\n/** Narrows a product DB id without duplicating the numeric identity boundary. */\nexport function requirePositiveOfflineInteger(value: unknown, label = 'Offline id'): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {\n throw new Error(`${label} must be a positive safe integer.`);\n }\n return value;\n}\n\n/** Type-tagged SQLite/web key; numeric 7 and text \"7\" never share a boundary. */\nexport function canonicalOfflinePrincipalId(value: OfflinePrincipalId): string {\n if (typeof value === 'number') {\n if (!Number.isSafeInteger(value) || !Number.isFinite(value)) {\n throw new Error('Offline principal id number must be a finite safe integer.');\n }\n return `n:${value}`;\n }\n if (value.length === 0) throw new Error('Offline principal id string must not be empty.');\n return `s:${JSON.stringify(value)}`;\n}\n\n/** Decodes a principal previously persisted by {@link canonicalOfflinePrincipalId}. */\nexport function parseOfflinePrincipalId(value: string): OfflinePrincipalId {\n if (value.startsWith('n:')) {\n const numberValue = Number(value.slice(2));\n if (!Number.isSafeInteger(numberValue)) throw new Error('Stored offline principal id is invalid.');\n return numberValue;\n }\n if (value.startsWith('s:')) {\n const stringValue: unknown = JSON.parse(value.slice(2));\n if (typeof stringValue !== 'string' || stringValue.length === 0) throw new Error('Stored offline principal id is invalid.');\n return stringValue;\n }\n throw new Error('Stored offline principal id has an unknown codec.');\n}\n\n/** Durable address of a generated or natural-key replica row. */\nexport type OfflineReplicaIdentity =\n | { readonly kind: 'generated'; readonly localId: string; readonly remoteId: OfflineGeneratedRemoteId | null }\n | { readonly kind: 'natural'; readonly naturalKey: OfflineNaturalKey }\n | { readonly kind: 'local'; readonly localId: string };\n\n/** Outbox address. Generated ids are resolved to the latest server id immediately before transport. */\nexport type OfflineCommandIdentity =\n | { readonly kind: 'generated'; readonly localId: string }\n | { readonly kind: 'natural'; readonly naturalKey: OfflineNaturalKey };\n\n/** Stable lookup address for every replica row, including local-only projections. */\nexport type OfflineReplicaAddress = OfflineCommandIdentity | { readonly kind: 'local'; readonly localId: string };\n\n/** Stable storage key for one outbox or replica row identity. */\nexport function canonicalOfflineCommandIdentity(identity: OfflineCommandIdentity): string {\n if (identity.kind === 'generated') {\n assertOfflineLocalId(identity.localId);\n return `generated:${identity.localId}`;\n }\n return `natural:${canonicalOfflineNaturalKeyIdentity(identity.naturalKey)}`;\n}\n\n/** Stable storage key for one materialized replica row identity. */\nexport function canonicalOfflineReplicaIdentity(identity: OfflineReplicaIdentity): string {\n if (identity.kind === 'generated') {\n assertOfflineLocalId(identity.localId);\n return `generated:${identity.localId}`;\n }\n if (identity.kind === 'local') {\n assertOfflineLocalId(identity.localId);\n return `local:${identity.localId}`;\n }\n return `natural:${canonicalOfflineNaturalKeyIdentity(identity.naturalKey)}`;\n}\n\n/** JSON persisted in SQLite/web outbox rows. */\nexport function serializeOfflineCommandIdentity(identity: OfflineCommandIdentity): string {\n canonicalOfflineCommandIdentity(identity);\n return JSON.stringify(identity);\n}\n\n/** Parses durable outbox identity JSON. */\nexport function parseOfflineCommandIdentity(value: unknown): OfflineCommandIdentity {\n if (!isPlainObject(value)) throw new Error('Offline command identity must be a plain object.');\n if (value['kind'] === 'generated') {\n assertOfflineLocalId(value['localId']);\n return { kind: 'generated', localId: value['localId'] };\n }\n if (value['kind'] === 'natural') {\n if (!isPlainObject(value['naturalKey'])) throw new Error('Offline natural command identity requires naturalKey.');\n return { kind: 'natural', naturalKey: value['naturalKey'] as OfflineNaturalKey };\n }\n throw new Error('Offline command identity must be generated or natural.');\n}\n\n/** Builds a generated replica identity. */\nexport function offlineGeneratedReplicaIdentity(localId: string, remoteId: OfflineGeneratedRemoteId | null): OfflineReplicaIdentity {\n assertOfflineLocalId(localId);\n return { kind: 'generated', localId, remoteId };\n}\n\n/** Validates a durable local row id before it can enter either storage backend. */\nexport function assertOfflineLocalId(value: unknown): asserts value is string {\n if (\n typeof value !== 'string' ||\n value.length === 0 ||\n value.includes('\\0') ||\n value !== value.normalize('NFC') ||\n new TextEncoder().encode(value).byteLength > 255\n ) {\n throw new Error('Offline localId must be a non-empty normalized string of at most 255 UTF-8 bytes without NUL.');\n }\n}\n\n/** Builds a natural replica identity from current domain values. */\nexport function offlineNaturalReplicaIdentity(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n values: unknown,\n): OfflineReplicaIdentity {\n return { kind: 'natural', naturalKey: offlineNaturalKeyFromValues(schema, values)! };\n}\n\n/** Converts a materialized replica identity into an outbox address. */\nexport function commandIdentityFromReplicaIdentity(identity: OfflineReplicaIdentity): OfflineCommandIdentity {\n if (identity.kind === 'generated') return { kind: 'generated', localId: identity.localId };\n if (identity.kind === 'local') {\n throw new Error('Local-only replica rows cannot be added to the Outbox.');\n }\n return { kind: 'natural', naturalKey: identity.naturalKey };\n}\n\n/** Converts a materialized row identity into its immutable repository address. */\nexport function replicaAddressFromIdentity(identity: OfflineReplicaIdentity): OfflineReplicaAddress {\n if (identity.kind === 'natural') return { kind: 'natural', naturalKey: identity.naturalKey };\n return { kind: identity.kind, localId: identity.localId };\n}\n\n/** Whether a command identity addresses the given replica row. */\nexport function commandIdentityMatchesReplicaRow(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n row: { readonly identity: OfflineReplicaIdentity },\n commandIdentity: OfflineCommandIdentity,\n): boolean {\n if (commandIdentity.kind === 'generated') {\n return row.identity.kind === 'generated' && row.identity.localId === commandIdentity.localId;\n }\n if (row.identity.kind !== 'natural') return false;\n return (\n canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) ===\n canonicalOfflineRemoteIdentity(schema, { naturalKey: normalizeOfflineNaturalKey(schema, commandIdentity.naturalKey) })\n );\n}\n\n/** Remote identity used by pull reconciliation and uniqueness checks. */\nexport function offlineReplicaRemoteIdentity(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n identity: OfflineReplicaIdentity,\n): OfflineReplicaRemoteIdentity | null {\n if (schema.identity.kind === 'generated') {\n return identity.kind === 'generated' && identity.remoteId !== null ? { remoteId: identity.remoteId } : null;\n }\n if (schema.identity.kind === 'naturalKey') {\n return identity.kind === 'natural' ? { naturalKey: identity.naturalKey } : null;\n }\n return null;\n}\n\nfunction canonicalOfflineNaturalKeyIdentity(naturalKey: OfflineNaturalKey): string {\n return JSON.stringify(\n Object.keys(naturalKey)\n .sort()\n .map((key) => {\n const value = naturalKey[key]!;\n return [key, typeof value === 'number' ? 'n' : 's', value];\n }),\n );\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n","import { InjectionToken } from '@angular/core';\nimport type { OfflineCommand, OfflineReplicaRow, OfflineReplicaRowKey, OfflineReplicaTransaction } from './offline-repository';\n\n/**\n * Authoritative inputs for rematerializing one aggregate from its remaining\n * ordered Outbox chain.\n *\n * `baseRow` is the current replica row for the aggregate, including its latest\n * `confirmedValues`. `localOnlyRows` are the current localOnly projection rows\n * owned by that aggregate. `commands` is the complete remaining FIFO chain\n * after the triggering mutation.\n */\nexport interface OfflineAggregateIntentProjectInput {\n /** Current aggregate base replica row, or `null` when the row is absent. */\n readonly baseRow: OfflineReplicaRow | null;\n /** Current authoritative localOnly projection rows for this aggregate. */\n readonly localOnlyRows: readonly OfflineReplicaRow[];\n /** Complete remaining ordered pending command chain for this aggregate. */\n readonly commands: readonly OfflineCommand[];\n /** Boundary that requested rematerialization. Only pull may return a conflict outcome. */\n readonly trigger?: 'local' | 'pull';\n /** Incoming authoritative revision when `trigger` is `pull`. */\n readonly incomingRevision?: string | number;\n}\n\n/**\n * Fully rematerialized aggregate projection.\n *\n * Kit writes `baseRow` as the sole base mutation (`null` removes the row) and\n * applies only the localOnly put/remove lists. Domain folding belongs here;\n * Kit never interprets command payloads.\n */\nexport interface OfflineAggregateIntentProjection {\n /** Rematerialized base replica row, or `null` to remove the aggregate row. */\n readonly baseRow: OfflineReplicaRow | null;\n /** LocalOnly projection rows to upsert for this aggregate. */\n readonly putLocalOnlyRows?: readonly OfflineReplicaRow[];\n /** LocalOnly projection rows to remove for this aggregate. */\n readonly removeLocalOnlyRows?: readonly OfflineReplicaRowKey[];\n}\n\n/** Product decision that pending intents cannot be replayed onto an incoming authoritative revision. */\nexport interface OfflineAggregateIntentConflict {\n readonly kind: 'conflict';\n readonly reason: string;\n}\n\n/** Result of product-owned aggregate rematerialization. */\nexport type OfflineAggregateIntentProjectResult = OfflineAggregateIntentProjection | OfflineAggregateIntentConflict;\n\n/**\n * Product-owned pure rematerialization of one aggregate.\n *\n * Given the authoritative base row, current localOnly projection rows, and the\n * remaining ordered {@link OfflineCommand} chain, return one fully materialized\n * base row plus localOnly put/remove mutations. The adapter must derive only\n * from confirmed base/localOnly values plus complete FIFO pending intents. It\n * must not perform I/O; Kit supplies already-read replica state and validates\n * scope, schema, identity, and footprints before writing.\n */\nexport interface OfflineAggregateIntentProjector {\n /** Rematerializes one aggregate from authoritative replica state and remaining intents. */\n project(input: OfflineAggregateIntentProjectInput): OfflineAggregateIntentProjectResult;\n}\n\n/** Returns whether the projector rejected replay onto an authoritative pull revision. */\nexport function isOfflineAggregateIntentConflict(result: OfflineAggregateIntentProjectResult): result is OfflineAggregateIntentConflict {\n return 'kind' in result && result.kind === 'conflict';\n}\n\n/** Required product adapter for aggregate rematerialization from remaining Outbox intents. */\nexport const OFFLINE_AGGREGATE_INTENT_PROJECTOR = new InjectionToken<OfflineAggregateIntentProjector>('OFFLINE_AGGREGATE_INTENT_PROJECTOR');\n\n/**\n * Converts a validated aggregate projection into replica put/remove mutations.\n *\n * @param projection - Rematerialized aggregate returned by the product projector.\n * @param baseRow - Current aggregate base row, used when the projection removes it.\n */\nexport function offlineAggregateIntentMutations(\n projection: OfflineAggregateIntentProjection,\n baseRow: OfflineReplicaRow | null,\n): Pick<OfflineReplicaTransaction, 'putRows' | 'removeRows'> {\n const putRows: OfflineReplicaRow[] = [];\n const removeRows: OfflineReplicaRowKey[] = [];\n if (projection.baseRow) putRows.push(projection.baseRow);\n else if (baseRow) {\n removeRows.push({\n userId: baseRow.userId,\n scopeId: baseRow.scopeId,\n sourceKey: baseRow.sourceKey,\n identity: baseRow.identity,\n });\n }\n putRows.push(...(projection.putLocalOnlyRows ?? []));\n removeRows.push(...(projection.removeLocalOnlyRows ?? []));\n return { putRows, removeRows };\n}\n","import { InjectionToken } from '@angular/core';\nimport type { OfflineReplicaRow, OfflineReplicaRowKey, OfflineScope } from './offline-repository';\nimport type { OfflineGeneratedRemoteId, OfflineNaturalKey, OfflineReplicaRemoteIdentity } from './offline-replica-schema';\n\n/** Server pull request for one user or partition-scoped replica. */\nexport interface OfflineReplicaPullRequest {\n scope: OfflineScope;\n cursor: string;\n schemaVersion: number;\n schemaHash: string;\n /**\n * Successfully transported commands that still require an authoritative row acknowledgement.\n * The server must hydrate and authorize each target from primary state and acknowledge it only\n * on the returned reconciliation change; it must never trust this client identity as proof.\n */\n reconciliationTargets: readonly OfflineReplicaReconciliationTarget[];\n}\n\n/** One awaiting-pull command whose canonical state must be hydrated independently of journal retention. */\nexport interface OfflineReplicaReconciliationTarget {\n readonly commandId: string;\n readonly operation: string;\n readonly sourceKey: string;\n readonly identity: OfflineReplicaRemoteIdentity;\n}\n\n/** One server-side replica mutation returned by an explicit pull page. */\nexport interface OfflineReplicaChangeBase {\n sourceKey: string;\n serverRevision: string | number;\n /**\n * Idempotency command ids durably recorded by the server and reflected in this final row state.\n * They may include commands from other clients; the runtime correlates only ids in its local Outbox.\n */\n acknowledgedCommandIds?: readonly string[];\n values: unknown | null;\n deleted: boolean;\n}\n\n/** One server-side mutation with the identity kind declared by its replica schema. */\nexport type OfflineReplicaChange = OfflineReplicaChangeBase & OfflineReplicaRemoteIdentity;\n\n/**\n * Backend wire identity accepted at the HTTP boundary.\n *\n * `serverId` is the database-facing name used by Hono applications. The\n * offline runtime deliberately calls the same value `remoteId`, because the\n * repository is not tied to a particular server database. Normalize exactly\n * once at the transport boundary with {@link normalizeOfflineReplicaPullPage}.\n */\nexport type OfflineReplicaWireIdentity =\n | { readonly serverId: OfflineGeneratedRemoteId }\n | { readonly remoteId: OfflineGeneratedRemoteId }\n | { readonly naturalKey: OfflineNaturalKey };\n\n/** One backend pull mutation before its DB-facing identity is normalized. */\nexport type OfflineReplicaWireChange = OfflineReplicaChangeBase & OfflineReplicaWireIdentity;\n\n/** One explicit replica pull response page from the application backend. */\nexport interface OfflineReplicaPullPage {\n schemaVersion: number;\n schemaHash: string;\n changes: readonly OfflineReplicaChange[];\n nextCursor: string;\n hasMore: boolean;\n /** The server can no longer continue this cursor and requires a confirmed-state snapshot rebuild. */\n rebaselineRequired?: boolean;\n}\n\n/** Product projection derived from one collapsed authoritative pull page. */\nexport interface OfflineReplicaPullProjection {\n putRows?: readonly OfflineReplicaRow[];\n removeRows?: readonly OfflineReplicaRowKey[];\n}\n\n/** Pure product adapter for local-only projections derived from server replica changes. */\nexport interface OfflineReplicaProjector {\n project(input: { scope: OfflineScope; changes: readonly OfflineReplicaChange[] }): Promise<OfflineReplicaPullProjection>;\n}\n\n/** Backend response accepted by the shared pull-page normalizer. */\nexport interface OfflineReplicaWirePullPage {\n schemaVersion: number;\n schemaHash: string;\n changes: readonly OfflineReplicaWireChange[];\n nextCursor: string;\n hasMore: boolean;\n /** The server can no longer continue this cursor and requires a confirmed-state snapshot rebuild. */\n rebaselineRequired?: boolean;\n}\n\n/**\n * Converts a backend DB identity (`serverId`) to the runtime identity\n * (`remoteId`) without allowing product pullers to each reimplement the rule.\n */\nexport function normalizeOfflineReplicaPullPage(page: OfflineReplicaWirePullPage): OfflineReplicaPullPage {\n return {\n ...page,\n changes: page.changes.map((change, index) => {\n if ('naturalKey' in change) return change;\n if ('serverId' in change && 'remoteId' in change) {\n throw new Error(`Offline replica pull page changes[${index}] cannot contain both serverId and remoteId.`);\n }\n if ('serverId' in change) {\n const { serverId, ...rest } = change;\n return { ...rest, remoteId: serverId };\n }\n return change;\n }),\n };\n}\n\n/** Application-provided transport that fetches explicit replica pull pages from the server. */\nexport interface OfflineReplicaPuller {\n pull(request: OfflineReplicaPullRequest): Promise<OfflineReplicaPullPage>;\n}\n\n/** DI token for the application-provided explicit replica pull transport. */\nexport const OFFLINE_REPLICA_PULLER = new InjectionToken<OfflineReplicaPuller>('OFFLINE_REPLICA_PULLER');\n\n/** Optional product adapter for local-only replica projections. */\nexport const OFFLINE_REPLICA_PROJECTOR = new InjectionToken<OfflineReplicaProjector>('OFFLINE_REPLICA_PROJECTOR');\n","import { InjectionToken } from '@angular/core';\nimport type { OfflineCommand } from './offline-repository';\n\n/** Optional product hooks for entity projection and command cleanup. */\nexport interface OfflineCommandHooks {\n entityType(command: Pick<OfflineCommand, 'operation' | 'aggregateType'>): string;\n onCommandRemoved?(command: OfflineCommand): Promise<void>;\n}\n\nexport const DEFAULT_OFFLINE_COMMAND_HOOKS: OfflineCommandHooks = {\n entityType: (command) => command.aggregateType,\n};\n\n/** DI token for optional product-specific synchronization hooks. */\nexport const OFFLINE_COMMAND_HOOKS = new InjectionToken<OfflineCommandHooks>('OFFLINE_COMMAND_HOOKS', {\n providedIn: 'root',\n factory: () => DEFAULT_OFFLINE_COMMAND_HOOKS,\n});\n","import { InjectionToken, type Type } from '@angular/core';\nimport type { OfflineReplicaSchemaBundle } from './offline-replica-schema';\nimport type { OfflineStorageUnavailableError } from './offline-storage';\n\n/** Backpressure limits for durable commands. Pending commands are never evicted automatically. */\nexport interface OfflineOutboxLimits {\n /** Maximum number of commands retained for one user. Defaults to 1,000. */\n maxCommandsPerUser?: number;\n /** Maximum serialized size retained for one user. Defaults to 10 MiB. */\n maxBytesPerUser?: number;\n}\n\n/** Product persistence adapter for the device-local offline mutation preference. */\nexport interface OfflineMutationPersistenceAdapter {\n /** Loads the last durable preference. `null` or `undefined` uses the configured default. */\n loadEnabled(): Promise<boolean | null | undefined>;\n /** Persists a completed enable or disable transition. */\n saveEnabled(enabled: boolean): Promise<void>;\n}\n\n/** Configuration for device-local mutation persistence control. */\nexport interface OfflineMutationPersistenceOptions {\n /** Injectable product adapter for the durable preference store. */\n adapter: Type<OfflineMutationPersistenceAdapter>;\n /** Initial value when no durable preference exists. Defaults to `true`. */\n defaultEnabled?: boolean;\n}\n\n/** Product-independent native offline persistence settings. */\nexport interface OfflineKitOptions {\n /** Runtime transport mode. Defaults to full synchronized replica/outbox behavior. */\n mode?: 'synchronized' | 'readCacheOnly';\n /** Encrypted SQLite database name used on iOS and Android. */\n databaseName: string;\n /** Creates the native database encryption key on first install. Required on iOS and Android. */\n createEncryptionKey?: () => Promise<string>;\n /** Versioned product replica schema applied to native SQLite during initialization. */\n replicaSchema: OfflineReplicaSchemaBundle;\n /**\n * Product wire protocol fingerprint exchanged with the synchronization server.\n *\n * Keep this independent from {@link replicaSchema}: local-only tables and\n * storage migrations must not force a server rollout. When omitted, Kit uses\n * the replica schema fingerprint for backward compatibility.\n */\n wireProtocol?: OfflineWireProtocolFingerprint;\n /** Optional durable Outbox backpressure policy. */\n outboxLimits?: OfflineOutboxLimits;\n /**\n * Optional device-local control for accepting new durable Outbox mutations.\n *\n * Replica reads remain enabled while mutation persistence is disabled. When omitted,\n * Kit preserves the historical always-enabled mutation behavior.\n */\n mutationPersistence?: OfflineMutationPersistenceOptions;\n /**\n * Optional product callback invoked when local storage initialization fails.\n *\n * Providing this callback opts the application into online-only startup degradation:\n * after the callback settles successfully, the app initializer completes with\n * {@link OfflineCoordinatorService.storageState} `unavailable` and session/sync are not started.\n * When omitted, initialization throws {@link OfflineStorageUnavailableError} as before.\n * If the callback throws or rejects, initialization still fails.\n *\n * Kit never deletes Outbox or replica data in response to storage failure. Products may invoke\n * `recoverOfflineLocalReset` only after an explicit destructive reset request.\n */\n onStorageUnavailable?: (error: OfflineStorageUnavailableError) => void | Promise<void>;\n}\n\n/** Exact versioned wire contract exchanged by pull transport. */\nexport interface OfflineWireProtocolFingerprint {\n /** Monotonic product wire protocol version. */\n readonly version: number;\n /** Deterministic fingerprint of the pull/push wire contract. */\n readonly hash: string;\n}\n\n/** DI token for product-independent offline persistence settings. */\nexport const OFFLINE_KIT_OPTIONS = new InjectionToken<OfflineKitOptions>('OFFLINE_KIT_OPTIONS');\n","import { InjectionToken } from '@angular/core';\nimport type { OfflineCommand, OfflineScope } from './offline-repository';\nimport type { OfflineCommandIdentity, OfflinePrincipalId, OfflineReplicaIdentity } from './offline-identity';\nimport type { OfflineGeneratedRemoteId, OfflineNaturalKey } from './offline-replica-schema';\n\n/** Server acknowledgement used to reconcile one optimistic local mutation. */\nexport interface OfflineCommandResult {\n /** Remote id returned by a successful generated-identity mutation. */\n remoteId?: OfflineGeneratedRemoteId;\n serverRevision?: string | number;\n /**\n * Full server-confirmed domain values after applying the mutation.\n *\n * Kit does not treat this as the durable confirmed baseline while the\n * command remains in the Outbox. Authoritative confirmed values come from\n * pull acknowledgement of `commandId`.\n */\n confirmedValues?: unknown;\n /** Removes the local replica row after a confirmed server delete. */\n removeReplica?: boolean;\n /**\n * Releases the deleted row's remote identity while keeping\n * its immutable local id for a queued recreate of the same logical target.\n */\n clearRemoteId?: boolean;\n response?: unknown;\n}\n\n/** Target identity resolved from the local replica immediately before transport. */\nexport type OfflineCommandTarget =\n | { readonly kind: 'generated'; readonly localId: string; readonly remoteId: OfflineGeneratedRemoteId | null }\n | { readonly kind: 'natural'; readonly naturalKey: OfflineNaturalKey };\n\n/** Product adapter that sends commands and projects acknowledgements into entities. */\nexport interface OfflineCommandExecutor {\n /** Sends the command using `command.commandId` as its durable server-side idempotency key. */\n execute(command: OfflineCommand, target: OfflineCommandTarget): Promise<OfflineCommandResult>;\n /**\n * Whether this transport error authoritatively proves that this idempotency\n * key did not commit. Returning true may clear an ambiguity retained from an\n * earlier response-loss attempt and expose normal conflict resolution.\n */\n provesCommandNotCommitted?(error: unknown, command: OfflineCommand): boolean;\n}\n\n/**\n * Returns a command whose only changed field is `baseRevision`.\n *\n * Payload and every other field are copied unchanged. Kit uses this when a\n * newer server revision is known, and passes `null` after a generated remote\n * identity is released.\n */\nexport function offlineCommandWithBaseRevision(command: OfflineCommand, baseRevision: string | number | null): OfflineCommand {\n return { ...command, baseRevision };\n}\n\n/** DI token for the product-specific command transport adapter. */\nexport const OFFLINE_COMMAND_EXECUTOR = new InjectionToken<OfflineCommandExecutor>('OFFLINE_COMMAND_EXECUTOR');\n\n/** Authenticated user and partition scopes currently eligible for synchronization. */\nexport interface OfflineSyncSession {\n userId: OfflinePrincipalId;\n scopes: OfflineScope[];\n}\n\n/** Product adapter that exposes the currently authenticated synchronization session. */\nexport interface OfflineSyncContext {\n /** Session allowed to read/write the local replica and append durable outbox commands. */\n getLocalSession?(): Promise<OfflineSyncSession | null>;\n /** Remotely authenticated session allowed to pull and replay commands. */\n getSession(): Promise<OfflineSyncSession | null>;\n}\n\n/** DI token for authenticated synchronization context. */\nexport const OFFLINE_SYNC_CONTEXT = new InjectionToken<OfflineSyncContext>('OFFLINE_SYNC_CONTEXT');\n\n/** Resolves the transport target from a replica row. */\nexport function offlineCommandTargetFromReplicaRow(row: { readonly identity: OfflineReplicaIdentity }): OfflineCommandTarget {\n if (row.identity.kind === 'natural') return { kind: 'natural', naturalKey: row.identity.naturalKey };\n if (row.identity.kind === 'local') throw new Error('Local-only replica rows cannot be synchronized.');\n return { kind: 'generated', localId: row.identity.localId, remoteId: row.identity.remoteId };\n}\n\n/** Resolves a command lookup identity from an enqueue request identity. */\nexport function offlineCommandLookupIdentity(identity: EnqueueOfflineCommandIdentity): OfflineCommandIdentity {\n if (identity.kind === 'generated') return { kind: 'generated', localId: identity.localId };\n return { kind: 'natural', naturalKey: identity.naturalKey };\n}\n\n/** Enqueue identity for generated entities. */\nexport interface EnqueueOfflineGeneratedIdentity {\n readonly kind: 'generated';\n readonly localId: string;\n readonly remoteId?: OfflineGeneratedRemoteId | null;\n readonly remoteIdHint?: OfflineGeneratedRemoteId | null;\n}\n\n/** Enqueue identity for natural-key entities. */\nexport interface EnqueueOfflineNaturalIdentity {\n readonly kind: 'natural';\n readonly naturalKey: OfflineNaturalKey;\n}\n\nexport type EnqueueOfflineCommandIdentity = EnqueueOfflineGeneratedIdentity | EnqueueOfflineNaturalIdentity;\n","/**\n * Internal repository capability used to detect commits made through another\n * native SQLite connection during a local read/derive/write operation.\n *\n * This symbol is intentionally not re-exported from the package entry point.\n */\nexport const OFFLINE_REPOSITORY_ATOMIC_MUTATION: unique symbol = Symbol('OFFLINE_REPOSITORY_ATOMIC_MUTATION');\n","import { inject, Injectable, InjectionToken } from '@angular/core';\nimport { KitStorageService } from '@rdlabo/ionic-angular-kit';\nimport {\n canonicalOfflineCommandIdentity,\n canonicalOfflinePrincipalId,\n canonicalOfflineReplicaIdentity,\n commandIdentityFromReplicaIdentity,\n offlineReplicaRemoteIdentity,\n type OfflineCommandIdentity,\n type OfflineReplicaAddress,\n type OfflineReplicaIdentity,\n type OfflinePrincipalId,\n} from './offline-identity';\nimport { OFFLINE_REPOSITORY_ATOMIC_MUTATION } from './offline-repository-concurrency';\nimport { OFFLINE_KIT_OPTIONS } from './offline-kit-options';\nimport {\n assertOfflineReplicaGeneratedRemoteId,\n assertOfflineReplicaNaturalKeyBaseline,\n canonicalOfflineRemoteIdentity,\n encodeOfflineReplicaValues,\n normalizeOfflineNaturalKey,\n offlineNaturalKeyFromValues,\n projectOfflineReplicaValues,\n sha256OfflineReplicaSchema,\n type OfflineGeneratedRemoteId,\n type OfflineReplicaEntitySchema,\n type OfflineReplicaRemoteIdentity,\n type OfflineReplicaWebMigrationRow,\n} from './offline-replica-schema';\n\nexport type { OfflineCommandIdentity, OfflinePrincipalId, OfflineReplicaAddress, OfflineReplicaIdentity } from './offline-identity';\nexport {\n canonicalOfflineCommandIdentity,\n canonicalOfflinePrincipalId,\n canonicalOfflineReplicaIdentity,\n commandIdentityFromReplicaIdentity,\n commandIdentityMatchesReplicaRow,\n offlineGeneratedReplicaIdentity,\n offlineNaturalReplicaIdentity,\n offlineReplicaRemoteIdentity,\n parseOfflineCommandIdentity,\n parseOfflinePrincipalId,\n replicaAddressFromIdentity,\n serializeOfflineCommandIdentity,\n} from './offline-identity';\n\n/** Current durable storage schema used by both web and native repositories. */\nexport const OFFLINE_SCHEMA_VERSION = 2;\n\nconst settledRepositoryOperation = async (): Promise<void> => undefined;\n\n/** User and partition scope of all local offline data. */\nexport interface OfflineScope {\n userId: OfflinePrincipalId;\n scopeId: string;\n}\n\n/** Synchronization state of a locally materialized product replica row. */\nexport type OfflineReplicaSyncState = 'confirmed' | 'pending' | 'blocked_auth' | 'rejected' | 'conflict';\nexport type OfflineReplicaVisibility = 'present' | 'pending_delete';\nexport type OfflineReplicaMutation = 'upsert' | 'delete';\n\n/** Durable processing state of an outbox command. */\nexport type OfflineCommandState = 'pending' | 'sending' | 'retry_wait' | 'awaiting_pull' | 'blocked_auth' | 'rejected' | 'conflict';\n\ninterface OfflineCommandBase<T> extends OfflineScope {\n commandId: string;\n aggregateType: string;\n /** Replica schema source key resolved when the command is enqueued. */\n sourceKey: string;\n /** Stable row identity. The Outbox never persists a generated server id. */\n identity: OfflineCommandIdentity;\n operation: string;\n /** Opaque product payload. Kit never mutates this after enqueue. */\n payload: T;\n /**\n * Declared localOnly projection rows this intent may create, update, or remove.\n * Kit persists keys only; before/after images are not durable truth.\n */\n localOnlyFootprint?: readonly OfflineReplicaRowKey[];\n /** Durable intent used to preserve a hidden tombstone across restart and replay. */\n replicaMutation?: OfflineReplicaMutation;\n baseRevision: string | number | null;\n state: OfflineCommandState;\n attempts: number;\n retryAt: number | null;\n createdAt: number;\n lastErrorCode: string | null;\n /** True when transport started but the client cannot prove whether the server committed. */\n serverCommitUnknown?: boolean;\n /** Remote identity captured after transport for journal-independent authoritative reconciliation. */\n reconciliationIdentity?: OfflineReplicaRemoteIdentity;\n}\n\nexport type OfflineCommand<T = unknown> = OfflineCommandBase<T>;\n\n/** Product replica row materialized from a versioned schema entity. */\ninterface OfflineReplicaRowBase<TValues> extends OfflineScope {\n /** Stable source key matching {@link OfflineReplicaEntitySchema.sourceKey}. */\n sourceKey: string;\n /** Row identity matching the entity schema. Natural-key rows have no synthetic ids. */\n identity: OfflineReplicaIdentity;\n /** Current optimistic domain values displayed locally. */\n values: TValues;\n /** Last server-confirmed domain values, or null while pending. */\n confirmedValues: TValues | null;\n serverRevision: string | number | null;\n fetchedAt: number;\n syncState: OfflineReplicaSyncState;\n /** Library-owned visibility; pending deletes remain durable but are hidden from product reads. */\n visibility?: OfflineReplicaVisibility;\n}\n\nexport type OfflineReplicaRow<TValues = unknown> = OfflineReplicaRowBase<TValues>;\n\n/** Stable address of a product replica row inside a user or partition-scoped replica. */\nexport interface OfflineReplicaRowKey extends OfflineScope {\n sourceKey: string;\n identity: OfflineReplicaIdentity;\n}\n\n/** Canonical physical key shared by every repository and replica transaction coordinator. */\nexport function canonicalOfflineReplicaRowKey(\n schema: Pick<OfflineReplicaEntitySchema<Record<string, unknown>>, 'scope'>,\n row: OfflineReplicaRowKey,\n): string {\n const partition = schema.scope === 'user' ? 'user' : String(row.scopeId);\n return `${canonicalOfflinePrincipalId(row.userId)}:${partition}:${row.sourceKey}:${canonicalOfflineReplicaIdentity(row.identity)}`;\n}\n\n/** Explicit one-way release of a generated remote id during a replica delete acknowledgement. */\nexport interface OfflineReplicaRemoteIdRelease extends OfflineReplicaRowKey {\n /** The current remote id being released; the matching put row must set `remoteId` to null. */\n remoteId: OfflineGeneratedRemoteId;\n}\n\n/** Scope partition plus the durable replica pull cursor for that partition. */\nexport interface OfflineReplicaCursor extends OfflineScope {\n cursor: string;\n}\n\n/**\n * Closed set of durable reasons a scope cannot be pulled until the client recovers\n * (app upgrade or re-authorization). Independent of Outbox command state.\n */\nexport type OfflinePullAttentionReason = 'schema_upgrade_required' | 'authorization_required';\n\n/**\n * First-class durable attention for a fatal pull failure scoped to user+scope.\n * Survives restart even when the Outbox is empty.\n */\nexport interface OfflinePullAttention extends OfflineScope {\n reason: OfflinePullAttentionReason;\n /** Optional HTTP status that produced this attention (for example 401, 403, or 409). */\n status?: number;\n}\n\n/** Atomic changes applied to the local replica and durable outbox together. */\nexport interface OfflineReplicaTransaction {\n putRows?: readonly OfflineReplicaRow[];\n /**\n * Allows only the matching `remoteId: current -> null` transition in `putRows`.\n * All other remote-id changes remain immutable.\n */\n releaseRemoteIds?: readonly OfflineReplicaRemoteIdRelease[];\n removeRows?: readonly OfflineReplicaRowKey[];\n putCommands?: readonly OfflineCommand[];\n removeCommandIds?: readonly string[];\n putCursors?: readonly OfflineReplicaCursor[];\n /** Durable fatal-pull attentions to upsert for user+scope. */\n putPullAttentions?: readonly OfflinePullAttention[];\n /** Scopes whose fatal-pull attentions should be removed after a successful pull. */\n removePullAttentions?: readonly OfflineScope[];\n}\n\n/**\n * Read-only view of durable offline state that cannot observe an in-flight write transaction.\n *\n * Obtain via {@link OfflineRepository.runReadSnapshot}. Compose multiple reads through this\n * handle inside one callback; do not call {@link OfflineRepository.runReadSnapshot} recursively.\n */\nexport interface OfflineRepositoryReader {\n getLastUserId(): Promise<OfflinePrincipalId | null>;\n getSessionManifest<T>(userId: OfflinePrincipalId): Promise<T | null>;\n getReplicaRow<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null>;\n getReplicaRowIncludingPendingDelete?<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null>;\n getReplicaRows<TValues = unknown>(scope: OfflineScope, sourceKey: string): Promise<OfflineReplicaRow<TValues>[]>;\n getReplicaRowByRemoteId<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n remoteId: OfflineGeneratedRemoteId,\n ): Promise<OfflineReplicaRow<TValues> | null>;\n getReplicaRowByRemoteIdentity<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaRemoteIdentity,\n ): Promise<OfflineReplicaRow<TValues> | null>;\n getReplicaCursor(scope: OfflineScope): Promise<OfflineReplicaCursor | null>;\n getPullAttentions?(userId: OfflinePrincipalId): Promise<OfflinePullAttention[]>;\n getCommands(scope: OfflineScope): Promise<OfflineCommand[]>;\n getCommandsForUser?(userId: OfflinePrincipalId): Promise<OfflineCommand[]>;\n}\n\n/** Durable local replica and outbox persistence contract. */\nexport interface OfflineRepository {\n initialize(): Promise<void>;\n getLastUserId(): Promise<OfflinePrincipalId | null>;\n setLastUserId(userId: OfflinePrincipalId): Promise<void>;\n getSessionManifest<T>(userId: OfflinePrincipalId): Promise<T | null>;\n putSessionManifest<T>(userId: OfflinePrincipalId, value: T): Promise<void>;\n getReplicaRow<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null>;\n /** Internal durable lookup used by synchronization; includes pending-delete tombstones. */\n getReplicaRowIncludingPendingDelete?<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null>;\n getReplicaRows<TValues = unknown>(scope: OfflineScope, sourceKey: string): Promise<OfflineReplicaRow<TValues>[]>;\n getReplicaRowByRemoteId<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n remoteId: OfflineGeneratedRemoteId,\n ): Promise<OfflineReplicaRow<TValues> | null>;\n getReplicaRowByRemoteIdentity<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaRemoteIdentity,\n ): Promise<OfflineReplicaRow<TValues> | null>;\n getReplicaCursor(scope: OfflineScope): Promise<OfflineReplicaCursor | null>;\n /** Durable fatal-pull attentions for the principal, ordered by scope id. */\n getPullAttentions?(userId: OfflinePrincipalId): Promise<OfflinePullAttention[]>;\n getCommands(scope: OfflineScope): Promise<OfflineCommand[]>;\n getCommandsForUser?(userId: OfflinePrincipalId): Promise<OfflineCommand[]>;\n putCommand(command: OfflineCommand): Promise<void>;\n replaceCommand(command: OfflineCommand): Promise<void>;\n removeCommand(commandId: string): Promise<void>;\n /** Upserts a durable fatal-pull attention for user+scope. */\n putPullAttention?(attention: OfflinePullAttention): Promise<void>;\n /** Removes a durable fatal-pull attention for user+scope when present. */\n removePullAttention?(scope: OfflineScope): Promise<void>;\n clearUser(userId: OfflinePrincipalId): Promise<void>;\n clearScope(scope: OfflineScope): Promise<void>;\n transactReplica(transaction: OfflineReplicaTransaction): Promise<void>;\n /**\n * Runs `read` against a committed snapshot that cannot observe an in-flight write.\n *\n * Each call independently waits for prior writes, then holds a reader lease until `read`\n * settles so concurrent writers wait for all active readers. Compose multi-reads only via\n * the provided {@link OfflineRepositoryReader}; callers must not invoke `runReadSnapshot`\n * recursively from inside `read` (nested support is intentionally absent). Mutating APIs\n * must not be called from `read`.\n */\n runReadSnapshot<T>(read: (reader: OfflineRepositoryReader) => Promise<T>): Promise<T>;\n /** @internal Runs one optimistic read/derive/write operation with platform-specific concurrency validation. */\n [OFFLINE_REPOSITORY_ATOMIC_MUTATION]?<T>(operation: (repository: OfflineRepository) => Promise<T>): Promise<T>;\n}\n\n/** DI token for the selected platform repository. */\nexport const OFFLINE_REPOSITORY = new InjectionToken<OfflineRepository>('OFFLINE_REPOSITORY');\n\n/** Returns whether the platform uses the cross-process-safe native repository. */\nexport function supportsSynchronizedOfflineRepository(platform: string): boolean {\n return platform === 'ios' || platform === 'android';\n}\n\n/** Selects encrypted SQLite on native platforms and Ionic Storage elsewhere. */\nexport function selectOfflineRepository(\n platform: string,\n webRepository: OfflineRepository,\n nativeRepository: OfflineRepository,\n): OfflineRepository {\n return supportsSynchronizedOfflineRepository(platform) ? nativeRepository : webRepository;\n}\n\ninterface OfflineMetadata {\n schemaVersion: number;\n lastUserId: OfflinePrincipalId | null;\n replicaSchemaVersion: number | null;\n replicaSchemaHash: string | null;\n}\n\n/** Crash-recoverable journal for an in-flight web replica schema migration. */\ninterface OfflineReplicaSchemaMigrationJournal {\n originalRows: Record<string, OfflineReplicaRow>;\n fromVersion: number;\n fromHash: string;\n targetVersion: number;\n targetHash: string;\n}\n\nconst METADATA_KEY = 'offline:metadata';\nconst SESSION_MANIFESTS_KEY = 'offline:session:manifests';\nconst ROWS_KEY = 'offline:replica:rows';\nconst ROW_PARTITION_PREFIX = 'offline:replica:rows:index:v1:';\nconst ROW_PARTITION_READY_KEY = 'offline:replica:rows:index:v1:ready';\nconst CURSORS_KEY = 'offline:replica:cursors';\nconst OUTBOX_KEY = 'offline:outbox:commands';\nconst REPLICA_TRANSACTION_KEY = 'offline:replica:transaction';\nconst REPLICA_SCHEMA_MIGRATION_KEY = 'offline:replica:schema-migration';\n// Legacy marker storage is no longer read or written. Keep cleanup support for\n// databases created by released versions that persisted this key.\nconst RECONCILIATION_SCOPES_KEY = 'offline:replica:reconciliation-scopes';\nconst PULL_ATTENTIONS_KEY = 'offline:replica:pull-attentions';\n\nfunction compareOfflineCommands(left: OfflineCommand, right: OfflineCommand): number {\n return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);\n}\n\n/** WebはIonic StorageのIndexedDB driverを利用する。 */\n@Injectable({ providedIn: 'root' })\nexport class IonicOfflineRepository implements OfflineRepository {\n readonly #storage = inject(KitStorageService);\n readonly #options = inject(OFFLINE_KIT_OPTIONS);\n #initialization: Promise<void> | null = null;\n #writes: Promise<void> = settledRepositoryOperation();\n #activeReaders = 0;\n #readersIdle: Promise<void> = settledRepositoryOperation();\n #resolveReadersIdle: (() => void) | null = null;\n #rowIndexBuild: Promise<void> | null = null;\n\n initialize(): Promise<void> {\n if (!this.#initialization) {\n this.#initialization = this.#migrate().catch((error: unknown) => {\n this.#initialization = null;\n throw error;\n });\n }\n return this.#initialization;\n }\n\n async getLastUserId(): Promise<OfflinePrincipalId | null> {\n return this.#withCommittedRead(() => this.#readLastUserId());\n }\n\n async setLastUserId(userId: OfflinePrincipalId): Promise<void> {\n await this.initialize();\n await this.#enqueueWrite(async () => {\n await this.#storage.set<OfflineMetadata>(METADATA_KEY, { ...(await this.#metadata()), lastUserId: userId });\n });\n }\n\n async getSessionManifest<T>(userId: OfflinePrincipalId): Promise<T | null> {\n return this.#withCommittedRead(() => this.#readSessionManifest<T>(userId));\n }\n\n async putSessionManifest<T>(userId: OfflinePrincipalId, value: T): Promise<void> {\n await this.initialize();\n await this.#mutateRecord<T>(SESSION_MANIFESTS_KEY, (manifests) => {\n manifests[canonicalOfflinePrincipalId(userId)] = value;\n return manifests;\n });\n }\n\n async getReplicaRow<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n return this.#withCommittedRead(() => this.#readReplicaRow(scope, sourceKey, identity, false));\n }\n\n async getReplicaRowIncludingPendingDelete<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n return this.#withCommittedRead(() => this.#readReplicaRow(scope, sourceKey, identity, true));\n }\n\n async getReplicaRows<TValues = unknown>(scope: OfflineScope, sourceKey: string): Promise<OfflineReplicaRow<TValues>[]> {\n return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey));\n }\n\n async getReplicaRowByRemoteId<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n remoteId: OfflineGeneratedRemoteId,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated') return null;\n return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });\n }\n\n async getReplicaRowByRemoteIdentity<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaRemoteIdentity,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n return this.#withCommittedRead(() => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity));\n }\n\n async getReplicaCursor(scope: OfflineScope): Promise<OfflineReplicaCursor | null> {\n return this.#withCommittedRead(() => this.#readReplicaCursor(scope));\n }\n\n async getPullAttentions(userId: OfflinePrincipalId): Promise<OfflinePullAttention[]> {\n return this.#withCommittedRead(() => this.#readPullAttentions(userId));\n }\n\n async getCommands(scope: OfflineScope): Promise<OfflineCommand[]> {\n return this.#withCommittedRead(() => this.#readCommands(scope));\n }\n\n async getCommandsForUser(userId: OfflinePrincipalId): Promise<OfflineCommand[]> {\n return this.#withCommittedRead(() => this.#readCommandsForUser(userId));\n }\n\n async runReadSnapshot<T>(read: (reader: OfflineRepositoryReader) => Promise<T>): Promise<T> {\n return this.#withCommittedRead(() => read(this.#reader()));\n }\n\n #normalizeCommand(command: OfflineCommand): OfflineCommand {\n if (command.serverCommitUnknown !== undefined) return command;\n const legacyAmbiguousFailure = command.attempts >= 2 && ['blocked_auth', 'conflict', 'rejected'].includes(command.state);\n return command.state === 'sending' || command.state === 'retry_wait' || legacyAmbiguousFailure\n ? { ...command, serverCommitUnknown: true }\n : command;\n }\n\n async #readLastUserId(): Promise<OfflinePrincipalId | null> {\n return (await this.#metadata()).lastUserId;\n }\n\n async #readSessionManifest<T>(userId: OfflinePrincipalId): Promise<T | null> {\n const manifests = await this.#readRecord<T>(SESSION_MANIFESTS_KEY);\n return manifests[canonicalOfflinePrincipalId(userId)] ?? null;\n }\n\n async #readReplicaRow<TValues>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n includePendingDelete: boolean,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n const schema = this.#resolveReplicaEntitySchema(sourceKey);\n const rows = await this.#readRowPartition<TValues>(scope, sourceKey, schema);\n const row = this.#findRowByAddress(rows, scope, sourceKey, schema, identity);\n if (!row || (!includePendingDelete && (row.visibility ?? 'present') === 'pending_delete')) return null;\n return this.#rowForScope(row, schema, scope) as OfflineReplicaRow<TValues>;\n }\n\n async #readReplicaRows<TValues>(scope: OfflineScope, sourceKey: string): Promise<OfflineReplicaRow<TValues>[]> {\n const schema = this.#resolveReplicaEntitySchema(sourceKey);\n const rows = await this.#readRowPartition<TValues>(scope, sourceKey, schema);\n return Object.values(rows)\n .filter((row) => {\n if (row.sourceKey !== sourceKey || row.userId !== scope.userId) return false;\n if ((row.visibility ?? 'present') === 'pending_delete') return false;\n return schema.scope === 'partition' ? row.scopeId === scope.scopeId : true;\n })\n .map((row) => this.#rowForScope(row, schema, scope))\n .sort((left, right) => this.#compareReplicaIdentity(schema, left.identity, right.identity));\n }\n\n async #readReplicaRowByRemoteIdentity<TValues>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaRemoteIdentity,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n const schema = this.#resolveReplicaEntitySchema(sourceKey);\n const canonical = canonicalOfflineRemoteIdentity(schema, identity);\n const rows = await this.#readRowPartition<TValues>(scope, sourceKey, schema);\n const row = Object.values(rows).find((candidate) => {\n if (candidate.sourceKey !== sourceKey || candidate.userId !== scope.userId) return false;\n if (schema.scope === 'partition' && candidate.scopeId !== scope.scopeId) return false;\n const candidateIdentity = offlineReplicaRemoteIdentity(schema, candidate.identity);\n return candidateIdentity !== null && canonicalOfflineRemoteIdentity(schema, candidateIdentity) === canonical;\n });\n return row ? (this.#rowForScope(row, schema, scope) as OfflineReplicaRow<TValues>) : null;\n }\n\n async #readReplicaCursor(scope: OfflineScope): Promise<OfflineReplicaCursor | null> {\n const cursors = await this.#readRecord<string>(CURSORS_KEY);\n const cursor = cursors[this.#cursorKey(scope)];\n return cursor === undefined ? null : { ...scope, cursor };\n }\n\n async #readPullAttentions(userId: OfflinePrincipalId): Promise<OfflinePullAttention[]> {\n const attentions = await this.#readRecord<OfflinePullAttention>(PULL_ATTENTIONS_KEY);\n return Object.values(attentions)\n .filter((attention) => attention.userId === userId)\n .sort((left, right) => (left.scopeId < right.scopeId ? -1 : left.scopeId > right.scopeId ? 1 : 0));\n }\n\n async #readCommands(scope: OfflineScope): Promise<OfflineCommand[]> {\n const commands = await this.#readRecord<OfflineCommand>(OUTBOX_KEY);\n return Object.values(commands)\n .filter((command) => command.userId === scope.userId && command.scopeId === scope.scopeId)\n .map((command) => this.#normalizeCommand(command))\n .sort(compareOfflineCommands);\n }\n\n async #readCommandsForUser(userId: OfflinePrincipalId): Promise<OfflineCommand[]> {\n const commands = await this.#readRecord<OfflineCommand>(OUTBOX_KEY);\n return Object.values(commands)\n .filter((command) => command.userId === userId)\n .map((command) => this.#normalizeCommand(command))\n .sort(compareOfflineCommands);\n }\n\n #reader(): OfflineRepositoryReader {\n return {\n getLastUserId: () => this.#readLastUserId(),\n getSessionManifest: (userId) => this.#readSessionManifest(userId),\n getReplicaRow: (scope, sourceKey, identity) => this.#readReplicaRow(scope, sourceKey, identity, false),\n getReplicaRowIncludingPendingDelete: (scope, sourceKey, identity) => this.#readReplicaRow(scope, sourceKey, identity, true),\n getReplicaRows: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey),\n getReplicaRowByRemoteId: async (scope, sourceKey, remoteId) => {\n if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated') return null;\n return this.#readReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });\n },\n getReplicaRowByRemoteIdentity: (scope, sourceKey, identity) => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity),\n getReplicaCursor: (scope) => this.#readReplicaCursor(scope),\n getPullAttentions: (userId) => this.#readPullAttentions(userId),\n getCommands: (scope) => this.#readCommands(scope),\n getCommandsForUser: (userId) => this.#readCommandsForUser(userId),\n };\n }\n\n async #withCommittedRead<T>(operation: () => Promise<T>): Promise<T> {\n await this.initialize();\n // Finish index readiness first (may enqueue a write). Then await the latest write\n // tail and register the reader synchronously — no await gap for a writer to start.\n await this.#ensureRowPartitionsReady();\n await this.#writes;\n this.#beginReaders();\n const read = async (): Promise<T> => operation();\n return read().finally(() => this.#endReaders());\n }\n\n #beginReaders(): void {\n if (this.#activeReaders === 0) {\n this.#readersIdle = new Promise<void>((resolve) => {\n this.#resolveReadersIdle = resolve;\n });\n }\n this.#activeReaders += 1;\n }\n\n #endReaders(): void {\n this.#activeReaders -= 1;\n if (this.#activeReaders === 0) {\n this.#resolveReadersIdle?.();\n this.#resolveReadersIdle = null;\n this.#readersIdle = settledRepositoryOperation();\n }\n }\n\n async putCommand(command: OfflineCommand): Promise<void> {\n await this.initialize();\n await this.#assertReplicaSchemaLocked();\n await this.#mutateRecord<OfflineCommand>(OUTBOX_KEY, (commands) => {\n commands[command.commandId] = command;\n return commands;\n });\n }\n\n replaceCommand(command: OfflineCommand): Promise<void> {\n return this.putCommand(command);\n }\n\n async removeCommand(commandId: string): Promise<void> {\n await this.initialize();\n await this.#mutateRecord<OfflineCommand>(OUTBOX_KEY, (commands) => {\n delete commands[commandId];\n return commands;\n });\n }\n\n async putPullAttention(attention: OfflinePullAttention): Promise<void> {\n await this.initialize();\n await this.#mutateRecord<OfflinePullAttention>(PULL_ATTENTIONS_KEY, (attentions) => {\n attentions[this.#cursorKey(attention)] = attention;\n return attentions;\n });\n }\n\n async removePullAttention(scope: OfflineScope): Promise<void> {\n await this.initialize();\n await this.#mutateRecord<OfflinePullAttention>(PULL_ATTENTIONS_KEY, (attentions) => {\n delete attentions[this.#cursorKey(scope)];\n return attentions;\n });\n }\n\n async clearUser(userId: OfflinePrincipalId): Promise<void> {\n await this.initialize();\n await this.#enqueueWrite(async () => {\n await this.#removeRowPartitions((key) => key.startsWith(`${ROW_PARTITION_PREFIX}${canonicalOfflinePrincipalId(userId)}:`));\n await Promise.all([\n this.#mutateRecordNow(SESSION_MANIFESTS_KEY, (manifests) => {\n delete manifests[canonicalOfflinePrincipalId(userId)];\n return manifests;\n }),\n this.#filterRecordNow<OfflineReplicaRow>(ROWS_KEY, (value) => value.userId !== userId),\n this.#filterRecordNow<OfflineCommand>(OUTBOX_KEY, (value) => value.userId !== userId),\n this.#filterRecordNow<string>(CURSORS_KEY, (_value, key) => !key.startsWith(`${canonicalOfflinePrincipalId(userId)}:`)),\n this.#filterRecordNow<OfflineScope>(RECONCILIATION_SCOPES_KEY, (value) => value.userId !== userId),\n this.#filterRecordNow<OfflinePullAttention>(PULL_ATTENTIONS_KEY, (value) => value.userId !== userId),\n ]);\n const metadata = await this.#metadata();\n if (metadata.lastUserId === userId) {\n await this.#storage.set<OfflineMetadata>(METADATA_KEY, { ...metadata, lastUserId: null });\n }\n });\n }\n\n async clearScope(scope: OfflineScope): Promise<void> {\n await this.initialize();\n const belongsToGroup = (value: OfflineScope) => value.userId === scope.userId && value.scopeId === scope.scopeId;\n await this.#enqueueWrite(async () => {\n await this.#removeRowPartitions((key) => {\n if (!key.startsWith(`${ROW_PARTITION_PREFIX}${canonicalOfflinePrincipalId(scope.userId)}:`)) return false;\n return key.includes(`:partition:${encodeURIComponent(scope.scopeId)}:`);\n });\n await Promise.all([\n this.#filterRecordNow<OfflineReplicaRow>(ROWS_KEY, (value) => {\n const schema = this.#resolveReplicaEntitySchema(value.sourceKey);\n return schema.scope === 'user' || !belongsToGroup(value);\n }),\n this.#filterRecordNow<OfflineCommand>(OUTBOX_KEY, (value) => {\n const schema = this.#resolveReplicaEntitySchema(value.sourceKey);\n return schema.scope === 'user' || !belongsToGroup(value);\n }),\n this.#filterRecordNow<string>(CURSORS_KEY, (_value, key) => key !== this.#cursorKey(scope)),\n this.#filterRecordNow<OfflineScope>(RECONCILIATION_SCOPES_KEY, (value) => !belongsToGroup(value)),\n this.#filterRecordNow<OfflinePullAttention>(PULL_ATTENTIONS_KEY, (value) => !belongsToGroup(value)),\n ]);\n });\n }\n\n async transactReplica(transaction: OfflineReplicaTransaction): Promise<void> {\n await this.initialize();\n return this.#enqueueWrite(() => this.#applyReplicaTransaction(transaction, true));\n }\n\n async #migrate(): Promise<void> {\n const metadata = await this.#storage.get<Partial<OfflineMetadata>>(METADATA_KEY);\n if (metadata?.schemaVersion !== undefined && metadata.schemaVersion !== OFFLINE_SCHEMA_VERSION) {\n throw new Error(\n `Unsupported offline storage schema version ${metadata.schemaVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +\n 'A lossless core schema migration is required before this database can be opened.',\n );\n }\n\n const interruptedSchemaMigration = await this.#storage.get<OfflineReplicaSchemaMigrationJournal>(REPLICA_SCHEMA_MIGRATION_KEY);\n if (interruptedSchemaMigration) {\n await this.#recoverReplicaSchemaMigration(interruptedSchemaMigration);\n }\n\n const currentMetadata = await this.#metadata();\n await this.#initializeReplicaSchema(currentMetadata.replicaSchemaVersion, currentMetadata.replicaSchemaHash);\n\n const interrupted = await this.#storage.get<OfflineReplicaTransaction>(REPLICA_TRANSACTION_KEY);\n if (interrupted) await this.#applyReplicaTransaction(interrupted, false);\n }\n\n async #initializeReplicaSchema(storedVersion: number | null, storedHash: string | null): Promise<void> {\n const bundle = this.#options.replicaSchema;\n const targetVersion = bundle.version;\n const targetHash = await sha256OfflineReplicaSchema(bundle);\n\n if (storedVersion === null) {\n const metadata = await this.#metadata();\n await this.#storage.set<OfflineMetadata>(METADATA_KEY, {\n ...metadata,\n replicaSchemaVersion: targetVersion,\n replicaSchemaHash: targetHash,\n });\n return;\n }\n\n if (storedVersion === targetVersion && storedHash === targetHash) {\n return;\n }\n\n if (storedVersion === targetVersion) {\n throw new Error(\n `Offline replica schema hash mismatch at version ${targetVersion}. Reinstall the application or bump replicaSchema.version after intentional schema changes.`,\n );\n }\n\n if (storedVersion > targetVersion) {\n throw new Error(\n `Offline replica schema version ${storedVersion} is newer than application version ${targetVersion}. Upgrade the application before opening this database.`,\n );\n }\n\n if (storedHash === null) {\n throw new Error(`Offline replica schema metadata at version ${storedVersion} is missing its schema hash.`);\n }\n\n await this.#runReplicaSchemaMigration(storedVersion, storedHash, targetVersion, targetHash);\n }\n\n async #recoverReplicaSchemaMigration(journal: OfflineReplicaSchemaMigrationJournal): Promise<void> {\n await this.#removeRowPartitions(() => true);\n await this.#storage.set(ROWS_KEY, journal.originalRows);\n const metadata = await this.#metadata();\n await this.#storage.set<OfflineMetadata>(METADATA_KEY, {\n ...metadata,\n replicaSchemaVersion: journal.fromVersion,\n replicaSchemaHash: journal.fromHash,\n });\n await this.#storage.remove(REPLICA_SCHEMA_MIGRATION_KEY);\n }\n\n async #runReplicaSchemaMigration(fromVersion: number, fromHash: string, targetVersion: number, targetHash: string): Promise<void> {\n const bundle = this.#options.replicaSchema;\n for (let version = fromVersion; version < targetVersion; version++) {\n if (!bundle.migrations.some((migration) => migration.fromVersion === version)) {\n throw new Error(`Missing offline replica schema migration from version ${version} to ${version + 1}.`);\n }\n }\n\n return this.#enqueueWrite(async (): Promise<void> => {\n const rows = await this.#readRecord<OfflineReplicaRow>(ROWS_KEY);\n const originalRows = structuredClone(rows);\n await this.#storage.set<OfflineReplicaSchemaMigrationJournal>(REPLICA_SCHEMA_MIGRATION_KEY, {\n originalRows,\n fromVersion,\n fromHash,\n targetVersion,\n targetHash,\n });\n\n const commitMigration = async (): Promise<void> => {\n const transformedRows: Record<string, OfflineReplicaRow> = {};\n for (const row of Object.values(rows)) {\n let current: OfflineReplicaWebMigrationRow | null = this.#toWebMigrationRow(row);\n for (let version = fromVersion; version < targetVersion; version++) {\n if (current === null) break;\n const migration = bundle.migrations.find((candidate) => candidate.fromVersion === version);\n if (!migration) {\n throw new Error(`Missing offline replica schema migration from version ${version} to ${version + 1}.`);\n }\n current = await migration.migrateWebRow(current);\n }\n if (current === null) continue;\n\n const entitySchema = bundle.entities.find((entity) => entity.sourceKey === current!.sourceKey);\n if (!entitySchema) {\n throw new Error(`Unknown offline replica source key \"${current!.sourceKey}\" after schema migration.`);\n }\n encodeOfflineReplicaValues(entitySchema, current!.values);\n if (current!.confirmedValues !== null) {\n encodeOfflineReplicaValues(entitySchema, current!.confirmedValues);\n }\n\n const transformedRow: OfflineReplicaRow = {\n ...row,\n sourceKey: current!.sourceKey,\n values: projectOfflineReplicaValues(entitySchema, current!.values),\n confirmedValues: current!.confirmedValues === null ? null : projectOfflineReplicaValues(entitySchema, current!.confirmedValues),\n };\n const transformedKey = this.#rowKey(transformedRow);\n if (transformedRows[transformedKey]) {\n throw new Error(`Replica schema migration produced duplicate row key \"${transformedKey}\".`);\n }\n transformedRows[transformedKey] = transformedRow;\n }\n\n const metadata = await this.#metadata();\n await this.#storage.set(ROWS_KEY, transformedRows);\n await this.#removeRowPartitions(() => true);\n await this.#storage.set<OfflineMetadata>(METADATA_KEY, {\n ...metadata,\n replicaSchemaVersion: targetVersion,\n replicaSchemaHash: targetHash,\n });\n await this.#storage.remove(REPLICA_SCHEMA_MIGRATION_KEY);\n };\n await commitMigration().catch(async (error: unknown) => {\n await this.#recoverReplicaSchemaMigration({\n originalRows,\n fromVersion,\n fromHash,\n targetVersion,\n targetHash,\n });\n throw error;\n });\n });\n }\n\n #toWebMigrationRow(row: OfflineReplicaRow): OfflineReplicaWebMigrationRow {\n return {\n sourceKey: row.sourceKey,\n values: structuredClone(row.values as Record<string, unknown>),\n confirmedValues: row.confirmedValues === null ? null : structuredClone(row.confirmedValues as Record<string, unknown>),\n };\n }\n\n async #assertReplicaSchemaLocked(): Promise<void> {\n const bundle = this.#options.replicaSchema;\n const metadata = await this.#metadata();\n const targetHash = await sha256OfflineReplicaSchema(bundle);\n if (metadata.replicaSchemaVersion === null) {\n throw new Error('Offline replica schema metadata is not initialized.');\n }\n if (metadata.replicaSchemaVersion !== bundle.version) {\n throw new Error(\n `Offline replica schema version ${metadata.replicaSchemaVersion} does not match application version ${bundle.version}.`,\n );\n }\n if (metadata.replicaSchemaHash !== targetHash) {\n throw new Error(\n `Offline replica schema hash mismatch at version ${bundle.version}. Reinstall the application or bump replicaSchema.version after intentional schema changes.`,\n );\n }\n }\n\n async #applyReplicaTransaction(transaction: OfflineReplicaTransaction, journal: boolean): Promise<void> {\n await this.#assertReplicaSchemaLocked();\n for (const row of transaction.putRows ?? []) this.#validateReplicaRow(row);\n const [rows, commands, cursors, pullAttentions] = await Promise.all([\n this.#readRecord<OfflineReplicaRow>(ROWS_KEY),\n this.#readRecord<OfflineCommand>(OUTBOX_KEY),\n this.#readRecord<string>(CURSORS_KEY),\n this.#readRecord<OfflinePullAttention>(PULL_ATTENTIONS_KEY),\n ]);\n const identityCheckRows = { ...rows };\n const releases = new Map<string, OfflineReplicaRemoteIdRelease>();\n for (const release of transaction.releaseRemoteIds ?? []) {\n this.#assertValidReleaseRemoteId(release.remoteId);\n const key = this.#rowKey(release);\n if (releases.has(key)) {\n throw new Error(\n `Offline replica remoteId release is duplicated for ${release.sourceKey}/${canonicalOfflineReplicaIdentity(release.identity)}.`,\n );\n }\n releases.set(key, release);\n }\n const consumedReleases = new Set<string>();\n for (const row of transaction.putRows ?? []) {\n const key = this.#rowKey(row);\n const existing = identityCheckRows[key];\n const release = releases.get(key);\n if (!existing && release) {\n throw new Error(\n `Offline replica remoteId release requires an existing row for ${row.sourceKey}/${canonicalOfflineReplicaIdentity(row.identity)}.`,\n );\n }\n if (existing) this.#assertReplicaIdentityAssignment(existing, row, release);\n if (release) consumedReleases.add(key);\n this.#assertUniqueReplicaIdentity(identityCheckRows, row);\n identityCheckRows[key] = row;\n }\n if (consumedReleases.size !== releases.size) {\n throw new Error('Offline replica remoteId release must match an existing row in putRows.');\n }\n if (journal) await this.#storage.set(REPLICA_TRANSACTION_KEY, transaction);\n for (const row of transaction.putRows ?? []) {\n const schema = this.#resolveReplicaEntitySchema(row.sourceKey);\n rows[this.#rowKey(row)] = {\n ...row,\n scopeId: schema.scope === 'user' ? '' : row.scopeId,\n values: projectOfflineReplicaValues(schema, row.values),\n confirmedValues: row.confirmedValues === null ? null : projectOfflineReplicaValues(schema, row.confirmedValues),\n };\n }\n for (const row of transaction.removeRows ?? []) {\n delete rows[this.#rowKey(row)];\n }\n for (const command of transaction.putCommands ?? []) commands[command.commandId] = command;\n for (const commandId of transaction.removeCommandIds ?? []) delete commands[commandId];\n for (const cursor of transaction.putCursors ?? []) {\n cursors[this.#cursorKey(cursor)] = cursor.cursor;\n }\n for (const attention of transaction.putPullAttentions ?? []) {\n pullAttentions[this.#cursorKey(attention)] = attention;\n }\n for (const scope of transaction.removePullAttentions ?? []) {\n delete pullAttentions[this.#cursorKey(scope)];\n }\n await Promise.all([\n this.#storage.set(ROWS_KEY, rows),\n this.#storage.set(OUTBOX_KEY, commands),\n this.#storage.set(CURSORS_KEY, cursors),\n this.#storage.set(PULL_ATTENTIONS_KEY, pullAttentions),\n ]);\n await this.#writeAffectedRowPartitions(rows, transaction);\n await this.#storage.remove(REPLICA_TRANSACTION_KEY);\n }\n\n async #readRowPartition<TValues>(\n scope: OfflineScope,\n sourceKey: string,\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n ): Promise<Record<string, OfflineReplicaRow<TValues>>> {\n const key = this.#rowPartitionKey(scope, sourceKey, schema);\n const cached = await this.#storage.get<Record<string, OfflineReplicaRow<TValues>>>(key);\n if (cached !== null) return cached;\n if (await this.#storage.get<boolean>(ROW_PARTITION_READY_KEY)) return {};\n // Non-mutating fallback under a reader lease (indexes are normally built before the lease).\n return this.#legacyRowPartition(scope, sourceKey, schema);\n }\n\n async #legacyRowPartition<TValues>(\n scope: OfflineScope,\n sourceKey: string,\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n ): Promise<Record<string, OfflineReplicaRow<TValues>>> {\n const rows = await this.#readRecord<OfflineReplicaRow<TValues>>(ROWS_KEY);\n return Object.fromEntries(\n Object.entries(rows).filter(([, row]) => {\n if (row.userId !== scope.userId || row.sourceKey !== sourceKey) return false;\n return schema.scope === 'user' || row.scopeId === scope.scopeId;\n }),\n );\n }\n\n async #ensureRowPartitionsReady(): Promise<void> {\n if (await this.#storage.get<boolean>(ROW_PARTITION_READY_KEY)) return;\n await this.#buildRowPartitions();\n }\n\n #buildRowPartitions(): Promise<void> {\n if (!this.#rowIndexBuild) {\n const run = async (): Promise<void> => {\n if (await this.#storage.get<boolean>(ROW_PARTITION_READY_KEY)) return;\n const rows = await this.#readRecord<OfflineReplicaRow>(ROWS_KEY);\n const partitions = new Map<string, Record<string, OfflineReplicaRow>>();\n for (const [rowKey, row] of Object.entries(rows)) {\n const schema = this.#resolveReplicaEntitySchema(row.sourceKey);\n const key = this.#rowPartitionKey(row, row.sourceKey, schema);\n const partition = partitions.get(key) ?? {};\n partition[rowKey] = row;\n partitions.set(key, partition);\n }\n await Promise.all([...partitions].map(([key, partition]) => this.#storage.set(key, partition)));\n await this.#storage.set(ROW_PARTITION_READY_KEY, true);\n };\n const build = this.#enqueueWrite(run);\n this.#rowIndexBuild = build.finally(() => {\n this.#rowIndexBuild = null;\n });\n }\n return this.#rowIndexBuild;\n }\n\n async #writeAffectedRowPartitions(rows: Record<string, OfflineReplicaRow>, transaction: OfflineReplicaTransaction): Promise<void> {\n const affected = new Map<\n string,\n { scope: OfflineScope; sourceKey: string; schema: OfflineReplicaEntitySchema<Record<string, unknown>> }\n >();\n for (const row of [...(transaction.putRows ?? []), ...(transaction.removeRows ?? [])]) {\n const schema = this.#resolveReplicaEntitySchema(row.sourceKey);\n const key = this.#rowPartitionKey(row, row.sourceKey, schema);\n affected.set(key, { scope: row, sourceKey: row.sourceKey, schema });\n }\n await Promise.all(\n [...affected].map(([key, { scope, sourceKey, schema }]) =>\n this.#storage.set(\n key,\n Object.fromEntries(\n Object.entries(rows).filter(([, row]) => {\n if (row.userId !== scope.userId || row.sourceKey !== sourceKey) return false;\n return schema.scope === 'user' || row.scopeId === scope.scopeId;\n }),\n ),\n ),\n ),\n );\n }\n\n #rowPartitionKey(scope: OfflineScope, sourceKey: string, schema: OfflineReplicaEntitySchema<Record<string, unknown>>): string {\n const partition = schema.scope === 'user' ? 'user' : `partition:${encodeURIComponent(scope.scopeId)}`;\n return `${ROW_PARTITION_PREFIX}${canonicalOfflinePrincipalId(scope.userId)}:${partition}:${encodeURIComponent(sourceKey)}`;\n }\n\n async #removeRowPartitions(matches: (key: string) => boolean): Promise<void> {\n const keys = (await this.#storage.keys()).filter((key) => key.startsWith(ROW_PARTITION_PREFIX) && matches(key));\n await Promise.all(keys.map((key) => this.#storage.remove(key)));\n }\n\n async #metadata(): Promise<OfflineMetadata> {\n const metadata = await this.#storage.get<Partial<OfflineMetadata>>(METADATA_KEY);\n return {\n schemaVersion: metadata?.schemaVersion ?? OFFLINE_SCHEMA_VERSION,\n lastUserId: metadata?.lastUserId ?? null,\n replicaSchemaVersion: metadata?.replicaSchemaVersion ?? null,\n replicaSchemaHash: metadata?.replicaSchemaHash ?? null,\n };\n }\n\n async #readRecord<T>(key: string): Promise<Record<string, T>> {\n return (await this.#storage.get<Record<string, T>>(key)) ?? {};\n }\n\n #filterRecordNow<T>(key: string, predicate: (value: T, recordKey: string) => boolean): Promise<void> {\n return this.#mutateRecordNow<T>(key, (record) =>\n Object.fromEntries(Object.entries(record).filter(([recordKey, value]) => predicate(value, recordKey))),\n );\n }\n\n #mutateRecord<T>(key: string, mutate: (record: Record<string, T>) => Record<string, T>): Promise<void> {\n return this.#enqueueWrite(() => this.#mutateRecordNow(key, mutate));\n }\n\n async #mutateRecordNow<T>(key: string, mutate: (record: Record<string, T>) => Record<string, T>): Promise<void> {\n const record = await this.#readRecord<T>(key);\n await this.#storage.set(key, mutate(record));\n }\n\n #enqueueWrite<T>(operation: () => Promise<T>): Promise<T> {\n const write = this.#writes.then(async () => {\n if (this.#activeReaders > 0) await this.#readersIdle;\n return operation();\n });\n this.#writes = write.then(\n () => undefined,\n () => undefined,\n );\n return write;\n }\n\n #rowKey(row: OfflineScope & { sourceKey: string; identity: OfflineReplicaIdentity }): string {\n const schema = this.#resolveReplicaEntitySchema(row.sourceKey);\n return canonicalOfflineReplicaRowKey(schema, row);\n }\n\n #findRowByAddress<TValues>(\n rows: Record<string, OfflineReplicaRow<TValues>>,\n scope: OfflineScope,\n sourceKey: string,\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n identity: OfflineReplicaAddress,\n ): OfflineReplicaRow<TValues> | undefined {\n return Object.values(rows).find((row) => {\n if (row.sourceKey !== sourceKey || row.userId !== scope.userId) return false;\n if (schema.scope === 'partition' && row.scopeId !== scope.scopeId) return false;\n if (identity.kind === 'generated') {\n return row.identity.kind === 'generated' && row.identity.localId === identity.localId;\n }\n if (identity.kind === 'local') {\n return row.identity.kind === 'local' && row.identity.localId === identity.localId;\n }\n if (row.identity.kind !== 'natural') return false;\n return (\n canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) ===\n canonicalOfflineRemoteIdentity(schema, { naturalKey: normalizeOfflineNaturalKey(schema, identity.naturalKey) })\n );\n });\n }\n\n #rowForScope<TValues>(\n row: OfflineReplicaRow<TValues>,\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n scope: OfflineScope,\n ): OfflineReplicaRow<TValues> {\n const normalized = { ...row, visibility: row.visibility ?? ('present' as const) };\n return schema.scope === 'user' ? { ...normalized, scopeId: scope.scopeId } : normalized;\n }\n\n #cursorKey(scope: OfflineScope): string {\n return `${canonicalOfflinePrincipalId(scope.userId)}:${scope.scopeId}`;\n }\n\n #compareReplicaIdentity(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n left: import('./offline-identity').OfflineReplicaIdentity,\n right: import('./offline-identity').OfflineReplicaIdentity,\n ): number {\n if (left.kind === 'natural' && right.kind === 'natural' && schema.identity.kind === 'naturalKey') {\n const leftKey = normalizeOfflineNaturalKey(schema, left.naturalKey);\n const rightKey = normalizeOfflineNaturalKey(schema, right.naturalKey);\n for (const sourceKey of schema.identity.sourceKeys) {\n const leftValue = leftKey[sourceKey]!;\n const rightValue = rightKey[sourceKey]!;\n if (leftValue === rightValue) continue;\n if (typeof leftValue === 'number' && typeof rightValue === 'number') {\n return leftValue < rightValue ? -1 : 1;\n }\n return compareUtf8Binary(String(leftValue), String(rightValue));\n }\n return 0;\n }\n const leftId = left.kind === 'natural' ? canonicalOfflineReplicaIdentity(left) : left.localId;\n const rightId = right.kind === 'natural' ? canonicalOfflineReplicaIdentity(right) : right.localId;\n return compareUtf8Binary(leftId, rightId);\n }\n\n #validateReplicaRow(row: OfflineReplicaRow): void {\n const schema = this.#resolveReplicaEntitySchema(row.sourceKey);\n this.#validateRowIdentity(schema, row);\n encodeOfflineReplicaValues(schema, row.values);\n if (row.confirmedValues !== null) encodeOfflineReplicaValues(schema, row.confirmedValues);\n assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);\n }\n\n #validateRowIdentity(schema: OfflineReplicaEntitySchema<Record<string, unknown>>, row: OfflineReplicaRow): void {\n if (schema.identity.kind === 'localOnly') {\n if (row.identity.kind !== 'local') {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" requires local identity.`);\n }\n return;\n }\n if (schema.identity.kind === 'generated') {\n if (row.identity.kind !== 'generated') {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" requires generated identity.`);\n }\n assertOfflineReplicaGeneratedRemoteId(schema, row.identity.remoteId);\n return;\n }\n if (schema.identity.kind === 'naturalKey') {\n if (row.identity.kind !== 'natural') {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" requires natural identity.`);\n }\n const fromValues = offlineNaturalKeyFromValues(schema, row.values)!;\n if (\n canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) !==\n canonicalOfflineRemoteIdentity(schema, { naturalKey: fromValues })\n ) {\n throw new Error(`Offline replica identity naturalKey must match values for \"${schema.sourceKey}\".`);\n }\n }\n }\n\n #assertUniqueReplicaIdentity(rows: Record<string, OfflineReplicaRow>, incoming: OfflineReplicaRow): void {\n const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);\n const identity = offlineReplicaRemoteIdentity(schema, incoming.identity);\n if (identity === null) return;\n const canonical = canonicalOfflineRemoteIdentity(schema, identity);\n const incomingKey = this.#rowKey(incoming);\n const collision = Object.entries(rows).find(([key, row]) => {\n if (key === incomingKey) return false;\n if (row.userId !== incoming.userId || row.sourceKey !== incoming.sourceKey) return false;\n if (schema.scope === 'partition' && row.scopeId !== incoming.scopeId) return false;\n const rowIdentity = offlineReplicaRemoteIdentity(schema, row.identity);\n return rowIdentity !== null && canonicalOfflineRemoteIdentity(schema, rowIdentity) === canonical;\n });\n if (collision) {\n if (schema.identity.kind === 'generated') {\n const remoteId = incoming.identity.kind === 'generated' ? incoming.identity.remoteId : null;\n const mapped =\n collision[1].identity.kind === 'generated'\n ? collision[1].identity.localId\n : canonicalOfflineReplicaIdentity(collision[1].identity);\n throw new Error(`Offline replica remote id ${String(remoteId)} is already mapped to ${mapped}.`);\n }\n throw new Error(`Offline replica remote identity is already mapped to another row.`);\n }\n }\n\n #assertReplicaIdentityAssignment(\n existing: OfflineReplicaRow,\n incoming: OfflineReplicaRow,\n release: OfflineReplicaRemoteIdRelease | undefined,\n ): void {\n const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);\n if (release && schema.identity.kind !== 'generated') {\n throw new Error(`Offline replica remoteId release is unsupported for source \"${incoming.sourceKey}\".`);\n }\n if (schema.identity.kind === 'localOnly') {\n if (existing.identity.kind !== 'local' || incoming.identity.kind !== 'local') {\n throw new Error(`Offline replica local identity is required for \"${incoming.sourceKey}\".`);\n }\n if (existing.identity.localId !== incoming.identity.localId) {\n throw new Error(`Offline replica localId is immutable for \"${schema.sourceKey}\".`);\n }\n return;\n }\n if (schema.identity.kind === 'generated') {\n if (existing.identity.kind !== 'generated' || incoming.identity.kind !== 'generated') {\n throw new Error(`Offline replica generated identity is required for \"${incoming.sourceKey}\".`);\n }\n if (release) {\n if (existing.identity.remoteId !== release.remoteId || incoming.identity.remoteId !== null) {\n throw new Error(\n `Offline replica remoteId release must transition current=${String(existing.identity.remoteId)} to incoming=null for ${incoming.sourceKey}/${incoming.identity.localId}.`,\n );\n }\n return;\n }\n if (existing.identity.localId !== incoming.identity.localId) {\n throw new Error(`Offline replica localId is immutable for \"${schema.sourceKey}\".`);\n }\n if (existing.identity.remoteId !== null && existing.identity.remoteId !== incoming.identity.remoteId) {\n throw new Error(\n `Offline replica remoteId is immutable: current=${String(existing.identity.remoteId)}, incoming=${String(incoming.identity.remoteId)}.`,\n );\n }\n return;\n }\n if (schema.identity.kind === 'naturalKey') {\n if (existing.identity.kind !== 'natural' || incoming.identity.kind !== 'natural') {\n throw new Error(`Offline replica natural identity is required for \"${schema.sourceKey}\".`);\n }\n const current = canonicalOfflineRemoteIdentity(schema, { naturalKey: existing.identity.naturalKey });\n const next = canonicalOfflineRemoteIdentity(schema, { naturalKey: incoming.identity.naturalKey });\n if (current !== next) throw new Error(`Offline replica naturalKey is immutable for \"${schema.sourceKey}\".`);\n }\n }\n\n #assertValidReleaseRemoteId(remoteId: OfflineGeneratedRemoteId): void {\n if (typeof remoteId === 'number') {\n if (!Number.isSafeInteger(remoteId) || remoteId <= 0) {\n throw new Error(`Offline replica release has invalid remoteId ${String(remoteId)}.`);\n }\n return;\n }\n if (typeof remoteId !== 'string' || remoteId.length === 0) {\n throw new Error(`Offline replica release has invalid remoteId ${String(remoteId)}.`);\n }\n }\n\n #resolveReplicaEntitySchema(sourceKey: string): OfflineReplicaEntitySchema<Record<string, unknown>> {\n const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);\n if (!schema) throw new Error(`Unknown offline replica source key \"${sourceKey}\".`);\n return schema;\n }\n}\n\nfunction compareUtf8Binary(left: string, right: string): number {\n const leftBytes = new TextEncoder().encode(left);\n const rightBytes = new TextEncoder().encode(right);\n const length = Math.min(leftBytes.length, rightBytes.length);\n for (let index = 0; index < length; index += 1) {\n if (leftBytes[index] !== rightBytes[index]) return leftBytes[index]! < rightBytes[index]! ? -1 : 1;\n }\n return leftBytes.length < rightBytes.length ? -1 : leftBytes.length > rightBytes.length ? 1 : 0;\n}\n","import { inject, Injectable } from '@angular/core';\nimport {\n OFFLINE_AGGREGATE_INTENT_PROJECTOR,\n isOfflineAggregateIntentConflict,\n type OfflineAggregateIntentProjectInput,\n type OfflineAggregateIntentProjection,\n type OfflineAggregateIntentProjectResult,\n} from './offline-aggregate-intent-projector';\nimport { canonicalOfflineReplicaIdentity, commandIdentityMatchesReplicaRow, type OfflineCommandIdentity } from './offline-identity';\nimport { OFFLINE_KIT_OPTIONS } from './offline-kit-options';\nimport { OFFLINE_REPOSITORY_ATOMIC_MUTATION } from './offline-repository-concurrency';\nimport {\n OFFLINE_REPOSITORY,\n canonicalOfflineReplicaRowKey,\n type OfflineCommand,\n type OfflineReplicaRow,\n type OfflineReplicaRowKey,\n type OfflineRepository,\n type OfflineScope,\n} from './offline-repository';\nimport type { OfflineReplicaEntitySchema } from './offline-replica-schema';\n\nconst settledMutation = async (): Promise<void> => undefined;\n\n/**\n * Serializes only local replica read/derive/write critical sections. Network\n * transport must stay outside this coordinator so synchronization never holds\n * the local mutation lane while waiting on I/O.\n *\n * This coordinator is the sole caller and validator of aggregate rematerialization.\n * Invoke {@link projectAggregateIntent} only from inside {@link run}; this\n * method does not acquire the lane itself.\n */\n@Injectable({ providedIn: 'root' })\nexport class OfflineReplicaMutationCoordinator {\n readonly #repository = inject(OFFLINE_REPOSITORY, { optional: true });\n readonly #projector = inject(OFFLINE_AGGREGATE_INTENT_PROJECTOR, { optional: true });\n readonly #options = inject(OFFLINE_KIT_OPTIONS, { optional: true });\n #tail: Promise<void> = settledMutation();\n\n /** Enqueues one local replica critical section behind any in-flight mutation. */\n run<T>(operation: (repository: OfflineRepository) => Promise<T>): Promise<T> {\n const mutation = this.#tail.then(() => {\n if (!this.#repository) throw new Error('Offline repository is not configured.');\n const atomicMutation = this.#repository?.[OFFLINE_REPOSITORY_ATOMIC_MUTATION];\n return atomicMutation ? (atomicMutation.call(this.#repository, operation) as Promise<T>) : operation(this.#repository);\n });\n this.#tail = mutation.then(\n () => undefined,\n () => undefined,\n );\n return mutation;\n }\n\n /** Resolves after every currently queued replica mutation has settled. */\n async drain(): Promise<void> {\n await this.#tail;\n }\n\n /**\n * Calls the product aggregate-intent projector and validates scope, schema,\n * identity, and footprints. Throws before returning when the projector is\n * missing or the projection is unsafe to write.\n *\n * @param input - Authoritative base row, current localOnly rows, and remaining commands.\n */\n projectAggregateIntent(input: OfflineAggregateIntentProjectInput): OfflineAggregateIntentProjectResult {\n if (!this.#projector) {\n throw new Error('Offline aggregate intent projector is not configured.');\n }\n if (!this.#options) {\n throw new Error('Offline aggregate intent projector requires replica schema configuration.');\n }\n const projection = this.#projector.project(input);\n if (isOfflineAggregateIntentConflict(projection)) {\n if (input.trigger !== 'pull' || input.commands.length === 0 || projection.reason.length === 0) {\n throw new Error('Offline aggregate intent conflict is valid only for pending commands during pull.');\n }\n return projection;\n }\n this.#assertAggregateIntentProjection(input, projection);\n return projection;\n }\n\n #assertAggregateIntentProjection(input: OfflineAggregateIntentProjectInput, projection: OfflineAggregateIntentProjection): void {\n const expected = this.#expectedAggregate(input);\n const footprint = this.#localOnlyFootprint(input);\n this.#assertBaseProjection(input, projection, expected);\n this.#assertLocalOnlyProjection(input, expected.scope, footprint, projection);\n }\n\n #expectedAggregate(input: OfflineAggregateIntentProjectInput): {\n scope: OfflineScope | null;\n sourceKey: string | null;\n commandIdentity: OfflineCommandIdentity | null;\n } {\n const command = input.commands[0] ?? null;\n const base = input.baseRow;\n const local = input.localOnlyRows[0] ?? null;\n const scope = base\n ? { userId: base.userId, scopeId: base.scopeId }\n : command\n ? { userId: command.userId, scopeId: command.scopeId }\n : local\n ? { userId: local.userId, scopeId: local.scopeId }\n : null;\n return {\n scope,\n sourceKey: base?.sourceKey ?? command?.sourceKey ?? null,\n commandIdentity: command?.identity ?? null,\n };\n }\n\n #assertBaseProjection(\n input: OfflineAggregateIntentProjectInput,\n projection: OfflineAggregateIntentProjection,\n expected: {\n scope: OfflineScope | null;\n sourceKey: string | null;\n commandIdentity: OfflineCommandIdentity | null;\n },\n ): void {\n const remaining = input.commands;\n const base = input.baseRow;\n if (remaining.length === 0) {\n if (base?.confirmedValues == null) {\n if (projection.baseRow !== null) {\n throw new Error('Offline aggregate intent projector must remove a base row whose confirmedValues are null.');\n }\n return;\n }\n this.#assertBaseRowIdentity(expected, projection.baseRow, base);\n if (!sameJson(projection.baseRow!.values, base.confirmedValues)) {\n throw new Error('Offline aggregate intent projector must restore confirmed values when no commands remain.');\n }\n if (projection.baseRow!.syncState !== 'confirmed' || (projection.baseRow!.visibility ?? 'present') !== 'present') {\n throw new Error('Offline aggregate intent projector must restore a confirmed present base row when no commands remain.');\n }\n return;\n }\n if (!projection.baseRow) {\n throw new Error('Offline aggregate intent projector must return a base row while pending commands remain.');\n }\n this.#assertBaseRowIdentity(expected, projection.baseRow, base);\n const last = remaining.at(-1)!;\n if (projection.baseRow.syncState !== 'pending') {\n throw new Error('Offline aggregate intent projector must keep a pending base row while commands remain.');\n }\n const expectedVisibility = last.replicaMutation === 'delete' ? 'pending_delete' : 'present';\n if ((projection.baseRow.visibility ?? 'present') !== expectedVisibility) {\n throw new Error('Offline aggregate intent projector must match remaining replica visibility.');\n }\n }\n\n #assertBaseRowIdentity(\n expected: {\n scope: OfflineScope | null;\n sourceKey: string | null;\n commandIdentity: OfflineCommandIdentity | null;\n },\n row: OfflineReplicaRow | null,\n inputBase: OfflineReplicaRow | null,\n ): void {\n if (!row || !expected.scope || !expected.sourceKey) {\n throw new Error('Offline aggregate intent projector base row must keep the aggregate identity.');\n }\n const schema = this.#entitySchema(expected.sourceKey);\n if (schema.identity.kind === 'localOnly') {\n throw new Error(`Offline aggregate intent projector cannot rematerialize localOnly source \"${expected.sourceKey}\".`);\n }\n if (row.userId !== expected.scope.userId || row.scopeId !== expected.scope.scopeId || row.sourceKey !== expected.sourceKey) {\n throw new Error('Offline aggregate intent projector base row must use the current scope and source.');\n }\n if (inputBase) {\n if (!sameJson(row.confirmedValues, inputBase.confirmedValues) || row.serverRevision !== inputBase.serverRevision) {\n throw new Error('Offline aggregate intent projector base row must keep confirmedValues.');\n }\n if (canonicalOfflineReplicaIdentity(row.identity) !== canonicalOfflineReplicaIdentity(inputBase.identity)) {\n throw new Error('Offline aggregate intent projector base row must keep the aggregate identity.');\n }\n return;\n }\n if (row.confirmedValues !== null) {\n throw new Error('Offline aggregate intent projector base row must keep confirmedValues.');\n }\n if (!expected.commandIdentity || !commandIdentityMatchesReplicaRow(schema, row, expected.commandIdentity)) {\n throw new Error('Offline aggregate intent projector base row must keep the aggregate identity.');\n }\n }\n\n #assertLocalOnlyProjection(\n input: OfflineAggregateIntentProjectInput,\n scope: OfflineScope | null,\n footprint: ReadonlySet<string>,\n projection: OfflineAggregateIntentProjection,\n ): void {\n const currentByKey = new Map(\n input.localOnlyRows.map((row) => [canonicalOfflineReplicaRowKey(this.#entitySchema(row.sourceKey), row), row] as const),\n );\n const putRows = projection.putLocalOnlyRows ?? [];\n const removeRows = projection.removeLocalOnlyRows ?? [];\n const seen = new Set<string>();\n for (const row of putRows) {\n const key = this.#assertLocalOnlyMutation(scope, footprint, row);\n if (seen.has(key)) throw new Error(`Offline aggregate intent projector contains duplicate localOnly row ${key}.`);\n const current = currentByKey.get(key);\n if (!sameJson(row.confirmedValues, current?.confirmedValues ?? null)) {\n throw new Error('Offline aggregate intent projector localOnly rows must keep confirmedValues.');\n }\n seen.add(key);\n }\n for (const row of removeRows) {\n const key = this.#assertLocalOnlyMutation(scope, footprint, row);\n if (seen.has(key)) throw new Error(`Offline aggregate intent projector contains duplicate localOnly row ${key}.`);\n seen.add(key);\n }\n if (seen.size !== footprint.size) {\n throw new Error('Offline aggregate intent projector must cover every localOnly footprint exactly once.');\n }\n }\n\n #assertLocalOnlyMutation(scope: OfflineScope | null, footprint: ReadonlySet<string>, row: OfflineReplicaRowKey): string {\n const schema = this.#entitySchema(row.sourceKey);\n if (schema.identity.kind !== 'localOnly') {\n throw new Error(`Offline aggregate intent projector may only mutate localOnly source \"${row.sourceKey}\".`);\n }\n if (!scope || row.userId !== scope.userId || row.scopeId !== scope.scopeId || row.identity.kind !== 'local') {\n throw new Error('Offline aggregate intent projector rows must use the current scope and local identity.');\n }\n const key = canonicalOfflineReplicaRowKey(schema, row);\n if (!footprint.has(key)) {\n throw new Error(`Offline aggregate intent projector changed undeclared localOnly row ${key}.`);\n }\n return key;\n }\n\n #localOnlyFootprint(input: OfflineAggregateIntentProjectInput): Set<string> {\n const keys = new Set<string>();\n for (const row of input.localOnlyRows) {\n keys.add(canonicalOfflineReplicaRowKey(this.#entitySchema(row.sourceKey), row));\n }\n for (const command of input.commands) {\n for (const key of commandFootprintKeys(command)) {\n keys.add(canonicalOfflineReplicaRowKey(this.#entitySchema(key.sourceKey), key));\n }\n }\n return keys;\n }\n\n #entitySchema(sourceKey: string): OfflineReplicaEntitySchema<Record<string, unknown>> {\n const schema = this.#options?.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);\n if (!schema) throw new Error(`Unknown offline replica source key \"${sourceKey}\".`);\n return schema;\n }\n}\n\n/** Declared localOnly keys persisted on one Outbox command. */\nexport function commandFootprintKeys(command: Pick<OfflineCommand, 'localOnlyFootprint'>): readonly OfflineReplicaRowKey[] {\n return command.localOnlyFootprint ?? [];\n}\n\nfunction sameJson(left: unknown, right: unknown): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n","import { inject, Injectable } from '@angular/core';\nimport { isOfflineAggregateIntentConflict, offlineAggregateIntentMutations } from './offline-aggregate-intent-projector';\nimport { OFFLINE_COMMAND_HOOKS } from './offline-command-hooks';\nimport { OFFLINE_KIT_OPTIONS } from './offline-kit-options';\nimport { offlineCommandWithBaseRevision } from './offline-command-executor';\nimport { commandFootprintKeys, OfflineReplicaMutationCoordinator } from './offline-replica-mutation-coordinator';\nimport {\n OFFLINE_REPLICA_PROJECTOR,\n OFFLINE_REPLICA_PULLER,\n type OfflineReplicaChange,\n type OfflineReplicaPullPage,\n type OfflineReplicaReconciliationTarget,\n} from './offline-replica-puller';\nimport {\n canonicalOfflineCommandIdentity,\n commandIdentityFromReplicaIdentity,\n commandIdentityMatchesReplicaRow,\n offlineGeneratedReplicaIdentity,\n offlineNaturalReplicaIdentity,\n} from './offline-identity';\nimport {\n canonicalOfflineRemoteIdentity,\n normalizeOfflineNaturalKey,\n offlineNaturalKeyFromValues,\n projectOfflineReplicaValues,\n sha256OfflineReplicaSchema,\n type OfflineReplicaRemoteIdentity,\n type OfflineReplicaEntitySchema,\n} from './offline-replica-schema';\nimport {\n OFFLINE_REPOSITORY,\n canonicalOfflineReplicaRowKey,\n type OfflineCommand,\n type OfflineReplicaRow,\n type OfflineReplicaRowKey,\n type OfflineScope,\n} from './offline-repository';\n\ntype CollapsedOfflineReplicaChange = OfflineReplicaChange & {\n /** Last position in this page at which each command id was acknowledged. */\n acknowledgementOrdinals: Readonly<Record<string, number>>;\n /** Position of the authoritative last change retained by the collapse. */\n collapsedOrdinal: number;\n};\n\n/**\n * Pull handshake reported a replica schema version/hash that does not match the local Kit schema.\n *\n * Prefer `instanceof` (or {@link OfflineReplicaSchemaMismatchError.code}) over English message text.\n */\nexport class OfflineReplicaSchemaMismatchError extends Error {\n /** Stable machine-readable discriminator for fatal pull classification (pre- and post-send). */\n static readonly code = 'OFFLINE_REPLICA_SCHEMA_MISMATCH' as const;\n\n readonly code = OfflineReplicaSchemaMismatchError.code;\n\n constructor(\n readonly clientVersion: number,\n readonly clientHash: string,\n readonly serverVersion: number,\n readonly serverHash: string,\n ) {\n super(`Offline replica schema mismatch: client=${clientVersion}/${clientHash}, server=${serverVersion}/${serverHash}.`);\n this.name = 'OfflineReplicaSchemaMismatchError';\n }\n}\n\n/** Pulls authoritative server deltas into one durable local replica partition. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineReplicaPullService {\n readonly #repository = inject(OFFLINE_REPOSITORY);\n readonly #options = inject(OFFLINE_KIT_OPTIONS);\n readonly #puller = inject(OFFLINE_REPLICA_PULLER);\n readonly #projector = inject(OFFLINE_REPLICA_PROJECTOR, { optional: true });\n readonly #hooks = inject(OFFLINE_COMMAND_HOOKS);\n readonly #replicaMutations = inject(OfflineReplicaMutationCoordinator);\n #schemaHash: Promise<string> | null = null;\n\n async pull(scope: OfflineScope): Promise<void> {\n if (this.#options.mode === 'readCacheOnly') return;\n const storageSchemaHash = await (this.#schemaHash ??= sha256OfflineReplicaSchema(this.#options.replicaSchema));\n const wireProtocol = this.#options.wireProtocol ?? {\n version: this.#options.replicaSchema.version,\n hash: storageSchemaHash,\n };\n let persistedCursor = (await this.#repository.getReplicaCursor(scope))?.cursor ?? '';\n let requestCursor = persistedCursor;\n let rebaselinePending = false;\n\n for (;;) {\n const reconciliationTargets = await this.#reconciliationTargets(scope);\n const reconciliationTargetsById = new Map(reconciliationTargets.map((target) => [target.commandId, target] as const));\n const page = await this.#puller.pull({\n scope,\n cursor: requestCursor,\n schemaVersion: wireProtocol.version,\n schemaHash: wireProtocol.hash,\n reconciliationTargets,\n });\n this.#assertPullPage(page);\n this.#assertHandshake(page.schemaVersion, page.schemaHash, wireProtocol);\n if (page.hasMore && page.nextCursor === requestCursor) {\n throw new Error(`Offline replica pull cursor did not advance for scope ${scope.userId}:${scope.scopeId}.`);\n }\n if (page.changes.length === 0 && !page.hasMore && page.nextCursor === requestCursor && !rebaselinePending) {\n return;\n }\n if (page.rebaselineRequired && page.changes.length === 0 && !page.hasMore) {\n throw new Error('Offline replica rebaseline marker must lead to a snapshot page.');\n }\n if (page.rebaselineRequired && page.changes.length === 0 && page.hasMore) {\n rebaselinePending = true;\n requestCursor = page.nextCursor;\n continue;\n }\n\n const applied = await this.#replicaMutations.run(async (repository) => {\n const currentCursor = (await repository.getReplicaCursor(scope))?.cursor ?? '';\n if (currentCursor !== persistedCursor) return currentCursor;\n const scopeCommands = await repository.getCommands(scope);\n const userCommands = repository.getCommandsForUser ? await repository.getCommandsForUser(scope.userId) : scopeCommands;\n const changes = this.#collapseChanges(page.changes);\n const projection = await this.#projector?.project({\n scope,\n changes,\n });\n this.#assertProjection(scope, projection);\n const putRows: OfflineReplicaRow[] = [];\n const removeRows: OfflineReplicaRowKey[] = [];\n const putCommands = new Map<string, OfflineCommand>();\n const removeCommandIds = new Set<string>();\n const rematerializeAfter: OfflineCommand[] = [];\n if (rebaselinePending || page.rebaselineRequired) {\n removeRows.push(...(await this.#confirmedRowsForRebaseline(scope, userCommands)));\n }\n\n for (const change of changes) {\n const schema = this.#entitySchema(change.sourceKey);\n const commands = schema.scope === 'user' ? userCommands : scopeCommands;\n const acknowledged = (change.acknowledgedCommandIds ?? [])\n .map((commandId) => {\n const command = commands.find((candidate) => candidate.commandId === commandId);\n if (!command) return null;\n if (command.sourceKey !== change.sourceKey) {\n throw new Error(`Acknowledged command \"${commandId}\" does not target \"${change.sourceKey}\".`);\n }\n const requested = reconciliationTargetsById.get(commandId);\n if (command.state === 'awaiting_pull') {\n if (!requested) {\n throw new Error(`Acknowledged command \"${commandId}\" was not requested for reconciliation on this pull page.`);\n }\n const schema = this.#entitySchema(change.sourceKey);\n if (\n canonicalOfflineRemoteIdentity(schema, requested.identity) !==\n canonicalOfflineRemoteIdentity(schema, this.#identity(change))\n ) {\n throw new Error(`Acknowledged command \"${commandId}\" does not match the requested remote identity.`);\n }\n }\n return command;\n })\n .filter((command): command is OfflineCommand => command !== null);\n const acknowledgedIdentities = new Set(acknowledged.map((command) => canonicalOfflineCommandIdentity(command.identity)));\n if (acknowledgedIdentities.size > 1) {\n throw new Error(`Acknowledged commands for \"${change.sourceKey}\" target multiple replica identities.`);\n }\n const acknowledgedCommand = acknowledged[0];\n const acknowledgedScope = acknowledgedCommand\n ? { userId: acknowledgedCommand.userId, scopeId: acknowledgedCommand.scopeId }\n : scope;\n const acknowledgedRow = acknowledgedCommand\n ? await (this.#repository.getReplicaRowIncludingPendingDelete?.(\n acknowledgedScope,\n change.sourceKey,\n acknowledgedCommand.identity,\n ) ?? this.#repository.getReplicaRow(acknowledgedScope, change.sourceKey, acknowledgedCommand.identity))\n : null;\n if (acknowledgedCommand && !acknowledgedRow) {\n throw new Error(`Acknowledged command \"${acknowledgedCommand.commandId}\" has no local replica row.`);\n }\n const identity = this.#identity(change);\n const serverRow = await this.#repository.getReplicaRowByRemoteIdentity(scope, change.sourceKey, identity);\n if (\n acknowledgedRow &&\n serverRow &&\n !commandIdentityMatchesReplicaRow(schema, acknowledgedRow, commandIdentityFromReplicaIdentity(serverRow.identity))\n ) {\n if (identity.remoteId !== undefined) {\n throw new Error(`Server id ${String(identity.remoteId)} is already mapped to another local replica row.`);\n }\n throw new Error(`Remote identity for \"${change.sourceKey}\" is already mapped to another local replica row.`);\n }\n const existing = acknowledgedRow ?? serverRow;\n const related = existing\n ? commands.filter(\n (command) => command.sourceKey === change.sourceKey && commandIdentityMatchesReplicaRow(schema, existing, command.identity),\n )\n : [];\n const hasPending = related.length > 0;\n\n if (acknowledgedCommand) {\n this.#assertIdentityAssignment(schema, existing!, identity);\n this.#applyAcknowledgement(change, existing!, related, putRows, removeRows, putCommands, removeCommandIds, rematerializeAfter);\n continue;\n }\n\n if (change.deleted) {\n if (!existing) continue;\n if (!hasPending) {\n removeRows.push({ ...existing, identity: existing.identity });\n continue;\n }\n putRows.push({\n ...existing,\n confirmedValues: null,\n serverRevision: change.serverRevision,\n syncState: 'conflict',\n fetchedAt: Date.now(),\n });\n for (const command of related) {\n putCommands.set(command.commandId, { ...command, state: 'conflict', retryAt: null, lastErrorCode: 'remote_deleted' });\n }\n rematerializeAfter.push(related[0]!);\n continue;\n }\n\n const confirmedValues = this.#validatedValues(schema, change);\n if (!existing) {\n putRows.push({\n ...scope,\n sourceKey: change.sourceKey,\n identity:\n schema.identity.kind === 'naturalKey'\n ? offlineNaturalReplicaIdentity(schema, confirmedValues)\n : offlineGeneratedReplicaIdentity(crypto.randomUUID(), identity.remoteId ?? null),\n values: confirmedValues,\n confirmedValues,\n serverRevision: change.serverRevision,\n fetchedAt: Date.now(),\n syncState: 'confirmed',\n });\n continue;\n }\n\n const remaining = related.filter((command) => !removeCommandIds.has(command.commandId));\n const confirmedRow: OfflineReplicaRow = {\n ...existing,\n confirmedValues,\n serverRevision: change.serverRevision,\n fetchedAt: Date.now(),\n values: remaining.length > 0 ? existing.values : confirmedValues,\n syncState: remaining.length > 0 ? 'pending' : 'confirmed',\n };\n putRows.push(confirmedRow);\n if (remaining.length > 0) rematerializeAfter.push(remaining[0]!);\n for (const command of remaining) {\n putCommands.set(command.commandId, offlineCommandWithBaseRevision(command, change.serverRevision));\n }\n }\n\n const confirmedAndProjected = this.#mergeRowMutations([\n { putRows, removeRows },\n { putRows: projection?.putRows ?? [], removeRows: projection?.removeRows ?? [] },\n ]);\n const rematerialized = await this.#rematerializePendingAggregates(\n scope,\n userCommands,\n scopeCommands,\n confirmedAndProjected,\n putCommands,\n removeCommandIds,\n rematerializeAfter,\n );\n const finalRows = this.#mergeRowMutations([confirmedAndProjected, rematerialized]);\n const removedCommands = [...removeCommandIds]\n .map(\n (commandId) =>\n userCommands.find((command) => command.commandId === commandId) ??\n scopeCommands.find((command) => command.commandId === commandId),\n )\n .filter((command): command is OfflineCommand => command != null);\n await repository.transactReplica({\n putRows: finalRows.putRows,\n removeRows: finalRows.removeRows,\n putCommands: [...putCommands.values()],\n removeCommandIds: [...removeCommandIds],\n putCursors: [{ ...scope, cursor: page.nextCursor }],\n });\n await Promise.all(removedCommands.map((command) => this.#hooks.onCommandRemoved?.(command).catch(() => undefined)));\n return page.nextCursor;\n });\n if (applied !== page.nextCursor) {\n persistedCursor = applied;\n requestCursor = applied;\n rebaselinePending = false;\n continue;\n }\n persistedCursor = page.nextCursor;\n requestCursor = page.nextCursor;\n rebaselinePending = false;\n if (!page.hasMore) return;\n }\n }\n\n async #reconciliationTargets(scope: OfflineScope): Promise<OfflineReplicaReconciliationTarget[]> {\n const commands = (await this.#repository.getCommands(scope)).filter((command) => command.state === 'awaiting_pull');\n const targets: OfflineReplicaReconciliationTarget[] = [];\n for (const command of commands) {\n const row =\n (await this.#repository.getReplicaRowIncludingPendingDelete?.(scope, command.sourceKey, command.identity)) ??\n (await this.#repository.getReplicaRow(scope, command.sourceKey, command.identity));\n if (!row) throw new Error(`Awaiting-pull command \"${command.commandId}\" has no replica row.`);\n const identity =\n command.reconciliationIdentity ??\n (row.identity.kind === 'generated'\n ? row.identity.remoteId === null\n ? null\n : { remoteId: row.identity.remoteId }\n : row.identity.kind === 'natural'\n ? { naturalKey: row.identity.naturalKey }\n : null);\n if (!identity) throw new Error(`Awaiting-pull command \"${command.commandId}\" has no remote identity.`);\n canonicalOfflineRemoteIdentity(this.#entitySchema(command.sourceKey), identity);\n targets.push({ commandId: command.commandId, operation: command.operation, sourceKey: command.sourceKey, identity });\n }\n return targets;\n }\n\n async #confirmedRowsForRebaseline(scope: OfflineScope, commands: readonly OfflineCommand[]): Promise<OfflineReplicaRowKey[]> {\n const preserved = new Set(\n commands.flatMap((command) => {\n const identity =\n command.identity.kind === 'generated'\n ? offlineGeneratedReplicaIdentity(command.identity.localId, null)\n : { kind: 'natural' as const, naturalKey: command.identity.naturalKey };\n return [this.#rowKey({ ...command, identity }), ...commandFootprintKeys(command).map((key) => this.#rowKey(key))];\n }),\n );\n const rows = (\n await Promise.all(this.#options.replicaSchema.entities.map((entity) => this.#repository.getReplicaRows(scope, entity.sourceKey)))\n ).flat();\n return rows.filter((row) => row.syncState === 'confirmed' && !preserved.has(this.#rowKey(row)));\n }\n\n #rowKey(row: OfflineReplicaRowKey): string {\n return canonicalOfflineReplicaRowKey(this.#entitySchema(row.sourceKey), row);\n }\n\n #mergeRowMutations(\n layers: readonly {\n putRows: readonly OfflineReplicaRow[];\n removeRows: readonly OfflineReplicaRowKey[];\n }[],\n ): { putRows: OfflineReplicaRow[]; removeRows: OfflineReplicaRowKey[] } {\n const mutations = new Map<string, { kind: 'put'; row: OfflineReplicaRow } | { kind: 'remove'; row: OfflineReplicaRowKey }>();\n for (const layer of layers) {\n for (const row of layer.removeRows) mutations.set(this.#rowKey(row), { kind: 'remove', row });\n for (const row of layer.putRows) mutations.set(this.#rowKey(row), { kind: 'put', row });\n }\n const putRows: OfflineReplicaRow[] = [];\n const removeRows: OfflineReplicaRowKey[] = [];\n for (const mutation of mutations.values()) {\n if (mutation.kind === 'put') putRows.push(mutation.row);\n else removeRows.push(mutation.row);\n }\n return { putRows, removeRows };\n }\n\n #assertProjection(\n scope: OfflineScope,\n projection: { putRows?: readonly OfflineReplicaRow[]; removeRows?: readonly OfflineReplicaRowKey[] } | undefined,\n ): void {\n for (const row of [...(projection?.putRows ?? []), ...(projection?.removeRows ?? [])]) {\n const schema = this.#entitySchema(row.sourceKey);\n if (schema.identity.kind !== 'localOnly') {\n throw new Error(`Offline replica projector may only mutate localOnly source \"${row.sourceKey}\".`);\n }\n if (row.userId !== scope.userId || row.scopeId !== scope.scopeId || row.identity.kind !== 'local') {\n throw new Error('Offline replica projector rows must use the current scope and local identity.');\n }\n }\n }\n\n #assertPullPage(page: OfflineReplicaPullPage): void {\n if (typeof page.nextCursor !== 'string') {\n throw new Error('Offline replica pull page nextCursor must be a string.');\n }\n if (typeof page.hasMore !== 'boolean') {\n throw new Error('Offline replica pull page hasMore must be a boolean.');\n }\n if (!Array.isArray(page.changes)) {\n throw new Error('Offline replica pull page changes must be an array.');\n }\n if (page.rebaselineRequired !== undefined && typeof page.rebaselineRequired !== 'boolean') {\n throw new Error('Offline replica pull page rebaselineRequired must be a boolean when present.');\n }\n for (const [index, change] of page.changes.entries()) {\n this.#assertPullChange(change, index);\n }\n }\n\n async #rematerializePendingAggregates(\n scope: OfflineScope,\n userCommands: readonly OfflineCommand[],\n scopeCommands: readonly OfflineCommand[],\n currentRows: { putRows: readonly OfflineReplicaRow[]; removeRows: readonly OfflineReplicaRowKey[] },\n putCommands: Map<string, OfflineCommand>,\n removeCommandIds: ReadonlySet<string>,\n seeds: readonly OfflineCommand[],\n ): Promise<{ putRows: OfflineReplicaRow[]; removeRows: OfflineReplicaRowKey[] }> {\n const remaining = [...userCommands, ...scopeCommands]\n .filter((command, index, all) => all.findIndex((candidate) => candidate.commandId === command.commandId) === index)\n .filter((command) => !removeCommandIds.has(command.commandId))\n .map((command) => putCommands.get(command.commandId) ?? command);\n const affected = new Map<string, OfflineCommand>();\n for (const command of [...seeds, ...remaining]) {\n if (removeCommandIds.has(command.commandId) && !remaining.some((item) => this.#aggregateKey(item) === this.#aggregateKey(command))) {\n affected.set(this.#aggregateKey(command), command);\n continue;\n }\n if (!removeCommandIds.has(command.commandId) || seeds.some((seed) => seed.commandId === command.commandId)) {\n affected.set(this.#aggregateKey(command), command);\n }\n }\n const putRows: OfflineReplicaRow[] = [];\n const removeRows: OfflineReplicaRowKey[] = [];\n const overlay = new Map(currentRows.putRows.map((row) => [this.#rowKey(row), row] as const));\n const removed = new Set(currentRows.removeRows.map((row) => this.#rowKey(row)));\n for (const [key, seed] of affected) {\n const remainingForAggregate = remaining.filter((command) => this.#aggregateKey(command) === key);\n const existingConflict = remainingForAggregate.find((command) => command.state === 'conflict');\n const footprintCommands = [...remainingForAggregate, seed];\n const baseRow = await this.#overlayBaseRow(seed, overlay, removed);\n const persistedLocalOnlyRows = await this.#persistedLocalOnlyRows(footprintCommands);\n const localOnlyRows = await this.#overlayLocalOnlyRows(footprintCommands, overlay, removed);\n const projection = existingConflict\n ? { kind: 'conflict' as const, reason: existingConflict.lastErrorCode ?? 'remote_revision' }\n : this.#replicaMutations.projectAggregateIntent({\n baseRow,\n localOnlyRows,\n commands: remainingForAggregate,\n trigger: 'pull',\n incomingRevision: baseRow?.serverRevision ?? undefined,\n });\n if (isOfflineAggregateIntentConflict(projection)) {\n if (!baseRow) throw new Error('Offline aggregate conflict requires an authoritative base row.');\n putRows.push({ ...baseRow, values: baseRow.values, syncState: 'conflict' });\n for (const command of remainingForAggregate) {\n putCommands.set(command.commandId, {\n ...command,\n state: 'conflict',\n retryAt: null,\n lastErrorCode: projection.reason,\n });\n }\n const incomingByKey = new Map(localOnlyRows.map((row) => [this.#rowKey(row), row] as const));\n for (const previous of persistedLocalOnlyRows) {\n const incoming = incomingByKey.get(this.#rowKey(previous));\n putRows.push({\n ...(incoming ?? previous),\n values: previous.values,\n confirmedValues: incoming?.confirmedValues ?? null,\n syncState: 'conflict',\n visibility: previous.visibility,\n });\n }\n continue;\n }\n const mutations = offlineAggregateIntentMutations(projection, baseRow);\n putRows.push(...(mutations.putRows ?? []));\n removeRows.push(...(mutations.removeRows ?? []));\n }\n void scope;\n return { putRows, removeRows };\n }\n\n async #overlayBaseRow(\n command: OfflineCommand,\n overlay: ReadonlyMap<string, OfflineReplicaRow>,\n removed: ReadonlySet<string>,\n ): Promise<OfflineReplicaRow | null> {\n const schema = this.#entitySchema(command.sourceKey);\n const identity =\n command.identity.kind === 'generated'\n ? offlineGeneratedReplicaIdentity(command.identity.localId, null)\n : { kind: 'natural' as const, naturalKey: command.identity.naturalKey };\n const canonical = this.#rowKey({ ...command, identity });\n if (removed.has(canonical)) return null;\n const overlaid = [...overlay.values()].find(\n (row) => row.sourceKey === command.sourceKey && commandIdentityMatchesReplicaRow(schema, row, command.identity),\n );\n if (overlaid) return overlaid;\n const commandScope = { userId: command.userId, scopeId: command.scopeId };\n return (\n this.#repository.getReplicaRowIncludingPendingDelete?.(commandScope, command.sourceKey, command.identity) ??\n this.#repository.getReplicaRow(commandScope, command.sourceKey, command.identity)\n );\n }\n\n async #overlayLocalOnlyRows(\n commands: readonly OfflineCommand[],\n overlay: ReadonlyMap<string, OfflineReplicaRow>,\n removed: ReadonlySet<string>,\n ): Promise<OfflineReplicaRow[]> {\n const keys = new Map<string, OfflineReplicaRowKey>();\n for (const command of commands) {\n for (const key of commandFootprintKeys(command)) keys.set(this.#rowKey(key), key);\n }\n const rows: OfflineReplicaRow[] = [];\n for (const [canonical, key] of keys) {\n if (removed.has(canonical)) continue;\n const overlaid = overlay.get(canonical);\n if (overlaid) {\n rows.push(overlaid);\n continue;\n }\n const rowScope = { userId: key.userId, scopeId: key.scopeId };\n const row =\n (await this.#repository.getReplicaRowIncludingPendingDelete?.(rowScope, key.sourceKey, key.identity)) ??\n (await this.#repository.getReplicaRow(rowScope, key.sourceKey, key.identity));\n if (row) rows.push(row);\n }\n return rows;\n }\n\n async #persistedLocalOnlyRows(commands: readonly OfflineCommand[]): Promise<OfflineReplicaRow[]> {\n return this.#overlayLocalOnlyRows(commands, new Map(), new Set());\n }\n\n #aggregateKey(command: OfflineCommand): string {\n const schema = this.#entitySchema(command.sourceKey);\n const partition = schema.scope === 'user' ? 'user' : `partition:${command.scopeId}`;\n return `${command.userId}:${partition}:${command.sourceKey}:${canonicalOfflineCommandIdentity(command.identity)}`;\n }\n\n #assertPullChange(change: unknown, index: number): void {\n const label = `Offline replica pull page changes[${index}]`;\n if (!isPlainObject(change)) {\n throw new Error(`${label} must be a plain object.`);\n }\n if (typeof change['sourceKey'] !== 'string') {\n throw new Error(`${label}.sourceKey must be a string.`);\n }\n if (typeof change['deleted'] !== 'boolean') {\n throw new Error(`${label}.deleted must be a boolean.`);\n }\n const schema = this.#entitySchema(change['sourceKey']);\n if (schema.identity.kind === 'generated') {\n const remoteId = change['remoteId'];\n const validInteger = typeof remoteId === 'number' && Number.isSafeInteger(remoteId) && remoteId > 0;\n const validText = typeof remoteId === 'string' && remoteId.length > 0;\n if (schema.identity.affinity === 'INTEGER' ? !validInteger : !validText) {\n throw new Error(`${label}.remoteId must be a valid generated remote id.`);\n }\n if (change['naturalKey'] !== undefined) {\n throw new Error(`${label}.naturalKey must be omitted for a generated entity.`);\n }\n }\n try {\n canonicalOfflineRemoteIdentity(schema, change as unknown as OfflineReplicaRemoteIdentity);\n } catch (error) {\n throw new Error(`${label} has invalid remote identity: ${error instanceof Error ? error.message : String(error)}`);\n }\n const revision = change['serverRevision'];\n if (typeof revision !== 'string' && (typeof revision !== 'number' || !Number.isFinite(revision))) {\n throw new Error(`${label}.serverRevision must be a string or number.`);\n }\n const acknowledgedCommandIds = change['acknowledgedCommandIds'];\n if (\n (acknowledgedCommandIds !== undefined && !Array.isArray(acknowledgedCommandIds)) ||\n (Array.isArray(acknowledgedCommandIds) &&\n acknowledgedCommandIds.some((commandId) => typeof commandId !== 'string' || commandId.length === 0))\n ) {\n throw new Error(`${label}.acknowledgedCommandIds must be an array of non-empty strings.`);\n }\n if (change['deleted']) {\n if (change['values'] !== null) {\n throw new Error(`${label} with deleted=true must have null values.`);\n }\n }\n }\n\n #assertHandshake(version: number, hash: string, expected: { readonly version: number; readonly hash: string }): void {\n if (version !== expected.version || hash !== expected.hash) {\n throw new OfflineReplicaSchemaMismatchError(expected.version, expected.hash, version, hash);\n }\n }\n\n #entitySchema(sourceKey: string): OfflineReplicaEntitySchema<Record<string, unknown>> {\n const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);\n if (!schema) throw new Error(`Unknown offline replica source key \"${sourceKey}\".`);\n return schema;\n }\n\n #validatedValues(schema: OfflineReplicaEntitySchema<Record<string, unknown>>, change: OfflineReplicaChange): unknown {\n if (change.values === null) {\n throw new Error(\n change.remoteId === undefined\n ? `Offline replica change \"${change.sourceKey}\" is missing values.`\n : `Offline replica change \"${change.sourceKey}\"/${String(change.remoteId)} is missing values.`,\n );\n }\n const values = projectOfflineReplicaValues(schema, change.values);\n if (schema.identity.kind === 'naturalKey') {\n const expected = offlineNaturalKeyFromValues(schema, values)!;\n const incoming = normalizeOfflineNaturalKey(schema, change.naturalKey!);\n if (\n canonicalOfflineRemoteIdentity(schema, { naturalKey: expected }) !==\n canonicalOfflineRemoteIdentity(schema, { naturalKey: incoming })\n ) {\n throw new Error(`Offline replica change \"${change.sourceKey}\" naturalKey does not match values.`);\n }\n }\n return values;\n }\n\n #collapseChanges(changes: readonly OfflineReplicaChange[]): CollapsedOfflineReplicaChange[] {\n const collapsed = new Map<string, CollapsedOfflineReplicaChange>();\n for (const [ordinal, change] of changes.entries()) {\n const schema = this.#entitySchema(change.sourceKey);\n const key = `${change.sourceKey}:${canonicalOfflineRemoteIdentity(schema, this.#identity(change))}`;\n const previous = collapsed.get(key);\n const acknowledgedCommandIds = [...new Set([...(previous?.acknowledgedCommandIds ?? []), ...(change.acknowledgedCommandIds ?? [])])];\n const acknowledgementOrdinals = { ...(previous?.acknowledgementOrdinals ?? {}) };\n for (const commandId of change.acknowledgedCommandIds ?? []) {\n acknowledgementOrdinals[commandId] = ordinal;\n }\n collapsed.set(key, {\n ...change,\n acknowledgedCommandIds,\n acknowledgementOrdinals,\n collapsedOrdinal: ordinal,\n });\n }\n return [...collapsed.values()];\n }\n\n #applyAcknowledgement(\n change: CollapsedOfflineReplicaChange,\n row: OfflineReplicaRow,\n related: readonly OfflineCommand[],\n putRows: OfflineReplicaRow[],\n removeRows: OfflineReplicaRowKey[],\n putCommands: Map<string, OfflineCommand>,\n removeCommandIds: Set<string>,\n rematerializeAfter: OfflineCommand[],\n ): void {\n const acknowledgedIds = new Set(change.acknowledgedCommandIds ?? []);\n const lastAcknowledgedIndex = related.reduce((last, command, index) => (acknowledgedIds.has(command.commandId) ? index : last), -1);\n if (lastAcknowledgedIndex < 0) {\n throw new Error(`Replica acknowledgement does not match the local aggregate outbox.`);\n }\n if (related.slice(0, lastAcknowledgedIndex + 1).some((command) => !acknowledgedIds.has(command.commandId))) {\n throw new Error(`Replica acknowledgement skipped an earlier aggregate command.`);\n }\n const lastAcknowledgedCommand = related[lastAcknowledgedIndex]!;\n const acknowledgementSuperseded = (change.acknowledgementOrdinals[lastAcknowledgedCommand.commandId] ?? -1) < change.collapsedOrdinal;\n const following = related\n .slice(lastAcknowledgedIndex + 1)\n .map((command) =>\n acknowledgementSuperseded || change.deleted\n ? { ...command, state: 'conflict' as const, retryAt: null, lastErrorCode: change.deleted ? 'remote_deleted' : 'remote_revision' }\n : offlineCommandWithBaseRevision(command, change.serverRevision),\n );\n for (const command of following) putCommands.set(command.commandId, command);\n for (const command of related.slice(0, lastAcknowledgedIndex + 1)) {\n removeCommandIds.add(command.commandId);\n }\n rematerializeAfter.push(lastAcknowledgedCommand);\n\n if (change.deleted) {\n if (following.length > 0) {\n putRows.push({\n ...row,\n confirmedValues: null,\n serverRevision: change.serverRevision,\n syncState: 'conflict',\n visibility: following.at(-1)!.replicaMutation === 'delete' ? 'pending_delete' : 'present',\n fetchedAt: Date.now(),\n });\n } else {\n removeRows.push({ ...row, identity: row.identity });\n }\n return;\n }\n\n const schema = this.#entitySchema(change.sourceKey);\n const confirmedValues = this.#validatedValues(schema, change);\n this.#assertIdentityAssignment(schema, row, this.#identity(change));\n putRows.push({\n ...row,\n identity: row.identity.kind === 'generated' ? { ...row.identity, remoteId: change.remoteId ?? row.identity.remoteId } : row.identity,\n values: following.length > 0 ? row.values : confirmedValues,\n confirmedValues,\n serverRevision: change.serverRevision,\n fetchedAt: Date.now(),\n syncState: following.length > 0 ? (acknowledgementSuperseded ? 'conflict' : 'pending') : 'confirmed',\n visibility: following.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',\n });\n }\n\n #identity(change: OfflineReplicaChange): OfflineReplicaRemoteIdentity {\n return change.remoteId !== undefined ? { remoteId: change.remoteId } : { naturalKey: change.naturalKey! };\n }\n\n #assertIdentityAssignment(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n row: OfflineReplicaRow,\n incoming: OfflineReplicaRemoteIdentity,\n ): void {\n if (schema.identity.kind === 'generated') {\n const remoteId = incoming.remoteId!;\n if (row.identity.kind !== 'generated') {\n throw new Error(`Replica generated identity is required for \"${schema.sourceKey}\".`);\n }\n if (row.identity.remoteId !== null && row.identity.remoteId !== remoteId) {\n throw new Error(`Replica remote id is immutable: current=${String(row.identity.remoteId)}, incoming=${String(remoteId)}.`);\n }\n return;\n }\n const current = row.identity.kind === 'natural' ? row.identity.naturalKey : offlineNaturalKeyFromValues(schema, row.values);\n if (\n current !== null &&\n canonicalOfflineRemoteIdentity(schema, { naturalKey: current }) !== canonicalOfflineRemoteIdentity(schema, incoming)\n ) {\n throw new Error(`Replica naturalKey is immutable for \"${schema.sourceKey}\".`);\n }\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n","import { computed, Injectable, signal } from '@angular/core';\nimport { App } from '@capacitor/app';\nimport type { PluginListenerHandle } from '@capacitor/core';\nimport { Network } from '@capacitor/network';\n\nexport type OfflineNetworkState = 'online' | 'offline' | 'unverified';\n\n/** transport不能(status=0)だけをlocal replica fallback対象にし、HTTPエラーは隠さない。 */\nexport function isOfflineFallbackError(error: unknown): boolean {\n return typeof error === 'object' && error !== null && (error as { status?: unknown }).status === 0;\n}\n\n/** Combines operating-system connectivity with observed API reachability. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineNetworkService {\n readonly #osConnected = signal<boolean | null>(null);\n readonly #apiReachable = signal<boolean | null>(null);\n readonly #listeners: PluginListenerHandle[] = [];\n #initialized = false;\n\n readonly state = computed<OfflineNetworkState>(() => {\n if (this.#osConnected() === false || this.#apiReachable() === false) return 'offline';\n if (this.#osConnected() === true && this.#apiReachable() === true) return 'online';\n return 'unverified';\n });\n readonly connected = computed(() => this.state() !== 'offline');\n\n async initialize(): Promise<void> {\n if (this.#initialized) return;\n this.#initialized = true;\n this.#osConnected.set((await Network.getStatus()).connected);\n this.#listeners.push(\n await Network.addListener('networkStatusChange', ({ connected }) => {\n this.#osConnected.set(connected);\n this.#apiReachable.set(connected ? null : false);\n }),\n await App.addListener('appStateChange', ({ isActive }) => {\n if (isActive) void this.#refreshOsStatus();\n }),\n );\n }\n\n markApiSuccess(): void {\n this.#apiReachable.set(true);\n }\n\n markApiFailure(): void {\n this.#apiReachable.set(false);\n }\n\n async #refreshOsStatus(): Promise<void> {\n this.#osConnected.set((await Network.getStatus()).connected);\n }\n}\n","import { inject, Injectable } from '@angular/core';\nimport { OFFLINE_KIT_OPTIONS } from './offline-kit-options';\n\n/** Raised when a new durable mutation reaches Kit after mutation persistence was closed. */\nexport class OfflineMutationPersistenceDisabledError extends Error {\n constructor() {\n super('Offline mutation persistence was disabled before the mutation could be accepted.');\n this.name = 'OfflineMutationPersistenceDisabledError';\n }\n}\n\n/** Product-independent lease gate around every new durable Outbox command. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineMutationAdmissionService {\n readonly #options = inject(OFFLINE_KIT_OPTIONS);\n #accepting = this.#options.mutationPersistence === undefined;\n #active = 0;\n #idle: Promise<void> | null = null;\n #resolveIdle: (() => void) | null = null;\n\n get accepting(): boolean {\n return this.#accepting;\n }\n\n async run<T>(operation: () => Promise<T>): Promise<T> {\n if (!this.#accepting) throw new OfflineMutationPersistenceDisabledError();\n this.#active += 1;\n return new Promise<T>((resolve) => resolve(operation())).finally(() => this.#release());\n }\n\n open(): void {\n this.#accepting = true;\n }\n\n async close(): Promise<void> {\n this.#accepting = false;\n if (this.#active === 0) return;\n if (!this.#idle) {\n this.#idle = new Promise<void>((resolve) => {\n this.#resolveIdle = resolve;\n });\n }\n return this.#idle;\n }\n\n #release(): void {\n this.#active -= 1;\n if (this.#active !== 0) return;\n this.#resolveIdle?.();\n this.#idle = null;\n this.#resolveIdle = null;\n }\n}\n","import { computed, effect, ErrorHandler, inject, Injectable, InjectionToken, signal, untracked } from '@angular/core';\nimport {\n OFFLINE_COMMAND_EXECUTOR,\n OFFLINE_SYNC_CONTEXT,\n offlineCommandLookupIdentity,\n offlineCommandTargetFromReplicaRow,\n offlineCommandWithBaseRevision,\n type OfflineCommandResult,\n type EnqueueOfflineCommandIdentity,\n type OfflineSyncSession,\n} from './offline-command-executor';\nimport { OFFLINE_COMMAND_HOOKS } from './offline-command-hooks';\nimport { OFFLINE_KIT_OPTIONS } from './offline-kit-options';\nimport { OfflineNetworkService } from './offline-network.service';\nimport { OfflineMutationAdmissionService } from './offline-mutation-admission.service';\nimport { OfflineReplicaPullService, OfflineReplicaSchemaMismatchError } from './offline-replica-pull.service';\nimport { isOfflineAggregateIntentConflict, offlineAggregateIntentMutations } from './offline-aggregate-intent-projector';\nimport { commandFootprintKeys, OfflineReplicaMutationCoordinator } from './offline-replica-mutation-coordinator';\nimport type {\n OfflineCommand,\n OfflinePullAttention,\n OfflinePullAttentionReason,\n OfflineReplicaSyncState,\n OfflineReplicaRow,\n OfflineReplicaRowKey,\n OfflineReplicaTransaction,\n OfflineRepository,\n OfflineScope,\n} from './offline-repository';\nimport { canonicalOfflineReplicaRowKey, OFFLINE_REPOSITORY } from './offline-repository';\nimport {\n canonicalOfflinePrincipalId,\n canonicalOfflineCommandIdentity,\n commandIdentityFromReplicaIdentity,\n commandIdentityMatchesReplicaRow,\n offlineGeneratedReplicaIdentity,\n type OfflineCommandIdentity,\n type OfflinePrincipalId,\n} from './offline-identity';\nimport {\n assertOfflineReplicaGeneratedRemoteId,\n canonicalOfflineRemoteIdentity,\n offlineNaturalKeyFromValues,\n type OfflineGeneratedRemoteId,\n type OfflineReplicaEntitySchema,\n} from './offline-replica-schema';\n\n/** Aggregate synchronization state exposed to application UI. */\nexport type OfflineSyncState = 'idle' | 'pending' | 'syncing' | 'attention';\n\n/** Mutation appended atomically to the outbox; Kit rematerializes optimistic replica state. */\nexport interface EnqueueOfflineCommand<T = unknown> {\n scopeId: string;\n aggregateType: string;\n identity: EnqueueOfflineCommandIdentity;\n operation: string;\n payload: T;\n /**\n * Optimistically hides an existing DB row while retaining its identity and\n * confirmed baseline for durable replay, conflict handling, and discard.\n */\n replicaMutation?: 'upsert' | 'delete';\n baseRevision?: string | number | null;\n /** Declared localOnly projection rows this intent may create, update, or remove. */\n localOnlyFootprint?: readonly OfflineReplicaRowKey[];\n}\n\n/**\n * A command prepared from replica reads while enqueue/ACK projection is\n * serialized. Kit rematerializes the aggregate; the prepare callback must not\n * supply replica row images as independent truth.\n */\nexport interface PreparedOfflineCommand<T = unknown> {\n request: EnqueueOfflineCommand<T>;\n}\n\nexport interface PreparedOfflineBatchOptions {\n flush?: boolean;\n /** Product identity/scope lease asserted after all async preparation and immediately before the durable commit. */\n assertCurrent?: () => void;\n}\n\n/** Validated Outbox command ready for a rematerialized replica commit. */\ninterface MaterializedOfflineEnqueue {\n command: OfflineCommand;\n /** Identity-bearing base row used when the aggregate does not yet exist locally. */\n seedBaseRow?: OfflineReplicaRow | null;\n}\n\n/** Raised before persistence when an outbox payload is not losslessly JSON serializable. */\nexport class OfflinePayloadValidationError extends Error {\n constructor(message = 'Offline command payload must contain only JSON values') {\n super(message);\n this.name = 'OfflinePayloadValidationError';\n }\n}\n\n/** Raised before persistence when retaining another command would exceed the configured durable Outbox capacity. */\nexport class OfflineOutboxCapacityError extends Error {\n constructor(\n readonly reason: 'command_count' | 'serialized_bytes',\n readonly currentCommands: number,\n readonly currentBytes: number,\n ) {\n super(\n reason === 'command_count'\n ? 'Offline Outbox command limit reached; synchronize or discard a pending command before continuing'\n : 'Offline Outbox storage limit reached; synchronize or discard a pending command before continuing',\n );\n this.name = 'OfflineOutboxCapacityError';\n }\n}\n\n/** Raised when a discard could race a request whose server commit is unknown. */\nexport class OfflineCommandInFlightError extends Error {\n constructor(readonly commandIds: readonly string[]) {\n super('Offline commands are being synchronized and cannot be discarded until their server result is known');\n this.name = 'OfflineCommandInFlightError';\n }\n}\n\nconst MAX_PARALLEL_AGGREGATES = 3;\nconst MAX_BACKOFF_MS = 60 * 60 * 1000;\nconst POST_SEND_PULL_RETRY_MS = 1_000;\nconst DEFAULT_MAX_OUTBOX_COMMANDS_PER_USER = 1_000;\nconst DEFAULT_MAX_OUTBOX_BYTES_PER_USER = 10 * 1024 * 1024;\n\n/** Injectable `[0, 1)` source used by equal-jitter retry delay. Defaults to `Math.random`. */\nexport const OFFLINE_RETRY_RANDOM = new InjectionToken<() => number>('OFFLINE_RETRY_RANDOM', {\n factory: () => Math.random,\n});\n\n/**\n * Equal-jitter delay in `[⌊cap/2⌋, cap)` for exponential offline command backoff.\n * Keeps a positive lower bound (half the exponential cap) while still desynchronizing clients.\n *\n * @param attempts - Attempt count already recorded on the failed command (`>= 1` after a send claim).\n * @param random - Unit interval sample in `[0, 1)`.\n */\nexport function offlineRetryDelayMs(attempts: number, random: () => number = Math.random): number {\n const cap = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.max(0, attempts - 1));\n const unit = random();\n if (!(unit >= 0 && unit < 1)) {\n throw new Error('Offline retry random() must return a number in [0, 1).');\n }\n const half = cap / 2;\n return Math.floor(half + unit * half);\n}\n\n/** Maintains the optimistic local replica and synchronizes its durable outbox. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineSyncService {\n readonly #network = inject(OfflineNetworkService);\n readonly #mutationAdmission = inject(OfflineMutationAdmissionService);\n readonly #repository = inject(OFFLINE_REPOSITORY);\n readonly #executor = inject(OFFLINE_COMMAND_EXECUTOR);\n readonly #context = inject(OFFLINE_SYNC_CONTEXT);\n readonly #hooks = inject(OFFLINE_COMMAND_HOOKS);\n readonly #options = inject(OFFLINE_KIT_OPTIONS);\n readonly #pull = inject(OfflineReplicaPullService);\n readonly #replicaMutations = inject(OfflineReplicaMutationCoordinator);\n readonly #errorHandler = inject(ErrorHandler);\n readonly #retryRandom = inject(OFFLINE_RETRY_RANDOM);\n readonly #commands = signal<OfflineCommand[]>([]);\n readonly #pullAttentions = signal<OfflinePullAttention[]>([]);\n readonly #knownScopes = new Map<string, OfflineScope>();\n /** In-memory scheduling cache for scopes whose authoritative post-send pull has not completed yet. */\n readonly #pendingPullScopes = new Map<string, OfflineScope>();\n #activeUserId: OfflinePrincipalId | null = null;\n #flushPromise: Promise<void> | null = null;\n #partialFlushInFlight = false;\n #chainedFullFlush: Promise<void> | null = null;\n readonly #flushTransitions = new Set<Promise<void>>();\n #generation = 0;\n readonly #sendingTransitions = new Set<Promise<unknown>>();\n #retryTimer: ReturnType<typeof setTimeout> | null = null;\n /** When non-null, automatic flushes pull only foreground scopes plus Outbox scopes. */\n #foregroundScopePolicy: readonly string[] | null = null;\n #initialization: Promise<void> | null = null;\n #initialized = false;\n #lastCommandCreatedAt = 0;\n\n readonly pendingCommands = this.#commands.asReadonly();\n readonly pendingCount = computed(() => this.pendingCommands().length);\n readonly conflicts = computed(() => this.#commands().filter((command) => command.state === 'conflict'));\n /** Durable fatal-pull attentions for the active principal, restored across restart. */\n readonly pullAttentions = this.#pullAttentions.asReadonly();\n readonly syncState = computed<OfflineSyncState>(() => {\n if (this.#pullAttentions().length > 0) return 'attention';\n const commands = this.#commands();\n if (commands.some((command) => ['blocked_auth', 'rejected', 'conflict'].includes(command.state))) return 'attention';\n // Any non-sending ambiguous commit (including restart-normalized pending+unknown) needs attention.\n if (commands.some((command) => command.state !== 'sending' && command.serverCommitUnknown === true)) return 'attention';\n if (commands.some((command) => command.state === 'sending')) return 'syncing';\n return commands.length > 0 ? 'pending' : 'idle';\n });\n\n constructor() {\n effect(() => {\n const connected = this.#network.connected();\n // The network transition may be observed after an explicit flush has already\n // persisted a fatal pull attention. Do not let that stale transition restart\n // the intentionally stopped loop; auth/session refresh remains able to retry.\n const hasFatalPullAttention = untracked(() => this.#pullAttentions().length > 0);\n if (this.#initialized && connected && !hasFatalPullAttention) this.#flushInBackground();\n });\n }\n\n async initialize(options: { flush?: boolean } = {}): Promise<void> {\n const generation = this.#generation;\n if (!(await this.#restoreCurrentGeneration(generation))) return;\n if (options.flush !== false && this.#network.connected()) this.#flushInBackground();\n }\n\n #ensureInitialized(): Promise<void> {\n this.#initialization ??= this.#initializeOnce();\n return this.#initialization;\n }\n\n async #restoreCurrentGeneration(generation: number): Promise<boolean> {\n await this.#ensureInitialized();\n return this.#isCurrent(generation);\n }\n\n async #initializeOnce(): Promise<void> {\n await this.#repository.initialize();\n await this.#discoverScopes();\n const commands = await this.#readKnownCommands();\n await Promise.all(\n commands\n .filter((command) => command.state === 'sending')\n .map((command) =>\n this.#repository.putCommand({\n ...command,\n state: 'pending',\n serverCommitUnknown: command.serverCommitUnknown ?? true,\n }),\n ),\n );\n this.#initialized = true;\n await this.#refreshState();\n }\n\n noteScope(scope: OfflineScope): void {\n this.#knownScopes.set(this.#scopeKey(scope), scope);\n }\n\n async reloadPendingCommands(): Promise<void> {\n const generation = this.#generation;\n if (!(await this.#restoreCurrentGeneration(generation))) return;\n await this.#refreshState();\n }\n\n async refreshSession(foregroundScopeIds?: readonly string[]): Promise<void> {\n const generation = this.#generation;\n if (!(await this.#restoreCurrentGeneration(generation))) return;\n this.#setForegroundScopePolicy(foregroundScopeIds);\n await this.#discoverScopes();\n await this.#restoreInterruptedCommands();\n await this.#refreshState();\n if (this.#network.connected()) this.#flushInBackground();\n }\n\n /** Restores local outbox visibility without enabling pull or replay transport. */\n async refreshLocalSession(): Promise<void> {\n const generation = this.#generation;\n if (!(await this.#restoreCurrentGeneration(generation))) return;\n await this.#discoverLocalScopes();\n await this.#restoreInterruptedCommands();\n await this.#refreshState();\n }\n\n async resetSession(): Promise<void> {\n this.revokeSession();\n await Promise.allSettled([this.#replicaMutations.drain(), ...this.#flushTransitions]);\n await this.#waitForSendingTransitions();\n await this.#restoreInterruptedCommands();\n this.#activeUserId = null;\n this.#knownScopes.clear();\n this.#pendingPullScopes.clear();\n this.#commands.set([]);\n this.#pullAttentions.set([]);\n this.#scheduleRetry(null);\n }\n\n /** Synchronously invalidate in-flight enqueue and transport work owned by the current session. */\n revokeSession(): void {\n this.#invalidateFlush();\n this.#foregroundScopePolicy = null;\n }\n\n enqueue<T>(request: EnqueueOfflineCommand<T>, options: { flush?: boolean } = {}): Promise<string> {\n return this.#mutationAdmission.run(() => {\n const generation = this.#generation;\n return this.#serializeReplicaMutation((repository) => this.#enqueue(request, options, generation, undefined, repository));\n });\n }\n\n /**\n * Reads, derives, and commits one Outbox command, then rematerializes its\n * aggregate from confirmed replica values plus remaining FIFO intents.\n */\n enqueuePrepared<T>(\n prepare: (repository: OfflineRepository) => Promise<PreparedOfflineCommand<T>>,\n options: { flush?: boolean } = {},\n ): Promise<string> {\n return this.#mutationAdmission.run(() => {\n const generation = this.#generation;\n return this.#serializeReplicaMutation(async (repository) => {\n await this.#ensureInitialized();\n if (!this.#isCurrent(generation)) throw new Error('Offline session changed before prepared enqueue.');\n const prepared = await prepare(repository);\n return this.#enqueue(prepared.request, options, generation, undefined, repository);\n });\n });\n }\n\n /**\n * Prepares and commits multiple Outbox commands as one serialized replica\n * transaction under a single captured session generation.\n *\n * All entries are prepared and validated before any write. Empty batches,\n * overlapping aggregate intents, and overlapping replica footprints are\n * rejected with no durable state change.\n */\n enqueuePreparedBatch<T>(\n prepare: (repository: OfflineRepository) => Promise<readonly PreparedOfflineCommand<T>[]>,\n options: PreparedOfflineBatchOptions = {},\n ): Promise<readonly string[]> {\n return this.#mutationAdmission.run(() => {\n const generation = this.#generation;\n return this.#serializeReplicaMutation(async (repository) => {\n await this.#ensureInitialized();\n if (!this.#isCurrent(generation)) throw new Error('Offline session changed before prepared batch enqueue.');\n const prepared = await prepare(repository);\n return this.#enqueuePreparedBatch(prepared, options, generation, repository);\n });\n });\n }\n\n /**\n * Atomically replaces a resolved durable command with a newly prepared command.\n *\n * Use this after an authoritative conflict read. The old intent remains durable\n * until validation, capacity checks, optimistic projection and replacement\n * command preparation have all succeeded.\n */\n replacePrepared<T>(\n commandId: string,\n prepare: (repository: OfflineRepository) => Promise<PreparedOfflineCommand<T>>,\n options: { flush?: boolean } = {},\n ): Promise<string> {\n const generation = this.#generation;\n return this.#serializeReplicaMutation(async (repository) => {\n await this.#ensureInitialized();\n if (!this.#isCurrent(generation)) throw new Error('Offline session changed before prepared replacement.');\n const knownCommands = await this.#readKnownCommands();\n const replaced = knownCommands.find((command) => command.commandId === commandId);\n if (!replaced) throw new Error(`Offline command ${commandId} no longer exists.`);\n this.#assertDiscardable([replaced]);\n if (\n knownCommands.some((command) => command.commandId !== commandId && this.#aggregateKey(command) === this.#aggregateKey(replaced))\n ) {\n throw new Error('Offline replacement requires the command to be the only pending intent for its aggregate.');\n }\n const prepared = await prepare(repository);\n return this.#enqueue(prepared.request, options, generation, replaced, repository);\n });\n }\n\n /**\n * Atomically rematerializes every unresolved intent for one aggregate.\n *\n * This is the conflict-recovery boundary for ordered intent chains: the old\n * chain remains durable until every replacement has been prepared and the\n * complete chain can be committed in one replica transaction.\n */\n replacePreparedAggregate<T>(\n commandId: string,\n prepare: (repository: OfflineRepository, commands: readonly OfflineCommand[]) => Promise<readonly PreparedOfflineCommand<T>[]>,\n options: PreparedOfflineBatchOptions = {},\n ): Promise<readonly string[]> {\n const generation = this.#generation;\n return this.#serializeReplicaMutation(async (repository) => {\n await this.#ensureInitialized();\n if (!this.#isCurrent(generation)) throw new Error('Offline session changed before prepared aggregate replacement.');\n const knownCommands = await this.#readKnownCommands();\n const selected = knownCommands.find((command) => command.commandId === commandId);\n if (!selected) throw new Error(`Offline command ${commandId} no longer exists.`);\n const aggregateKey = this.#aggregateKey(selected);\n const replaced = knownCommands.filter((command) => this.#aggregateKey(command) === aggregateKey);\n this.#assertDiscardable(replaced);\n const prepared = await prepare(repository, replaced);\n if (prepared.length !== replaced.length) {\n throw new Error('Offline aggregate replacement must preserve the ordered intent count.');\n }\n const session = await this.#beginEnqueueSession(generation);\n const materializations: MaterializedOfflineEnqueue[] = [];\n for (const [index, entry] of prepared.entries()) {\n this.#assertEnqueueScope(session, entry.request.scopeId);\n materializations.push(await this.#materializeEnqueue(session.userId, entry.request, replaced[index]));\n }\n const retained = knownCommands.filter((command) => !replaced.some((item) => item.commandId === command.commandId));\n this.#assertDistinctBatchFootprints(materializations, retained, true);\n await this.#assertOutboxCapacity(\n session.userId,\n materializations.map((item) => item.command),\n replaced.map((command) => command.commandId),\n knownCommands,\n );\n options.assertCurrent?.();\n await this.#commitMaterializedEnqueues(\n materializations,\n generation,\n options,\n replaced.map((command) => command.commandId),\n repository,\n );\n return materializations.map((item) => item.command.commandId);\n });\n }\n\n /**\n * Serializes a product-owned replica projection with enqueue and command ACK\n * reconciliation. For read/derive/write cache updates, prefer\n * `runSerializedReplicaMutation` so the read is serialized as well.\n */\n async transactReplica(transaction: OfflineReplicaTransaction): Promise<void> {\n await this.runSerializedReplicaMutation(async (repository) => {\n await repository.transactReplica(transaction);\n });\n }\n\n /**\n * Runs a product cache's replica read/derive/write sequence atomically with\n * enqueue and ACK projection. Use this for any repository reads that inform\n * a later transaction; `transactReplica` alone only serializes the write.\n */\n runSerializedReplicaMutation<T>(operation: (repository: OfflineRepository) => Promise<T>): Promise<T> {\n const generation = this.#generation;\n return this.#serializeReplicaMutation(async (repository) => {\n await this.#ensureInitialized();\n if (!this.#isCurrent(generation)) throw new Error('Offline session changed before serialized replica mutation.');\n const result = await operation(repository);\n if (this.#isCurrent(generation)) await this.#refreshState(generation);\n return result;\n });\n }\n\n #serializeReplicaMutation<T>(operation: (repository: OfflineRepository) => Promise<T>): Promise<T> {\n return this.#replicaMutations.run(operation);\n }\n\n async #enqueue<T>(\n request: EnqueueOfflineCommand<T>,\n options: { flush?: boolean },\n generation: number,\n replaced?: OfflineCommand,\n repository: OfflineRepository = this.#repository,\n ): Promise<string> {\n const session = await this.#beginEnqueueSession(generation);\n this.#assertEnqueueScope(session, request.scopeId);\n const materialization = await this.#materializeEnqueue(session.userId, request, replaced);\n const currentCommands = await this.#commandsForUser(session.userId);\n const retainedCommands = replaced ? currentCommands.filter((command) => command.commandId !== replaced.commandId) : currentCommands;\n this.#assertDistinctBatchFootprints([materialization], retainedCommands);\n await this.#assertOutboxCapacity(\n session.userId,\n [materialization.command],\n replaced ? [replaced.commandId] : undefined,\n currentCommands,\n );\n await this.#commitMaterializedEnqueues([materialization], generation, options, replaced ? [replaced.commandId] : undefined, repository);\n return materialization.command.commandId;\n }\n\n async #enqueuePreparedBatch<T>(\n prepared: readonly PreparedOfflineCommand<T>[],\n options: PreparedOfflineBatchOptions,\n generation: number,\n repository: OfflineRepository,\n ): Promise<readonly string[]> {\n if (prepared.length === 0) {\n throw new Error('Prepared offline batch must contain at least one command.');\n }\n const session = await this.#beginEnqueueSession(generation);\n const currentCommands = await this.#commandsForUser(session.userId);\n this.#rememberCreatedAt(currentCommands);\n const firstCreatedAt = Math.max(Date.now(), this.#lastCommandCreatedAt + 1);\n this.#lastCommandCreatedAt = firstCreatedAt + prepared.length - 1;\n const materializations: MaterializedOfflineEnqueue[] = [];\n for (const [index, entry] of prepared.entries()) {\n this.#assertEnqueueScope(session, entry.request.scopeId);\n materializations.push(await this.#materializeEnqueue(session.userId, entry.request, undefined, firstCreatedAt + index));\n }\n this.#assertDistinctBatchFootprints(materializations, currentCommands);\n await this.#assertOutboxCapacity(\n session.userId,\n materializations.map((item) => item.command),\n undefined,\n currentCommands,\n );\n options.assertCurrent?.();\n await this.#commitMaterializedEnqueues(materializations, generation, options, undefined, repository);\n return materializations.map((item) => item.command.commandId);\n }\n\n async #beginEnqueueSession(generation: number): Promise<OfflineSyncSession> {\n await this.#ensureInitialized();\n if (this.#options.mode === 'readCacheOnly') {\n throw new Error('This offline provider is configured as a read-only cache and cannot enqueue commands.');\n }\n const session = await this.#getLocalSession();\n if (!session) throw new Error('Cannot enqueue an offline command without an authenticated user');\n this.#assertSessionPrincipalBoundary(session);\n this.#setActiveUser(session.userId);\n if (!this.#isCurrent(generation)) {\n throw new Error('Offline session changed before the command could be persisted');\n }\n return session;\n }\n\n #assertEnqueueScope(session: OfflineSyncSession, scopeId: string): void {\n if (!session.scopes.some((candidate) => candidate.userId === session.userId && candidate.scopeId === scopeId)) {\n throw new Error(`Offline sync session does not include scope \"${scopeId}\".`);\n }\n this.noteScope({ userId: session.userId, scopeId });\n }\n\n async #materializeEnqueue<T>(\n userId: OfflinePrincipalId,\n request: EnqueueOfflineCommand<T>,\n replaced?: OfflineCommand,\n createdAt?: number,\n ): Promise<MaterializedOfflineEnqueue> {\n const scope = { userId, scopeId: request.scopeId };\n this.noteScope(scope);\n const commandIdentity = offlineCommandLookupIdentity(request.identity);\n const normalized = await this.#normalizeEnqueueRequest(scope, request, commandIdentity);\n const commandId = crypto.randomUUID();\n const sourceKey = this.#hooks.entityType(request);\n const localOnlyFootprint = this.#normalizedLocalOnlyFootprint(scope, request.localOnlyFootprint);\n if (replaced) this.#assertReplacementFootprint(replaced, localOnlyFootprint);\n let command: OfflineCommand = {\n ...scope,\n commandId,\n aggregateType: request.aggregateType,\n sourceKey,\n identity: commandIdentity,\n operation: request.operation,\n payload: normalized.payload,\n replicaMutation: request.replicaMutation ?? 'upsert',\n baseRevision: normalized.baseRevision,\n state: 'pending',\n attempts: 0,\n retryAt: null,\n createdAt: replaced?.createdAt ?? createdAt ?? (await this.#nextCommandCreatedAt(userId)),\n lastErrorCode: null,\n };\n if (localOnlyFootprint.length > 0) command = { ...command, localOnlyFootprint };\n if (\n replaced &&\n (replaced.userId !== command.userId ||\n replaced.scopeId !== command.scopeId ||\n replaced.aggregateType !== command.aggregateType ||\n replaced.sourceKey !== command.sourceKey ||\n canonicalOfflineCommandIdentity(replaced.identity) !== canonicalOfflineCommandIdentity(command.identity))\n ) {\n throw new Error('Offline replacement command must address the same aggregate and replica identity.');\n }\n const entityType = command.sourceKey;\n const schema = this.#entitySchema(entityType);\n if (schema.identity.kind === 'localOnly') {\n throw new Error(`Offline replica source \"${entityType}\" is local-only and cannot be added to the Outbox.`);\n }\n if (schema.identity.kind === 'generated' && request.identity.kind !== 'generated') {\n throw new Error(`Offline replica source \"${entityType}\" requires generated identity.`);\n }\n if (schema.identity.kind === 'naturalKey' && request.identity.kind !== 'natural') {\n throw new Error(`Offline replica source \"${entityType}\" requires natural identity.`);\n }\n if (request.replicaMutation === 'delete' && !this.#repository.getReplicaRowIncludingPendingDelete) {\n throw new Error('Offline repository does not support durable replica delete tombstones.');\n }\n const existing = await this.#getReplicaRowForSync(scope, entityType, commandIdentity);\n const generatedIdentity = request.identity.kind === 'generated' ? request.identity : null;\n const initialRemoteId = this.#initialRemoteId(\n schema,\n existing?.identity.kind === 'generated' ? existing.identity.remoteId : null,\n generatedIdentity?.remoteId,\n );\n this.#assertRemoteIdHint(\n schema,\n existing?.identity.kind === 'generated' ? existing.identity.remoteId : null,\n generatedIdentity?.remoteIdHint,\n );\n const naturalKey =\n schema.identity.kind === 'naturalKey' && request.identity.kind === 'natural'\n ? request.identity.naturalKey\n : existing\n ? offlineNaturalKeyFromValues(schema, existing.values)\n : null;\n if (\n schema.identity.kind === 'naturalKey' &&\n request.identity.kind === 'natural' &&\n canonicalOfflineRemoteIdentity(schema, { naturalKey: request.identity.naturalKey }) !==\n canonicalOfflineRemoteIdentity(schema, { naturalKey: naturalKey! })\n ) {\n throw new Error(`Offline command naturalKey must match replica identity for \"${entityType}\".`);\n }\n const remoteIdentity =\n schema.identity.kind === 'generated'\n ? initialRemoteId === null\n ? null\n : { remoteId: initialRemoteId }\n : schema.identity.kind === 'naturalKey'\n ? { naturalKey: naturalKey! }\n : null;\n if (schema.identity.kind === 'naturalKey') {\n const canonicalValuesKey = canonicalOfflineRemoteIdentity(schema, remoteIdentity!);\n if (\n existing &&\n canonicalOfflineRemoteIdentity(schema, {\n naturalKey:\n existing.identity.kind === 'natural' ? existing.identity.naturalKey : offlineNaturalKeyFromValues(schema, existing.values)!,\n }) !== canonicalValuesKey\n ) {\n throw new Error(`Offline replica naturalKey is immutable and must match command identity for \"${entityType}\".`);\n }\n }\n if (remoteIdentity !== null) {\n const mapped = await this.#repository.getReplicaRowByRemoteIdentity(scope, entityType, remoteIdentity);\n if (mapped !== null && !commandIdentityMatchesReplicaRow(schema, mapped, commandIdentity)) {\n if ('remoteId' in remoteIdentity) {\n throw new Error(`Offline replica remote id ${String(remoteIdentity.remoteId)} is already mapped to another row.`);\n }\n throw new Error(`Offline replica remote identity is already mapped to another row.`);\n }\n }\n this.#canonicalJson(normalized.payload);\n const seedBaseRow = existing\n ? undefined\n : request.identity.kind === 'generated'\n ? {\n ...scope,\n sourceKey,\n identity: { kind: 'generated' as const, localId: request.identity.localId, remoteId: initialRemoteId },\n values: {},\n confirmedValues: null,\n serverRevision: null,\n fetchedAt: Date.now(),\n syncState: 'pending' as const,\n }\n : request.identity.kind === 'natural'\n ? {\n ...scope,\n sourceKey,\n identity: { kind: 'natural' as const, naturalKey: request.identity.naturalKey },\n values: { ...request.identity.naturalKey },\n confirmedValues: null,\n serverRevision: null,\n fetchedAt: Date.now(),\n syncState: 'pending' as const,\n }\n : null;\n return { command, seedBaseRow };\n }\n\n #assertDistinctBatchFootprints(\n entries: readonly MaterializedOfflineEnqueue[],\n existingCommands: readonly OfflineCommand[],\n allowOneAggregate = false,\n ): void {\n const aggregates = new Set<string>();\n const replicaKeys = new Set<string>();\n const existingFootprints = new Map<string, string>();\n for (const command of existingCommands) {\n const aggregate = this.#aggregateKey(command);\n for (const key of this.#commandFootprintKeys(command)) existingFootprints.set(key, aggregate);\n }\n for (const entry of entries) {\n const aggregate = this.#aggregateKey(entry.command);\n if (aggregates.has(aggregate) && !allowOneAggregate) {\n throw new Error('Prepared offline batch contains overlapping aggregate intents.');\n }\n aggregates.add(aggregate);\n for (const key of this.#commandFootprintKeys(entry.command)) {\n if (replicaKeys.has(key) && !allowOneAggregate) {\n throw new Error('Prepared offline batch contains overlapping replica footprints.');\n }\n const existingAggregate = existingFootprints.get(key);\n if (existingAggregate !== undefined && existingAggregate !== aggregate) {\n throw new Error('Offline commands for different aggregates cannot share a replica footprint.');\n }\n replicaKeys.add(key);\n }\n }\n }\n\n #commandFootprintKeys(command: OfflineCommand): readonly string[] {\n const identity =\n command.identity.kind === 'generated'\n ? offlineGeneratedReplicaIdentity(command.identity.localId, null)\n : ({ kind: 'natural', naturalKey: command.identity.naturalKey } as const);\n return [this.#replicaRowKey({ ...command, identity }), ...commandFootprintKeys(command).map((key) => this.#replicaRowKey(key))];\n }\n\n async #commitMaterializedEnqueues(\n entries: readonly MaterializedOfflineEnqueue[],\n generation: number,\n options: { flush?: boolean },\n removeCommandIds?: readonly string[],\n repository: OfflineRepository = this.#repository,\n ): Promise<void> {\n if (generation !== this.#generation) {\n throw new Error('Offline session changed before the command could be persisted');\n }\n const known = await this.#readKnownCommands();\n const remaining = [\n ...known.filter((command) => !(removeCommandIds ?? []).includes(command.commandId)),\n ...entries.map((entry) => entry.command),\n ].sort(compareOfflineCommands);\n const affected = new Map<string, OfflineCommand>();\n const seeds = new Map<string, OfflineReplicaRow | null>();\n for (const entry of entries) {\n affected.set(this.#aggregateKey(entry.command), entry.command);\n if (entry.seedBaseRow !== undefined) seeds.set(this.#aggregateKey(entry.command), entry.seedBaseRow);\n }\n const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, seeds);\n await repository.transactReplica({\n putRows: rematerialized.putRows,\n removeRows: rematerialized.removeRows,\n putCommands: entries.map((entry) => entry.command),\n removeCommandIds,\n });\n await this.#refreshState().catch((error) => this.#reportError(error));\n if (options.flush !== false && this.#network.connected()) this.#flushInBackground();\n }\n\n #normalizedLocalOnlyFootprint(\n scope: OfflineScope,\n footprint: readonly OfflineReplicaRowKey[] | undefined,\n ): readonly OfflineReplicaRowKey[] {\n if (!footprint || footprint.length === 0) return [];\n const seen = new Set<string>();\n return footprint.map((key) => {\n this.#assertLocalOnlyFootprintKey(scope, key);\n const canonical = this.#replicaRowKey(key);\n if (seen.has(canonical)) throw new Error(`Prepared offline enqueue contains duplicate replica row ${canonical}.`);\n seen.add(canonical);\n return this.#minimalReplicaRowKey(key);\n });\n }\n\n #assertLocalOnlyFootprintKey(scope: OfflineScope, key: OfflineReplicaRowKey): void {\n if (key.userId !== scope.userId || key.scopeId !== scope.scopeId) {\n throw new Error('Prepared offline enqueue localOnly footprint must use the command scope.');\n }\n if (this.#entitySchema(key.sourceKey).identity.kind !== 'localOnly') {\n throw new Error(`Prepared offline enqueue footprint may only declare localOnly source \"${key.sourceKey}\".`);\n }\n if (key.identity.kind !== 'local') {\n throw new Error('Prepared offline enqueue footprint must use local identity.');\n }\n }\n\n #assertReplacementFootprint(replaced: OfflineCommand, next: readonly OfflineReplicaRowKey[]): void {\n const previous = new Set(commandFootprintKeys(replaced).map((key) => this.#replicaRowKey(key)));\n const incoming = new Set(next.map((key) => this.#replicaRowKey(key)));\n if (previous.size !== incoming.size || [...previous].some((key) => !incoming.has(key))) {\n throw new Error('Offline replacement must preserve the localOnly footprint.');\n }\n }\n\n #minimalReplicaRowKey(key: OfflineReplicaRowKey): OfflineReplicaRowKey {\n return {\n userId: key.userId,\n scopeId: key.scopeId,\n sourceKey: key.sourceKey,\n identity: key.identity,\n };\n }\n\n #replicaRowKey(key: OfflineReplicaRowKey): string {\n return canonicalOfflineReplicaRowKey(this.#entitySchema(key.sourceKey), key);\n }\n\n async #assertOutboxCapacity(\n userId: OfflinePrincipalId,\n newCommands: readonly OfflineCommand[],\n excludingCommandIds?: readonly string[],\n knownCommands?: readonly OfflineCommand[],\n ): Promise<void> {\n const currentCommands = knownCommands ?? (await this.#commandsForUser(userId));\n const commands = excludingCommandIds\n ? currentCommands.filter((candidate) => !excludingCommandIds.includes(candidate.commandId))\n : currentCommands;\n const maxCommands = this.#options.outboxLimits?.maxCommandsPerUser ?? DEFAULT_MAX_OUTBOX_COMMANDS_PER_USER;\n const maxBytes = this.#options.outboxLimits?.maxBytesPerUser ?? DEFAULT_MAX_OUTBOX_BYTES_PER_USER;\n const currentBytes = this.#serializedOutboxBytes(commands);\n if (commands.length + newCommands.length > maxCommands) {\n throw new OfflineOutboxCapacityError('command_count', commands.length, currentBytes);\n }\n const nextBytes = this.#serializedOutboxBytes([...commands, ...newCommands]);\n if (nextBytes > maxBytes) {\n throw new OfflineOutboxCapacityError('serialized_bytes', commands.length, currentBytes);\n }\n }\n\n async #commandsForUser(userId: OfflinePrincipalId): Promise<OfflineCommand[]> {\n return this.#repository.getCommandsForUser\n ? this.#repository.getCommandsForUser(userId)\n : (\n await Promise.all(\n [...this.#knownScopes.values()].filter((scope) => scope.userId === userId).map((scope) => this.#repository.getCommands(scope)),\n )\n ).flat();\n }\n\n #serializedOutboxBytes(commands: readonly OfflineCommand[]): number {\n return new TextEncoder().encode(JSON.stringify(commands)).byteLength;\n }\n\n async discard(commandId: string, options: { flush?: boolean } = {}): Promise<void> {\n const generation = this.#generation;\n if (!(await this.#restoreCurrentGeneration(generation))) return;\n // A pull may have completed while transport was being cancelled. Re-read\n // and project the discard inside the same local mutation lane used by\n // enqueue, ACK, and pull application so an old before-image cannot replace\n // a newer authoritative row after its cursor has advanced.\n const command = await this.#replicaMutations.run(async (repository) => {\n const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);\n if (!current) return null;\n this.#assertDiscardable([current]);\n this.#invalidateFlush();\n await this.#discardCommands([current], repository);\n return current;\n });\n if (!command) return;\n await this.#restoreInterruptedCommands();\n await this.#refreshState();\n await this.#hooks.onCommandRemoved?.(command).catch((error) => this.#reportError(error));\n if (options.flush !== false && this.#network.connected()) this.#flushInBackground();\n }\n\n /** Clears a retry backoff/auth block selected explicitly by the user and sends the durable command now. */\n async retryNow(commandId: string): Promise<void> {\n const generation = this.#generation;\n if (!(await this.#restoreCurrentGeneration(generation))) return;\n this.#invalidateFlush();\n await this.#waitForSendingTransitions();\n await this.#restoreInterruptedCommands();\n const retried = await this.runSerializedReplicaMutation(async (repository) => {\n // Re-read only after every interrupted transport transition has settled.\n // An ACK may have removed the command while retryNow was waiting; never\n // resurrect such a command from an object captured before invalidation.\n const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);\n if (!current) return false;\n if (current.state !== 'retry_wait' && current.state !== 'blocked_auth' && current.serverCommitUnknown !== true) {\n throw new Error(`Offline command ${commandId} is not waiting for retry or reauthentication.`);\n }\n await repository.putCommand({\n ...current,\n state: 'pending',\n retryAt: null,\n lastErrorCode: null,\n });\n return true;\n });\n if (retried && this.#network.connected()) await this.flush();\n }\n\n async discardAllPending(): Promise<void> {\n const generation = this.#generation;\n if (!(await this.#restoreCurrentGeneration(generation))) return;\n const commands = await this.#replicaMutations.run(async (repository) => {\n const current = await this.#readKnownCommands();\n this.#assertDiscardable(current);\n this.#invalidateFlush();\n await this.#discardCommands(current, repository);\n return current;\n });\n await this.#refreshState();\n await Promise.all(commands.map((command) => this.#hooks.onCommandRemoved?.(command).catch((error) => this.#reportError(error))));\n }\n\n #assertDiscardable(commands: readonly OfflineCommand[]): void {\n const ambiguous = commands.filter(\n (command) => command.state === 'sending' || command.state === 'awaiting_pull' || command.serverCommitUnknown === true,\n );\n if (ambiguous.length > 0) {\n throw new OfflineCommandInFlightError(ambiguous.map((command) => command.commandId));\n }\n }\n\n #flushInBackground(): void {\n void this.#beginFlush(false).catch((error) => this.#reportError(error));\n }\n\n flush(): Promise<void> {\n const generation = this.#generation;\n return this.#flushAfterInitialization(generation);\n }\n\n async #flushAfterInitialization(generation: number): Promise<void> {\n if (!(await this.#restoreCurrentGeneration(generation))) return;\n return this.#beginFlush(true);\n }\n\n #beginFlush(explicitFull: boolean): Promise<void> {\n const isPartial = !explicitFull && this.#foregroundScopePolicy !== null;\n if (this.#flushPromise) {\n if (explicitFull && this.#partialFlushInFlight) {\n if (!this.#chainedFullFlush) {\n const generation = this.#generation;\n const partial = this.#flushPromise;\n const chain = partial\n .then(\n () => undefined,\n () => undefined,\n )\n .then(() => {\n if (!this.#isCurrent(generation)) return;\n return this.#beginFlush(true);\n })\n .finally(() => {\n if (this.#chainedFullFlush === chain) this.#chainedFullFlush = null;\n });\n this.#chainedFullFlush = chain;\n }\n return this.#chainedFullFlush;\n }\n return this.#flushPromise;\n }\n const generation = this.#generation;\n const promise = this.#runFlush(generation, explicitFull).finally(() => {\n this.#flushTransitions.delete(promise);\n if (this.#flushPromise === promise) {\n this.#flushPromise = null;\n this.#partialFlushInFlight = false;\n }\n });\n this.#flushPromise = promise;\n this.#partialFlushInFlight = isPartial;\n this.#flushTransitions.add(promise);\n return promise;\n }\n\n async #runFlush(generation: number, explicitFull: boolean): Promise<void> {\n if (!this.#isCurrent(generation)) return;\n if (!this.#network.connected()) {\n await this.#refreshState(generation);\n return;\n }\n if (!(await this.#discoverScopes(generation))) return;\n const isPartial = !explicitFull && this.#foregroundScopePolicy !== null;\n const pullScopes = isPartial\n ? this.#scopesForPartialPull(this.#foregroundScopePolicy!, await this.#readKnownCommands())\n : [...this.#knownScopes.values()];\n const prePullFailures: unknown[] = [];\n let fatalPullFailure: unknown | null = null;\n const pulledScopeKeys = new Set<string>();\n for (const scope of pullScopes) {\n if (!this.#isCurrent(generation) || !this.#network.connected()) return;\n const pullScope = async (): Promise<void> => {\n await this.#pull.pull(scope);\n await this.#markScopeReconciled(scope, generation);\n pulledScopeKeys.add(this.#scopeKey(scope));\n };\n const pull = await pullScope().then(\n () => ({ status: 'fulfilled' as const }),\n (error: unknown) => ({ status: 'rejected' as const, error }),\n );\n if (pull.status === 'rejected') {\n prePullFailures.push(pull.error);\n if (this.#isFatalPullFailure(pull.error)) {\n // Auth/upgrade-driven recovery only: stop remaining scopes immediately.\n fatalPullFailure = fatalPullFailure ?? pull.error;\n await this.#persistFatalPullAttentions(pull.error, scope, pullScopes, generation);\n break;\n }\n if (this.#pendingPullScopes.has(this.#scopeKey(scope))) {\n this.#scheduleRetry(Date.now() + POST_SEND_PULL_RETRY_MS);\n }\n }\n }\n const dirtyScopes = new Map<string, OfflineScope>();\n const sendWorkerFailures: unknown[] = [];\n while (this.#network.connected() && this.#isCurrent(generation) && fatalPullFailure === null) {\n const known = await this.#readKnownCommands();\n const groups = this.#eligibleAggregateGroups(known).filter((group) =>\n group.some(\n (command) =>\n (command.state === 'pending' || command.state === 'retry_wait') &&\n pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })),\n ),\n );\n if (!this.#isCurrent(generation)) return;\n if (groups.length === 0) break;\n const pendingBefore = known.filter((command) => command.state === 'pending' || command.state === 'retry_wait').length;\n let cursor = 0;\n const workers = Array.from({ length: Math.min(MAX_PARALLEL_AGGREGATES, groups.length) }, async () => {\n while (cursor < groups.length) {\n const group = groups[cursor++];\n if (group && this.#isCurrent(generation)) await this.#sendAggregate(group, generation, dirtyScopes, pulledScopeKeys);\n }\n });\n // Drain with allSettled so one rejecting worker cannot skip sibling settlement or post-send pull.\n const settled = await Promise.allSettled(workers);\n for (const result of settled) {\n if (result.status === 'rejected') sendWorkerFailures.push(result.reason);\n }\n if (sendWorkerFailures.length > 0) break;\n const pendingAfter = (await this.#readKnownCommands()).filter(\n (command) => command.state === 'pending' || command.state === 'retry_wait',\n ).length;\n if (pendingAfter >= pendingBefore) break;\n }\n for (const scope of dirtyScopes.values()) {\n this.#pendingPullScopes.set(this.#scopeKey(scope), scope);\n }\n const postPullFailures: unknown[] = [];\n // Fatal pre-pull skips pending post-pulls; recovery is auth/upgrade-driven, not timer retry.\n // Fatal post-send pull stops remaining pending scopes the same way (ACK preserved, no resend).\n if (fatalPullFailure === null) {\n const postPullScopes = [...this.#pendingPullScopes.values()];\n for (const scope of postPullScopes) {\n if (!this.#isCurrent(generation) || !this.#network.connected()) break;\n // A command response may contain only the aggregate's base row. Pull once per dirty scope so\n // sibling-table journal entries are visible before completed Outbox state reaches product UI.\n const pullScope = async (): Promise<void> => {\n await this.#pull.pull(scope);\n await this.#markScopeReconciled(scope, generation);\n };\n const pull = await pullScope().then(\n () => ({ status: 'fulfilled' as const }),\n (error: unknown) => ({ status: 'rejected' as const, error }),\n );\n if (pull.status === 'rejected') {\n if (this.#isFatalPullFailure(pull.error)) {\n fatalPullFailure = fatalPullFailure ?? pull.error;\n await this.#persistFatalPullAttentions(pull.error, scope, postPullScopes, generation);\n break;\n }\n postPullFailures.push(pull.error);\n }\n }\n }\n await this.#refreshState(generation);\n if (fatalPullFailure !== null) {\n // Auth/upgrade recovery only — never arm the 1s automatic flush retry.\n // Transported commands remain awaiting_pull for later auth/upgrade recovery.\n // Only the owning generation may clear the timer — a stale fatal must not disarm a\n // newer session's already-armed retry_wait / post-pull retry.\n if (this.#isCurrent(generation)) this.#scheduleRetry(null);\n throw fatalPullFailure;\n }\n const failures = [...prePullFailures, ...sendWorkerFailures, ...postPullFailures];\n if (failures.length > 0) {\n // Keep rejecting the flush promise after workers settle even when the session\n // was revoked mid-flight, so callers and ErrorHandler still observe the failure.\n if (this.#isCurrent(generation)) {\n this.#scheduleRetry(Date.now() + POST_SEND_PULL_RETRY_MS);\n }\n throw failures[0];\n }\n if (this.#isCurrent(generation)) {\n for (const command of await this.#readKnownCommands()) {\n if (command.state !== 'awaiting_pull') continue;\n const scope = { userId: command.userId, scopeId: command.scopeId };\n this.#pendingPullScopes.set(this.#scopeKey(scope), scope);\n }\n }\n }\n\n #isFatalPullFailure(error: unknown): boolean {\n const status = this.#errorStatus(error);\n // Pull-protocol HTTP 409 is schema mismatch (distinct from command-send conflict\n // classification elsewhere in this service). Same classifier for pre-pull and post-send pull.\n if (status === 401 || status === 403 || status === 409) return true;\n return error instanceof OfflineReplicaSchemaMismatchError;\n }\n\n #pullAttentionReason(error: unknown): OfflinePullAttentionReason | null {\n if (error instanceof OfflineReplicaSchemaMismatchError) return 'schema_upgrade_required';\n const status = this.#errorStatus(error);\n if (status === 409) return 'schema_upgrade_required';\n if (status === 401 || status === 403) return 'authorization_required';\n return null;\n }\n\n /**\n * Persists durable pull attentions for a current-generation fatal pull.\n * Schema/409 marks all attempted pull scopes; 401 marks every known principal scope;\n * 403 marks only the failing scope. Stale generations must not mutate a newer session.\n */\n async #persistFatalPullAttentions(\n error: unknown,\n failingScope: OfflineScope,\n attemptedScopes: readonly OfflineScope[],\n generation: number,\n ): Promise<void> {\n if (!this.#isCurrent(generation)) return;\n const reason = this.#pullAttentionReason(error);\n if (reason === null) return;\n const status = this.#errorStatus(error);\n // Snapshot synchronously before any await so a concurrent session switch cannot retarget scopes.\n const scoped =\n status === 403\n ? [failingScope]\n : status === 401\n ? [...this.#knownScopes.values()].filter((scope) => scope.userId === failingScope.userId)\n : attemptedScopes.filter((scope) => scope.userId === failingScope.userId);\n const scopes = scoped.length > 0 ? scoped : [failingScope];\n const attentions: OfflinePullAttention[] = scopes.map((scope) => {\n const attention: OfflinePullAttention = {\n userId: scope.userId,\n scopeId: scope.scopeId,\n reason,\n };\n if (status > 0) attention.status = status;\n return attention;\n });\n if (!this.#isCurrent(generation)) return;\n await this.#repository.transactReplica({ putPullAttentions: attentions });\n }\n\n #setForegroundScopePolicy(foregroundScopeIds?: readonly string[]): void {\n this.#foregroundScopePolicy = foregroundScopeIds !== undefined ? foregroundScopeIds : null;\n }\n\n #scopesForPartialPull(foregroundScopeIds: readonly string[], commands: readonly OfflineCommand[]): OfflineScope[] {\n const foregroundScopeSet = new Set(foregroundScopeIds);\n const outboxScopeKeys = new Set(commands.map((command) => this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })));\n const attentionScopeKeys = new Set(this.#pullAttentions().map((attention) => this.#scopeKey(attention)));\n return [...this.#knownScopes.values()].filter(\n (scope) =>\n foregroundScopeSet.has(scope.scopeId) ||\n outboxScopeKeys.has(this.#scopeKey(scope)) ||\n attentionScopeKeys.has(this.#scopeKey(scope)) ||\n this.#pendingPullScopes.has(this.#scopeKey(scope)),\n );\n }\n\n #eligibleAggregateGroups(commands: OfflineCommand[]): OfflineCommand[][] {\n const now = Date.now();\n const groups = new Map<string, OfflineCommand[]>();\n for (const command of commands) {\n const key = this.#aggregateKey(command);\n const group = groups.get(key) ?? [];\n group.push(command);\n groups.set(key, group);\n }\n return [...groups.values()].filter((group) =>\n group.some((command) => command.state === 'pending' || (command.state === 'retry_wait' && (command.retryAt ?? 0) <= now)),\n );\n }\n\n async #sendAggregate(\n commands: OfflineCommand[],\n generation: number,\n dirtyScopes: Map<string, OfflineScope>,\n pulledScopeKeys: ReadonlySet<string>,\n ): Promise<void> {\n for (const command of commands) {\n if (!this.#isCurrent(generation)) return;\n if (command.state === 'awaiting_pull') continue;\n if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now()) break;\n if (!['pending', 'retry_wait'].includes(command.state)) break;\n // User-scoped aggregates ignore scopeId in the FIFO key, so later commands may\n // belong to scopes that failed pre-pull even when the head was admitted.\n if (!pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId }))) break;\n let sending = await this.#claimSendingCommand(command, generation);\n if (!sending) return;\n if (!this.#isCurrent(generation)) return;\n await this.#refreshState(generation);\n if (!this.#isCurrent(generation)) return;\n const claimedCommand = sending;\n const readRow = async (): Promise<OfflineReplicaRow | null> => this.#rowForCommand(claimedCommand);\n const rowResult = await readRow().then(\n (row) => ({ status: 'fulfilled' as const, row }),\n (error: unknown) => ({ status: 'rejected' as const, error }),\n );\n if (rowResult.status === 'rejected') {\n if (!this.#isCurrent(generation)) return;\n await this.#persistFailedCommand(sending, rowResult.error, generation, null, sending.serverCommitUnknown === true);\n throw rowResult.error;\n }\n const row = rowResult.row;\n if (!row) {\n const error = new Error(\n `Offline replica row not found: ${sending.aggregateType}/${canonicalOfflineCommandIdentity(sending.identity)}`,\n );\n await this.#persistFailedCommand(sending, error, generation, null, sending.serverCommitUnknown === true);\n throw error;\n }\n const priorCommitUnknown = sending.serverCommitUnknown === true;\n const transportCommand = await this.#markTransportStarted(sending, generation);\n if (!transportCommand) return;\n sending = transportCommand;\n const executeCommand = async (): Promise<OfflineCommandResult> =>\n this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));\n const execution = await executeCommand().then(\n (result) => ({ status: 'fulfilled' as const, result }),\n (error: unknown) => ({ status: 'rejected' as const, error }),\n );\n if (execution.status === 'rejected') {\n if (!this.#isCurrent(generation)) return;\n const commitUnknown = this.#executor.provesCommandNotCommitted?.(execution.error, sending)\n ? false\n : priorCommitUnknown || this.#serverCommitCouldBeUnknown(execution.error);\n await this.#persistFailedCommand(sending, execution.error, generation, row, commitUnknown);\n if (!this.#isClassifiableTransportError(execution.error)) throw execution.error;\n break;\n }\n const result = execution.result;\n if (!this.#isCurrent(generation)) return;\n const completeCommand = async (): Promise<void> => this.#completeCommand(commands, sending, result, generation);\n const completion = await completeCommand().then(\n () => ({ status: 'fulfilled' as const }),\n (error: unknown) => ({ status: 'rejected' as const, error }),\n );\n if (completion.status === 'rejected') {\n if (!this.#isCurrent(generation)) return;\n await this.#persistFailedCommand(sending, completion.error, generation, row, true);\n throw completion.error;\n }\n if (this.#isCurrent(generation)) {\n const scope = { userId: sending.userId, scopeId: sending.scopeId };\n dirtyScopes.set(this.#scopeKey(scope), scope);\n }\n }\n }\n\n async #normalizeEnqueueRequest<T>(\n scope: OfflineScope,\n request: EnqueueOfflineCommand<T>,\n commandIdentity: OfflineCommandIdentity,\n ): Promise<{ payload: T; baseRevision: string | number | null }> {\n let baseRevision = request.baseRevision ?? null;\n const sourceKey = this.#hooks.entityType(request);\n const row = await this.#getReplicaRowForSync(scope, sourceKey, commandIdentity);\n if (row?.serverRevision != null && row.serverRevision !== baseRevision) {\n baseRevision = row.serverRevision;\n }\n return { payload: request.payload, baseRevision };\n }\n\n async #completeCommand(\n commands: OfflineCommand[],\n command: OfflineCommand,\n result: OfflineCommandResult,\n generation: number,\n ): Promise<void> {\n return this.#serializeReplicaMutation((repository) => this.#completeCommandLocked(commands, command, result, generation, repository));\n }\n\n async #completeCommandLocked(\n commands: OfflineCommand[],\n command: OfflineCommand,\n result: OfflineCommandResult,\n generation: number,\n repository: OfflineRepository,\n ): Promise<void> {\n if (result.clearRemoteId === true && result.remoteId !== undefined) {\n throw new Error('Offline command cannot return remoteId and clearRemoteId together.');\n }\n if (result.clearRemoteId === true && result.serverRevision !== undefined) {\n throw new Error('Offline command cannot return serverRevision and clearRemoteId together.');\n }\n const latestCommands = (await this.#readKnownCommands()).filter(\n (candidate) => this.#aggregateKey(candidate) === this.#aggregateKey(command),\n );\n const latestIndex = latestCommands.findIndex((candidate) => candidate.commandId === command.commandId);\n if (latestIndex < 0) return;\n const revision = result.serverRevision;\n const following = latestCommands.slice(latestIndex + 1);\n const rebased =\n result.clearRemoteId === true\n ? following.map((item) => offlineCommandWithBaseRevision(item, null))\n : revision === undefined\n ? following\n : following.map((item) => offlineCommandWithBaseRevision(item, revision));\n const current = await this.#rowForCommand(command);\n if (!this.#isCurrent(generation)) return;\n if (!current) {\n throw new Error(`Offline replica row disappeared while completing command ${command.commandId}.`);\n }\n this.#assertServerRevision(result.serverRevision);\n const removesReplica = result.removeReplica === true || command.replicaMutation === 'delete';\n if (result.clearRemoteId === true && !removesReplica) {\n throw new Error('Offline command can clear remoteId only for a confirmed replica removal.');\n }\n const schema = this.#entitySchema(current.sourceKey);\n this.#assertCommandResultIdentity(schema, current, result);\n const resolvedRemoteId = this.#resolvedRemoteId(current, result);\n const reconciliationIdentity =\n current.identity.kind === 'generated'\n ? resolvedRemoteId === null\n ? undefined\n : { remoteId: resolvedRemoteId }\n : current.identity.kind === 'natural'\n ? { naturalKey: current.identity.naturalKey }\n : undefined;\n const awaitingPull: OfflineCommand = {\n ...command,\n state: 'awaiting_pull',\n retryAt: null,\n lastErrorCode: null,\n serverCommitUnknown: false,\n ...(reconciliationIdentity ? { reconciliationIdentity } : {}),\n };\n latestCommands.splice(latestIndex, 1 + rebased.length, awaitingPull, ...rebased);\n const identityUpdatedBase: OfflineReplicaRow = {\n ...current,\n identity:\n current.identity.kind === 'generated'\n ? {\n ...current.identity,\n remoteId: result.clearRemoteId === true ? null : resolvedRemoteId,\n }\n : current.identity,\n serverRevision: result.clearRemoteId === true ? null : (revision ?? current.serverRevision),\n fetchedAt: Date.now(),\n };\n const rematerialized = await this.#rematerializeAggregate(awaitingPull, latestCommands, identityUpdatedBase);\n if (!this.#isCurrent(generation)) return;\n await repository.transactReplica({\n putRows: rematerialized.putRows,\n releaseRemoteIds:\n result.clearRemoteId === true && current.identity.kind === 'generated' && current.identity.remoteId !== null\n ? [\n {\n userId: current.userId,\n scopeId: current.scopeId,\n sourceKey: current.sourceKey,\n identity: current.identity,\n remoteId: current.identity.remoteId,\n },\n ]\n : undefined,\n removeRows: rematerialized.removeRows,\n putCommands: [awaitingPull, ...rebased],\n });\n const scope = { userId: command.userId, scopeId: command.scopeId };\n this.#pendingPullScopes.set(this.#scopeKey(scope), scope);\n commands.splice(0, commands.length, ...latestCommands);\n }\n\n async #rowForCommand(command: OfflineCommand): Promise<OfflineReplicaRow | null> {\n const scope = { userId: command.userId, scopeId: command.scopeId };\n const entityType = this.#entityType(command);\n return this.#getReplicaRowForSync(scope, entityType, command.identity);\n }\n\n #getReplicaRowForSync(scope: OfflineScope, sourceKey: string, identity: OfflineCommandIdentity): Promise<OfflineReplicaRow | null> {\n return (\n this.#repository.getReplicaRowIncludingPendingDelete?.(scope, sourceKey, identity) ??\n this.#repository.getReplicaRow(scope, sourceKey, identity)\n );\n }\n\n #replicaState(state: OfflineCommand['state']): OfflineReplicaSyncState {\n if (state === 'blocked_auth' || state === 'rejected' || state === 'conflict') return state;\n return 'pending';\n }\n\n #entityType(command: Pick<OfflineCommand, 'sourceKey'>): string {\n return command.sourceKey;\n }\n\n #entitySchema(sourceKey: string): OfflineReplicaEntitySchema<Record<string, unknown>> {\n const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);\n if (!schema) throw new Error(`Unknown offline replica source key \"${sourceKey}\".`);\n return schema;\n }\n\n async #discardCommands(discarded: readonly OfflineCommand[], repository: OfflineRepository): Promise<void> {\n const all = await this.#readKnownCommands();\n const discardedIds = new Set(discarded.map((command) => command.commandId));\n const affected = new Map<string, OfflineCommand>();\n for (const command of discarded) affected.set(this.#aggregateKey(command), command);\n const remaining = all.filter((item) => !discardedIds.has(item.commandId));\n const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining);\n await repository.transactReplica({\n putRows: rematerialized.putRows,\n removeRows: rematerialized.removeRows,\n removeCommandIds: [...discardedIds],\n });\n }\n\n async #rematerializeAffectedAggregates(\n affected: ReadonlyMap<string, OfflineCommand>,\n remaining: readonly OfflineCommand[],\n seeds: ReadonlyMap<string, OfflineReplicaRow | null> = new Map(),\n ): Promise<Pick<OfflineReplicaTransaction, 'putRows' | 'removeRows'>> {\n const putRows: OfflineReplicaRow[] = [];\n const removeRows: OfflineReplicaRowKey[] = [];\n for (const [key, command] of affected) {\n const remainingForAggregate = remaining.filter((item) => this.#aggregateKey(item) === key);\n const footprintCommands = [...remainingForAggregate, ...[...affected.values()].filter((item) => this.#aggregateKey(item) === key)];\n const rematerialized = await this.#rematerializeAggregate(\n command,\n remainingForAggregate,\n seeds.has(key) ? seeds.get(key) : undefined,\n footprintCommands,\n );\n putRows.push(...(rematerialized.putRows ?? []));\n removeRows.push(...(rematerialized.removeRows ?? []));\n }\n return { putRows, removeRows };\n }\n\n async #rematerializeAggregate(\n command: OfflineCommand,\n remaining: readonly OfflineCommand[],\n baseRow = undefined as OfflineReplicaRow | null | undefined,\n footprintCommands = remaining,\n ): Promise<Pick<OfflineReplicaTransaction, 'putRows' | 'removeRows'>> {\n const current = baseRow === undefined ? await this.#rowForCommand(command) : baseRow;\n const projection = this.#replicaMutations.projectAggregateIntent({\n baseRow: current,\n localOnlyRows: await this.#localOnlyRowsForCommands(footprintCommands),\n commands: remaining,\n trigger: 'local',\n });\n if (isOfflineAggregateIntentConflict(projection)) {\n throw new Error('Offline aggregate intent projector cannot return conflict outside pull reconciliation.');\n }\n return offlineAggregateIntentMutations(projection, current);\n }\n\n async #localOnlyRowsForCommands(commands: readonly OfflineCommand[]): Promise<OfflineReplicaRow[]> {\n const keys = new Map<string, OfflineReplicaRowKey>();\n for (const command of commands) {\n for (const key of commandFootprintKeys(command)) {\n keys.set(this.#replicaRowKey(key), key);\n }\n }\n const rows = await Promise.all([...keys.values()].map((key) => this.#getLocalOnlyRow(key)));\n return rows.filter((row): row is OfflineReplicaRow => row !== null);\n }\n\n #getLocalOnlyRow(key: OfflineReplicaRowKey): Promise<OfflineReplicaRow | null> {\n const scope = { userId: key.userId, scopeId: key.scopeId };\n return (\n this.#repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity) ??\n this.#repository.getReplicaRow(scope, key.sourceKey, key.identity)\n );\n }\n\n #aggregateKey(command: OfflineCommand): string {\n const sourceKey = this.#entityType(command);\n const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);\n if (!schema) throw new Error(`Unknown offline replica source key \"${sourceKey}\".`);\n const partition = schema.scope === 'user' ? 'user' : `partition:${command.scopeId}`;\n return `${canonicalOfflinePrincipalId(command.userId)}:${partition}:${sourceKey}:${canonicalOfflineCommandIdentity(command.identity)}`;\n }\n\n #failedCommand(command: OfflineCommand, error: unknown, serverCommitUnknown: boolean): OfflineCommand {\n const status = this.#errorStatus(error);\n if (status === 401 || status === 403) {\n return { ...command, state: 'blocked_auth', lastErrorCode: String(status), serverCommitUnknown };\n }\n if (status === 409 || status === 412) {\n return { ...command, state: 'conflict', lastErrorCode: String(status), serverCommitUnknown };\n }\n if (status >= 400 && status < 500 && status !== 429) {\n return { ...command, state: 'rejected', lastErrorCode: String(status), serverCommitUnknown };\n }\n const retryAt = Date.now() + offlineRetryDelayMs(command.attempts, this.#retryRandom);\n return {\n ...command,\n state: 'retry_wait',\n retryAt,\n lastErrorCode: status > 0 ? String(status) : 'network',\n serverCommitUnknown,\n };\n }\n\n async #persistFailedCommand(\n command: OfflineCommand,\n error: unknown,\n generation: number,\n row?: OfflineReplicaRow | null,\n serverCommitUnknown = true,\n ): Promise<void> {\n const failed = this.#failedCommand(command, error, serverCommitUnknown);\n await this.#serializeReplicaMutation(async (repository) => {\n const current = row === undefined ? await this.#rowForCommand(command) : row;\n if (!this.#isCurrent(generation)) return;\n if (current) {\n await repository.transactReplica({\n putRows: [{ ...current, syncState: this.#replicaState(failed.state) }],\n putCommands: [failed],\n });\n } else {\n await repository.putCommand(failed);\n }\n });\n if (!this.#isCurrent(generation)) return;\n if (failed.state === 'retry_wait') this.#scheduleRetry(failed.retryAt);\n await this.#refreshState(generation);\n }\n\n #errorStatus(error: unknown): number {\n if (typeof error !== 'object' || error === null) return 0;\n const status = (error as { status?: unknown }).status;\n return typeof status === 'number' ? status : 0;\n }\n\n #isClassifiableTransportError(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n const status = (error as { status?: unknown }).status;\n return typeof status === 'number' && Number.isInteger(status) && status >= 0;\n }\n\n #serverCommitCouldBeUnknown(error: unknown): boolean {\n const status = this.#errorStatus(error);\n return status === 0 || status === 429 || status >= 500;\n }\n\n #reportError(error: unknown): void {\n queueMicrotask(() => this.#dispatchError(error));\n }\n\n #dispatchError(error: unknown): void {\n let result: unknown;\n try {\n result = (this.#errorHandler.handleError as (reportedError: unknown) => unknown)(error);\n } catch {\n return;\n }\n if (result instanceof Promise) {\n void result.catch(() => undefined);\n }\n }\n\n #assertServerRevision(revision: string | number | undefined): void {\n if (typeof revision === 'number' && !Number.isFinite(revision)) {\n throw new Error(`Offline command returned invalid serverRevision ${String(revision)}.`);\n }\n }\n\n #resolvedRemoteId(current: OfflineReplicaRow, result: OfflineCommandResult): OfflineGeneratedRemoteId | null {\n if (current.identity.kind !== 'generated') return null;\n const incoming = result.remoteId;\n if (incoming === undefined) return current.identity.remoteId;\n const schema = this.#entitySchema(current.sourceKey);\n assertOfflineReplicaGeneratedRemoteId(schema, incoming);\n if (current.identity.remoteId !== null && current.identity.remoteId !== incoming) {\n throw new Error(\n `Offline replica remote id is immutable: current=${String(current.identity.remoteId)}, incoming=${String(incoming)}.`,\n );\n }\n return incoming;\n }\n\n #initialRemoteId(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n current: OfflineGeneratedRemoteId | null,\n incoming: OfflineGeneratedRemoteId | null | undefined,\n ): OfflineGeneratedRemoteId | null {\n if (incoming === null || incoming === undefined) return current;\n assertOfflineReplicaGeneratedRemoteId(schema, incoming);\n if (current !== null && current !== incoming) {\n throw new Error(`Offline replica remote id is immutable: current=${String(current)}, incoming=${String(incoming)}.`);\n }\n return incoming;\n }\n\n #assertRemoteIdHint(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n current: OfflineGeneratedRemoteId | null,\n hint: OfflineGeneratedRemoteId | null | undefined,\n ): void {\n if (hint === null || hint === undefined) return;\n assertOfflineReplicaGeneratedRemoteId(schema, hint);\n if (current !== null && current !== hint) {\n throw new Error(`Offline replica remoteId hint does not match current=${String(current)}: incoming=${String(hint)}.`);\n }\n }\n\n #assertCommandResultIdentity(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n current: OfflineReplicaRow,\n result: OfflineCommandResult,\n ): void {\n if (result.clearRemoteId === true && schema.identity.kind !== 'generated') {\n throw new Error(`Offline command cannot clear remoteId for source \"${schema.sourceKey}\".`);\n }\n if (schema.identity.kind === 'naturalKey' && result.remoteId !== undefined) {\n throw new Error(`Offline command returned generated remote id for naturalKey source \"${schema.sourceKey}\".`);\n }\n if (schema.identity.kind !== 'generated' && result.remoteId !== undefined) {\n throw new Error(`Offline command returned generated remote id for source \"${schema.sourceKey}\" without generated identity.`);\n }\n if (schema.identity.kind === 'naturalKey' && result.confirmedValues !== undefined) {\n const currentKey =\n current.identity.kind === 'natural' ? current.identity.naturalKey : offlineNaturalKeyFromValues(schema, current.values)!;\n const confirmedKey = offlineNaturalKeyFromValues(schema, result.confirmedValues)!;\n if (\n canonicalOfflineRemoteIdentity(schema, { naturalKey: currentKey }) !==\n canonicalOfflineRemoteIdentity(schema, { naturalKey: confirmedKey })\n ) {\n throw new Error(`Offline replica naturalKey is immutable for \"${schema.sourceKey}\".`);\n }\n }\n }\n\n async #discoverScopes(generation = this.#generation): Promise<boolean> {\n const session = await this.#context.getSession();\n if (!this.#isCurrent(generation)) return false;\n if (!session) {\n return false;\n }\n this.#assertSessionPrincipalBoundary(session);\n this.#setActiveUser(session.userId);\n this.#knownScopes.clear();\n for (const scope of session.scopes) this.#knownScopes.set(this.#scopeKey(scope), scope);\n await this.#restorePendingPullScopes(session.userId, generation);\n await this.#prunePullAttentions(session.userId, generation);\n return true;\n }\n\n async #discoverLocalScopes(generation = this.#generation): Promise<boolean> {\n const session = await this.#getLocalSession();\n if (!this.#isCurrent(generation)) return false;\n if (!session) {\n this.#activeUserId = null;\n this.#knownScopes.clear();\n this.#pullAttentions.set([]);\n return true;\n }\n this.#assertSessionPrincipalBoundary(session);\n this.#setActiveUser(session.userId);\n this.#knownScopes.clear();\n for (const scope of session.scopes) this.#knownScopes.set(this.#scopeKey(scope), scope);\n await this.#restorePendingPullScopes(session.userId, generation);\n await this.#prunePullAttentions(session.userId, generation);\n return true;\n }\n\n #getLocalSession(): Promise<OfflineSyncSession | null> {\n return this.#context.getLocalSession?.() ?? this.#context.getSession();\n }\n\n #setActiveUser(userId: OfflinePrincipalId): void {\n if (this.#activeUserId === userId) return;\n this.#knownScopes.clear();\n this.#pendingPullScopes.clear();\n this.#pullAttentions.set([]);\n this.#activeUserId = userId;\n this.#lastCommandCreatedAt = 0;\n }\n\n #assertSessionPrincipalBoundary(session: OfflineSyncSession): void {\n canonicalOfflinePrincipalId(session.userId);\n for (const scope of session.scopes) {\n if (scope.userId !== session.userId) {\n throw new Error('Offline sync session scope belongs to a different principal.');\n }\n }\n }\n\n async #readKnownCommands(): Promise<OfflineCommand[]> {\n const userId = this.#activeUserId;\n if (userId === null) return [];\n const commands = (await this.#commandsForUser(userId))\n .filter((command) => this.#knownScopes.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })))\n .sort(compareOfflineCommands);\n this.#rememberCreatedAt(commands);\n return commands;\n }\n\n async #nextCommandCreatedAt(userId: OfflinePrincipalId): Promise<number> {\n const commands = await this.#commandsForUser(userId);\n this.#rememberCreatedAt(commands);\n const createdAt = Math.max(Date.now(), this.#lastCommandCreatedAt + 1);\n this.#lastCommandCreatedAt = createdAt;\n return createdAt;\n }\n\n #rememberCreatedAt(commands: readonly OfflineCommand[]): void {\n for (const command of commands) this.#lastCommandCreatedAt = Math.max(this.#lastCommandCreatedAt, command.createdAt);\n }\n\n async #refreshState(generation = this.#generation): Promise<void> {\n const commands = await this.#readKnownCommands();\n const attentions =\n this.#activeUserId !== null && this.#repository.getPullAttentions ? await this.#repository.getPullAttentions(this.#activeUserId) : [];\n if (!this.#isCurrent(generation)) return;\n this.#commands.set(commands);\n this.#pullAttentions.set(attentions);\n const nextRetry = commands\n .filter((command) => command.state === 'retry_wait' && command.retryAt !== null)\n .reduce<number | null>((earliest, command) => Math.min(earliest ?? command.retryAt!, command.retryAt!), null);\n this.#scheduleRetry(nextRetry);\n }\n\n #scheduleRetry(retryAt: number | null): void {\n if (this.#retryTimer) clearTimeout(this.#retryTimer);\n this.#retryTimer = null;\n if (retryAt === null) return;\n this.#retryTimer = setTimeout(\n () => {\n this.#retryTimer = null;\n if (this.#network.connected()) this.#flushInBackground();\n },\n Math.max(0, retryAt - Date.now()),\n );\n }\n\n #invalidateFlush(): void {\n this.#generation += 1;\n this.#flushPromise = null;\n this.#partialFlushInFlight = false;\n this.#chainedFullFlush = null;\n this.#scheduleRetry(null);\n }\n\n #isCurrent(generation: number): boolean {\n return generation === this.#generation;\n }\n\n async #restoreInterruptedCommands(): Promise<void> {\n const commands = await this.#readKnownCommands();\n await Promise.all(\n commands\n .filter((command) => command.state === 'sending')\n .map((command) =>\n this.#repository.putCommand({\n ...command,\n state: 'pending',\n serverCommitUnknown: command.serverCommitUnknown ?? true,\n }),\n ),\n );\n }\n\n #claimSendingCommand(command: OfflineCommand, generation: number): Promise<OfflineCommand | null> {\n const transition = this.#serializeReplicaMutation(async (repository) => {\n if (!this.#isCurrent(generation)) return null;\n const scope = { userId: command.userId, scopeId: command.scopeId };\n const current = (await this.#repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);\n if (!current || !['pending', 'retry_wait'].includes(current.state)) return null;\n const sending: OfflineCommand = {\n ...current,\n state: 'sending',\n attempts: current.attempts + 1,\n retryAt: null,\n lastErrorCode: null,\n };\n await repository.putCommand(sending);\n return sending;\n });\n this.#sendingTransitions.add(transition);\n void transition.then(\n () => this.#sendingTransitions.delete(transition),\n () => this.#sendingTransitions.delete(transition),\n );\n return transition;\n }\n\n #markTransportStarted(command: OfflineCommand, generation: number): Promise<OfflineCommand | null> {\n return this.#serializeReplicaMutation(async (repository) => {\n if (!this.#isCurrent(generation)) return null;\n const scope = { userId: command.userId, scopeId: command.scopeId };\n const current = (await this.#repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);\n if (!current || current.state !== 'sending') return null;\n const transportCommand = { ...current, serverCommitUnknown: true };\n await repository.putCommand(transportCommand);\n return transportCommand;\n });\n }\n\n async #restorePendingPullScopes(userId: OfflinePrincipalId, generation: number): Promise<void> {\n const commands = await this.#readKnownCommands();\n if (!this.#isCurrent(generation) || this.#activeUserId !== userId) return;\n this.#pendingPullScopes.clear();\n for (const command of commands) {\n if (command.state !== 'awaiting_pull') continue;\n const scope = { userId: command.userId, scopeId: command.scopeId };\n const key = this.#scopeKey(scope);\n this.#pendingPullScopes.set(key, scope);\n }\n }\n\n async #prunePullAttentions(userId: OfflinePrincipalId, generation: number): Promise<void> {\n if (!this.#repository.getPullAttentions) return;\n const attentions = await this.#repository.getPullAttentions(userId);\n if (!this.#isCurrent(generation) || this.#activeUserId !== userId) return;\n const currentKeys = new Set(this.#knownScopes.keys());\n const revoked = attentions.filter((attention) => !currentKeys.has(this.#scopeKey(attention)));\n if (revoked.length > 0) {\n await this.#repository.transactReplica({ removePullAttentions: revoked });\n }\n }\n\n async #markScopeReconciled(scope: OfflineScope, generation: number): Promise<void> {\n if (!this.#isCurrent(generation)) return;\n await this.#repository.transactReplica({\n removePullAttentions: [scope],\n });\n if (!this.#isCurrent(generation)) return;\n this.#pendingPullScopes.delete(this.#scopeKey(scope));\n }\n\n async #waitForSendingTransitions(): Promise<void> {\n await Promise.allSettled([...this.#sendingTransitions]);\n }\n\n #canonicalJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map((item) => this.#canonicalJson(item)).join(',')}]`;\n if (value !== null && typeof value === 'object') {\n if (Object.getPrototypeOf(value) !== Object.prototype) {\n throw new OfflinePayloadValidationError();\n }\n return `{${Object.entries(value)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n .map(([key, item]) => `${JSON.stringify(key)}:${this.#canonicalJson(item)}`)\n .join(',')}}`;\n }\n if (typeof value === 'number' && !Number.isFinite(value)) {\n throw new OfflinePayloadValidationError();\n }\n const serialized = JSON.stringify(value);\n if (typeof serialized !== 'string') {\n throw new OfflinePayloadValidationError();\n }\n return serialized;\n }\n\n #scopeKey(scope: OfflineScope): string {\n return `${canonicalOfflinePrincipalId(scope.userId)}:${scope.scopeId}`;\n }\n}\n\nfunction compareOfflineCommands(left: OfflineCommand, right: OfflineCommand): number {\n return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);\n}\n","import { computed, ErrorHandler, inject, Injectable, InjectionToken, signal } from '@angular/core';\nimport { OFFLINE_KIT_OPTIONS, type OfflineMutationPersistenceAdapter } from './offline-kit-options';\nimport { OfflineMutationAdmissionService } from './offline-mutation-admission.service';\nimport { OfflineNetworkService } from './offline-network.service';\nimport { OfflineSyncService } from './offline-sync.service';\n\n/** Raised when disabling requires pending commands to be synchronized while transport is offline. */\nexport class OfflineMutationPersistenceRequiresOnlineError extends Error {\n constructor() {\n super('Pending offline mutations must be synchronized before persistence can be disabled.');\n this.name = 'OfflineMutationPersistenceRequiresOnlineError';\n }\n}\n\n/** Raised when pending commands remain after the disable transition attempted a flush. */\nexport class OfflineMutationPersistencePendingError extends Error {\n constructor(readonly pendingCount: number) {\n super('Pending offline mutations remain after synchronization.');\n this.name = 'OfflineMutationPersistencePendingError';\n }\n}\n\ntype OfflineMutationPersistenceState = 'initializing' | 'enabled' | 'disabling' | 'disabled';\n\nconst settledMutationPersistence = async (): Promise<void> => undefined;\n\nfunction invokeMutationPersistence<T>(operation: () => Promise<T>): Promise<T> {\n return new Promise<T>((resolve) => resolve(operation()));\n}\n\nfunction reportMutationPersistenceError(errorHandler: ErrorHandler, error: unknown): void {\n try {\n errorHandler.handleError(error);\n } catch {\n // Preference failure already degraded safely to disabled. Telemetry must not stop bootstrap.\n }\n}\n\n/** Read-only mutation admission signal consumed by the HTTP interceptor. */\nexport const OFFLINE_MUTATION_PERSISTENCE_ENABLED = new InjectionToken<() => boolean>('OFFLINE_MUTATION_PERSISTENCE_ENABLED', {\n factory: () => () => true,\n});\n\n/** Product adapter used by Kit to persist the device-local mutation preference. */\nexport const OFFLINE_MUTATION_PERSISTENCE_ADAPTER = new InjectionToken<OfflineMutationPersistenceAdapter | null>(\n 'OFFLINE_MUTATION_PERSISTENCE_ADAPTER',\n { factory: () => null },\n);\n\n/** Controls whether Kit accepts new durable mutations while leaving replica reads enabled. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineMutationPersistenceService {\n readonly #options = inject(OFFLINE_KIT_OPTIONS);\n readonly #errorHandler = inject(ErrorHandler);\n readonly #persistence = inject(OFFLINE_MUTATION_PERSISTENCE_ADAPTER);\n readonly #network = inject(OfflineNetworkService);\n readonly #sync = inject(OfflineSyncService);\n readonly #admission = inject(OfflineMutationAdmissionService);\n readonly #configured = this.#options.mode !== 'readCacheOnly' && this.#options.mutationPersistence !== undefined;\n readonly #state = signal<OfflineMutationPersistenceState>(this.#configured ? 'initializing' : 'enabled');\n #initializePromise: Promise<void> | null = null;\n #transitionTail: Promise<void> = settledMutationPersistence();\n #transitionRevision = 0;\n #persistedEnabled = !this.#configured;\n #latestTransition: { enabled: boolean; promise: Promise<void>; revision: number } | null = null;\n\n /** Whether the product configured a device-local mutation persistence preference. */\n readonly available = this.#configured;\n /** Whether new durable Outbox mutations are currently accepted. */\n readonly enabled = computed(() => this.#state() === 'enabled');\n /** Whether Kit is draining accepted and pending mutations before disabling. */\n readonly changing = computed(() => this.#state() === 'disabling');\n\n /** Loads the durable preference before Kit initializes repository-backed services. */\n async initialize(): Promise<void> {\n if (!this.#configured) {\n this.#admission.open();\n return;\n }\n await (this.#initializePromise ??= this.#loadInitialPreference());\n }\n\n /**\n * Enables or disables new durable mutations.\n *\n * Disabling closes admission synchronously, waits for already admitted commits,\n * flushes existing commands, verifies an empty Outbox, and only then persists OFF.\n */\n setEnabled(enabled: boolean): Promise<void> {\n if (!this.#configured) return settledMutationPersistence();\n const initialization = this.initialize();\n const latest = this.#latestTransition;\n if (latest?.enabled === enabled) return latest.promise;\n if (!latest && ((enabled && this.#state() === 'enabled') || (!enabled && this.#state() === 'disabled'))) {\n return settledMutationPersistence();\n }\n\n const revision = ++this.#transitionRevision;\n if (!enabled) {\n this.#state.set('disabling');\n void this.#admission.close();\n }\n const transition = this.#transitionTail.then(() => initialization).then(() => this.#applyTransition(enabled, revision));\n this.#transitionTail = transition.catch(() => undefined);\n const promise = transition.finally(() => {\n if (this.#latestTransition?.revision === revision) this.#latestTransition = null;\n });\n this.#latestTransition = { enabled, promise, revision };\n return promise;\n }\n\n async #loadInitialPreference(): Promise<void> {\n const persistence = this.#requiredPersistence();\n return invokeMutationPersistence(() => persistence.loadEnabled()).then(\n (stored) => {\n this.#persistedEnabled = stored ?? this.#options.mutationPersistence?.defaultEnabled ?? true;\n if (this.#transitionRevision === 0) {\n this.#state.set(this.#persistedEnabled ? 'enabled' : 'disabled');\n if (this.#persistedEnabled) this.#admission.open();\n }\n },\n async (error: unknown) => {\n this.#persistedEnabled = false;\n if (this.#transitionRevision === 0) this.#state.set('disabled');\n await this.#admission.close();\n reportMutationPersistenceError(this.#errorHandler, error);\n },\n );\n }\n\n #applyTransition(enabled: boolean, revision: number): Promise<void> {\n if (revision !== this.#transitionRevision) return settledMutationPersistence();\n const transition = enabled ? this.#enable(revision) : this.#disable(revision);\n return transition.catch((error: unknown) => {\n if (revision === this.#transitionRevision) {\n this.#state.set(this.#persistedEnabled ? 'enabled' : 'disabled');\n if (this.#persistedEnabled) this.#admission.open();\n }\n return Promise.reject(error);\n });\n }\n\n async #enable(revision: number): Promise<void> {\n await this.#requiredPersistence().saveEnabled(true);\n this.#persistedEnabled = true;\n if (revision !== this.#transitionRevision) return;\n this.#state.set('enabled');\n this.#admission.open();\n }\n\n async #disable(revision: number): Promise<void> {\n await this.#admission.close();\n if (revision !== this.#transitionRevision) return;\n await this.#sync.initialize({ flush: false });\n if (revision !== this.#transitionRevision) return;\n const pendingBeforeFlush = this.#sync.pendingCount();\n if (pendingBeforeFlush > 0) {\n if (this.#network.state() === 'offline') throw new OfflineMutationPersistenceRequiresOnlineError();\n await this.#sync.flush();\n }\n if (revision !== this.#transitionRevision) return;\n const pendingCount = this.#sync.pendingCount();\n if (pendingCount > 0) throw new OfflineMutationPersistencePendingError(pendingCount);\n await this.#requiredPersistence().saveEnabled(false);\n this.#persistedEnabled = false;\n if (revision === this.#transitionRevision) this.#state.set('disabled');\n }\n\n #requiredPersistence(): OfflineMutationPersistenceAdapter {\n if (!this.#persistence) throw new Error('Offline mutation persistence adapter is not provided.');\n return this.#persistence;\n }\n}\n","import { inject, Injectable, signal } from '@angular/core';\nimport type { OfflineScope } from './offline-repository';\nimport type { OfflinePrincipalId } from './offline-identity';\nimport { OFFLINE_REPOSITORY } from './offline-repository';\n\n/** Persisted identity and partition boundary for one authenticated local replica. */\nexport interface OfflineSessionManifest {\n userId: OfflinePrincipalId;\n readonly scopeIds: readonly string[];\n /** Authentication-provider subject used to distinguish users on a shared device. */\n authSubject: string | null;\n updatedAt: number;\n}\n\n/** Checks the authenticated subject and optional scope against one persisted session boundary. */\nexport function offlineSessionManifestAllows(\n manifest: OfflineSessionManifest | null,\n authSubject: string | null,\n scopeId?: string,\n): manifest is OfflineSessionManifest {\n if (!manifest || manifest.authSubject !== authSubject) return false;\n return scopeId === undefined || manifest.scopeIds.includes(scopeId);\n}\n\n/** Structural lease used to reject stale asynchronous session commits. */\nexport interface OfflineSessionTransitionLease {\n isCurrent(): boolean;\n}\n\n/** Owns activation and cleanup of the authenticated local-replica boundary. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineSessionService {\n readonly #repository = inject(OFFLINE_REPOSITORY);\n readonly #activeManifest = signal<OfflineSessionManifest | null>(null);\n #initialized = false;\n #localAccessThisRun = false;\n #remoteActivatedThisRun = false;\n\n readonly activeManifest = this.#activeManifest.asReadonly();\n\n async initialize(): Promise<void> {\n if (this.#initialized) return;\n await this.#repository.initialize();\n const userId = await this.#repository.getLastUserId();\n if (userId !== null) {\n const manifest = await this.#repository.getSessionManifest<OfflineSessionManifest>(userId);\n this.#activeManifest.set(manifest ?? { userId, scopeIds: [], authSubject: null, updatedAt: 0 });\n }\n this.#initialized = true;\n }\n\n async activateSession(userId: OfflinePrincipalId, scopeIds: readonly string[], authSubject: string | null): Promise<void>;\n async activateSession(\n userId: OfflinePrincipalId,\n scopeIds: readonly string[],\n authSubject: string | null,\n lease: OfflineSessionTransitionLease,\n ): Promise<boolean>;\n async activateSession(\n userId: OfflinePrincipalId,\n scopeIds: readonly string[],\n authSubject: string | null,\n lease?: OfflineSessionTransitionLease,\n ): Promise<void | boolean> {\n await this.initialize();\n if (lease && !lease.isCurrent()) return false;\n const normalizedScopeIds = [...new Set(scopeIds)].sort((a, b) => a.localeCompare(b));\n const previousUserId = await this.#repository.getLastUserId();\n if (lease && !lease.isCurrent()) return false;\n let previous = previousUserId === userId ? ((await this.#repository.getSessionManifest<OfflineSessionManifest>(userId)) ?? null) : null;\n if (lease && !lease.isCurrent()) return false;\n // A changed provider subject is a different person even when the product reuses its numeric id.\n // This deliberately also clears legacy null -> known subject and known subject -> null transitions.\n if (previousUserId !== null && (previousUserId !== userId || previous?.authSubject !== authSubject)) {\n await this.#repository.clearUser(previousUserId);\n if (lease && !lease.isCurrent()) return false;\n previous = null;\n }\n const active = new Set(normalizedScopeIds);\n await Promise.all(\n (previous?.scopeIds ?? [])\n .filter((scopeId) => !active.has(scopeId))\n .map((scopeId) => this.#repository.clearScope({ userId, scopeId })),\n );\n if (lease && !lease.isCurrent()) return false;\n\n const manifest: OfflineSessionManifest = {\n userId,\n scopeIds: normalizedScopeIds,\n authSubject,\n updatedAt: Date.now(),\n };\n await this.#repository.setLastUserId(userId);\n if (lease && !lease.isCurrent()) return false;\n await this.#repository.putSessionManifest(userId, manifest);\n if (lease && !lease.isCurrent()) return false;\n this.#activeManifest.set(manifest);\n this.#localAccessThisRun = true;\n this.#remoteActivatedThisRun = true;\n return lease ? true : undefined;\n }\n\n async clearActiveSession(): Promise<void> {\n await this.initialize();\n const userId = await this.#repository.getLastUserId();\n if (userId !== null) await this.#repository.clearUser(userId);\n this.#activeManifest.set(null);\n this.#localAccessThisRun = false;\n this.#remoteActivatedThisRun = false;\n }\n\n /** Immediately revoke local and remote runtime access while durable cleanup is pending. */\n revokeAccess(): void {\n this.#localAccessThisRun = false;\n this.#remoteActivatedThisRun = false;\n }\n\n /** Disable remote pull/replay eligibility while retaining the verified local manifest. */\n async suspendRemoteSession(): Promise<void> {\n await this.initialize();\n this.#remoteActivatedThisRun = false;\n }\n\n /**\n * Returns the persisted identity boundary for local-only route access.\n *\n * @remarks\n * This does not activate the sync context. Call it only after the authentication authority has\n * been classified as unavailable, never after explicit sign-out or HTTP 401/403. Legacy\n * manifests without an authentication-provider subject are rejected.\n *\n * @param authSubject - A currently known provider subject. When supplied, it must match the\n * persisted subject.\n */\n async getOfflineAccessManifest(authSubject?: string | null): Promise<OfflineSessionManifest | null> {\n await this.initialize();\n const manifest = this.#activeManifest();\n if (!manifest?.authSubject || (authSubject !== undefined && manifest.authSubject !== authSubject)) {\n return null;\n }\n return { ...manifest, scopeIds: [...manifest.scopeIds] };\n }\n\n /**\n * Activates a previously verified manifest for local replica and outbox access only.\n *\n * @remarks\n * This never enables pull or command replay. A later successful remote authentication must call\n * {@link activateSession} before synchronization can use transport.\n *\n * @param authSubject - A currently known provider subject. When supplied, it must match the\n * persisted subject.\n */\n async activateOfflineSession(authSubject?: string | null, lease?: OfflineSessionTransitionLease): Promise<OfflineSessionManifest | null> {\n const manifest = await this.getOfflineAccessManifest(authSubject);\n if (lease && !lease.isCurrent()) return null;\n this.#localAccessThisRun = manifest !== null;\n this.#remoteActivatedThisRun = false;\n return manifest;\n }\n\n /** Returns the session allowed to use the local replica and append outbox commands. */\n async getLocalSession(): Promise<{ userId: OfflinePrincipalId; scopes: OfflineScope[] } | null> {\n await this.initialize();\n return this.#localAccessThisRun ? this.#sessionFromManifest() : null;\n }\n\n /** Returns the remotely authenticated session eligible for pull and command replay. */\n async getSession(): Promise<{ userId: OfflinePrincipalId; scopes: OfflineScope[] } | null> {\n await this.initialize();\n return this.#remoteActivatedThisRun ? this.#sessionFromManifest() : null;\n }\n\n #sessionFromManifest(): { userId: OfflinePrincipalId; scopes: OfflineScope[] } | null {\n const manifest = this.#activeManifest();\n return manifest\n ? { userId: manifest.userId, scopes: manifest.scopeIds.map((scopeId) => ({ userId: manifest.userId, scopeId })) }\n : null;\n }\n}\n","/**\n * Closed set of reasons local offline storage failed to become ready.\n *\n * Product policy should branch on this discriminant rather than English message text.\n */\nexport type OfflineStorageUnavailableReason =\n | 'encryption_key_unavailable'\n | 'core_schema_incompatible'\n | 'replica_schema_mismatch'\n | 'migration_missing'\n | 'storage_unavailable';\n\n/**\n * Local offline storage could not be opened or migrated without risking data loss.\n *\n * Prefer `instanceof` / {@link OfflineStorageUnavailableError.reason} over message text.\n * The original failure is preserved on {@link Error.cause}. Kit never deletes Outbox or\n * replica rows in response to this error; recovery is product-owned and explicit.\n */\nexport class OfflineStorageUnavailableError extends Error {\n /** Stable machine-readable discriminator for storage initialization failures. */\n static readonly code = 'OFFLINE_STORAGE_UNAVAILABLE' as const;\n\n readonly code = OfflineStorageUnavailableError.code;\n\n constructor(\n readonly reason: OfflineStorageUnavailableReason,\n message: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = 'OfflineStorageUnavailableError';\n }\n}\n\n/**\n * Coordinator view of encrypted local storage after app initialization.\n *\n * `unavailable` is reached only when the product opted into online-only startup via\n * `onStorageUnavailable` (or when inspecting state after a thrown failure).\n */\nexport type OfflineStorageState =\n | { readonly status: 'initializing' }\n | { readonly status: 'ready' }\n | { readonly status: 'unavailable'; readonly error: OfflineStorageUnavailableError };\n\n/** Narrows an unknown failure to {@link OfflineStorageUnavailableError}. */\nexport function isOfflineStorageUnavailableError(error: unknown): error is OfflineStorageUnavailableError {\n return error instanceof OfflineStorageUnavailableError;\n}\n","import { computed, inject, Injectable, signal } from '@angular/core';\nimport type { OfflinePrincipalId } from './offline-identity';\nimport { OFFLINE_KIT_OPTIONS } from './offline-kit-options';\nimport { OfflineNetworkService } from './offline-network.service';\nimport { OfflineMutationPersistenceService } from './offline-mutation-persistence.service';\nimport { OFFLINE_REPOSITORY } from './offline-repository';\nimport { OfflineSessionService } from './offline-session.service';\nimport type { OfflineSessionManifest, OfflineSessionTransitionLease } from './offline-session.service';\nimport { OfflineStorageUnavailableError, type OfflineStorageState } from './offline-storage';\nimport { OfflineSyncService } from './offline-sync.service';\n\n/** User choice when logout encounters unconfirmed local mutations. */\nexport type OfflineLogoutAction = 'sync' | 'discard' | 'cancel';\n\nconst settledTransition = async (): Promise<void> => undefined;\n\n/** Options for {@link OfflineCoordinatorService.resumeRemoteSession}. */\nexport interface OfflineResumeRemoteSessionOptions {\n readonly foregroundScopeIds?: readonly string[];\n}\n\n/** Coordinates local persistence, session boundaries, network state, and outbox synchronization. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineCoordinatorService {\n readonly #repository = inject(OFFLINE_REPOSITORY);\n readonly #network = inject(OfflineNetworkService);\n readonly #mutationPersistence = inject(OfflineMutationPersistenceService);\n readonly #sync = inject(OfflineSyncService);\n readonly #session = inject(OfflineSessionService);\n readonly #options = inject(OFFLINE_KIT_OPTIONS);\n readonly #storageState = signal<OfflineStorageState>({ status: 'initializing' });\n #localInitialization: Promise<void> | null = null;\n #syncInitialization: Promise<void> | null = null;\n #runtimeInitialization: Promise<void> | null = null;\n #transitionRevision = 0;\n #transitionTail: Promise<void> = settledTransition();\n\n /**\n * Local storage readiness after {@link initialize}.\n *\n * When `unavailable`, the product opted into online-only startup; replica/outbox APIs must not be used.\n */\n readonly storageState = this.#storageState.asReadonly();\n /**\n * Product-policy guard: `true` only when encrypted local storage finished initialization successfully.\n *\n * Use this (or {@link storageState}) to disable offline mutations and replica reads when storage is unavailable.\n */\n readonly isStorageReady = computed(() => this.#storageState().status === 'ready');\n\n readonly networkState = this.#network.state;\n readonly syncState = this.#sync.syncState;\n readonly pendingCount = this.#sync.pendingCount;\n readonly conflicts = this.#sync.conflicts;\n /** Device-local control for accepting new durable Outbox mutations. */\n readonly mutationPersistence = this.#mutationPersistence;\n\n /** Opens local storage and restores its persisted session boundary without waiting for network discovery. */\n initializeLocal(): Promise<void> {\n this.#localInitialization ??= this.#initializeLocal();\n return this.#localInitialization;\n }\n\n /** Opens the local substrate, starts network discovery, then initializes synchronization. */\n initialize(): Promise<void> {\n this.#runtimeInitialization ??= this.#initializeRuntime();\n return this.#runtimeInitialization;\n }\n\n async #initializeLocal(): Promise<void> {\n await this.#mutationPersistence.initialize();\n const initializeSubstrate = async (): Promise<void> => {\n await this.#repository.initialize();\n await this.#session.initialize();\n };\n const substrateReady = await initializeSubstrate().then(\n () => true,\n async (error: unknown) => {\n const typed = this.#asStorageUnavailable(error);\n this.#storageState.set({ status: 'unavailable', error: typed });\n const onUnavailable = this.#options.onStorageUnavailable;\n if (!onUnavailable) throw typed;\n await onUnavailable(typed);\n return false;\n },\n );\n if (!substrateReady) return;\n this.#storageState.set({ status: 'ready' });\n }\n\n async #initializeRuntime(): Promise<void> {\n const networkReady = this.#network.initialize();\n await Promise.all([this.#initializeSync(), networkReady]);\n }\n\n #initializeSync(): Promise<void> {\n this.#syncInitialization ??= this.#initializeSyncOnce();\n return this.#syncInitialization;\n }\n\n async #initializeSyncOnce(): Promise<void> {\n await this.initializeLocal();\n if (this.#storageUnavailable()) return;\n await this.#sync.initialize({ flush: false });\n }\n\n async activateSession(userId: OfflinePrincipalId, scopeIds: readonly string[], authSubject: string | null): Promise<void> {\n if (!(await this.prepareRemoteSession(userId, scopeIds, authSubject))) return;\n await this.resumeRemoteSession();\n }\n\n /** Installs a remotely verified identity without starting pull or outbox replay. */\n async prepareRemoteSession(\n userId: OfflinePrincipalId,\n scopeIds: readonly string[],\n authSubject: string | null,\n authLease?: OfflineSessionTransitionLease,\n ): Promise<boolean> {\n const revision = ++this.#transitionRevision;\n const lease = this.#lease(revision, authLease);\n await this.initialize();\n if (this.#storageUnavailable()) return true;\n if (!lease.isCurrent()) return false;\n return this.#enqueueTransition(async () => {\n await this.#sync.resetSession();\n await this.#session.suspendRemoteSession();\n if (!lease.isCurrent()) return false;\n return this.#session.activateSession(userId, scopeIds, authSubject, lease);\n });\n }\n\n /** Starts pull and outbox replay after the caller has published remote access. */\n async resumeRemoteSession(options?: OfflineResumeRemoteSessionOptions): Promise<void> {\n await this.initialize();\n if (this.#storageUnavailable()) return;\n await this.#sync.refreshSession(options?.foregroundScopeIds);\n }\n\n /**\n * Activates a restored identity for local replica/outbox use without enabling transport sync.\n */\n async activateOfflineSession(\n authSubject?: string | null,\n authLease?: OfflineSessionTransitionLease,\n ): Promise<OfflineSessionManifest | null> {\n const revision = ++this.#transitionRevision;\n const lease = this.#lease(revision, authLease);\n await this.#initializeSync();\n if (this.#storageUnavailable()) return null;\n if (!lease.isCurrent()) return null;\n return this.#enqueueTransition(async () => {\n await this.#sync.resetSession();\n if (!lease.isCurrent()) return null;\n const manifest = await this.#session.activateOfflineSession(authSubject, lease);\n if (manifest && lease.isCurrent()) await this.#sync.refreshLocalSession();\n return lease.isCurrent() ? manifest : null;\n });\n }\n\n async clearActiveSession(): Promise<void> {\n this.#sync.revokeSession();\n this.#session.revokeAccess();\n ++this.#transitionRevision;\n await this.#initializeSync();\n if (this.#storageUnavailable()) return;\n return this.#enqueueTransition(async () => {\n await this.#sync.resetSession();\n await this.#session.clearActiveSession();\n });\n }\n\n async prepareLogout(action: OfflineLogoutAction): Promise<boolean> {\n await this.initialize();\n if (this.#storageUnavailable()) return action !== 'cancel';\n if (action === 'cancel') return false;\n if (action === 'discard') {\n await this.#sync.discardAllPending();\n return true;\n }\n await this.#sync.flush();\n return this.#sync.pendingCount() === 0;\n }\n\n async flush(): Promise<void> {\n await this.initialize();\n if (this.#storageUnavailable()) return;\n return this.#sync.flush();\n }\n\n #asStorageUnavailable(error: unknown): OfflineStorageUnavailableError {\n if (error instanceof OfflineStorageUnavailableError) return error;\n const message = error instanceof Error ? error.message : 'Offline storage is unavailable.';\n return new OfflineStorageUnavailableError('storage_unavailable', message || 'Offline storage is unavailable.', {\n cause: error,\n });\n }\n\n #storageUnavailable(): boolean {\n return this.#storageState().status === 'unavailable';\n }\n\n #lease(revision: number, authLease?: OfflineSessionTransitionLease): OfflineSessionTransitionLease {\n return { isCurrent: () => revision === this.#transitionRevision && (authLease?.isCurrent() ?? true) };\n }\n\n #enqueueTransition<T>(operation: () => Promise<T>): Promise<T> {\n const transition = this.#transitionTail.then(operation, operation);\n this.#transitionTail = transition.then(\n () => undefined,\n () => undefined,\n );\n return transition;\n }\n}\n","import { inject } from '@angular/core';\nimport { canonicalOfflinePrincipalId, type OfflinePrincipalId } from './offline-identity';\nimport { toObservable } from '@angular/core/rxjs-interop';\nimport type { RouterStateSnapshot } from '@angular/router';\nimport type { KitAuthAccessLease, KitAuthConfig, KitRemoteAccessRecovery } from '@rdlabo/ionic-angular-kit';\nimport type { Observable } from 'rxjs';\nimport { distinctUntilChanged, map } from 'rxjs/operators';\nimport { OfflineCoordinatorService } from './offline-coordinator.service';\n\n/** Remote identity fields required to activate an offline session boundary. */\nexport interface OfflineRemoteIdentity {\n readonly userId: OfflinePrincipalId;\n readonly scopeIds: readonly string[];\n readonly authSubject: string;\n /** Scope partitions to pull eagerly on automatic resume; remaining scopes require an explicit flush. */\n readonly foregroundScopeIds?: readonly string[];\n}\n\n/** Phase that distinguishes route authorization from background remote recovery. */\nexport type OfflineAuthExchangePhase = 'authorize' | 'recover';\n\n/** Context passed to the product credential exchange callback. */\nexport interface OfflineAuthExchangeContext {\n readonly phase: OfflineAuthExchangePhase;\n readonly state?: RouterStateSnapshot;\n readonly lease: KitAuthAccessLease;\n}\n\n/** Context supplied after remote transport has resumed for the same authenticated identity. */\nexport interface OfflineAuthResumeContext<TIdentity extends OfflineRemoteIdentity> {\n readonly phase: OfflineAuthExchangePhase;\n readonly state?: RouterStateSnapshot;\n readonly lease: KitAuthAccessLease;\n readonly identity: TIdentity;\n}\n\n/** Options for {@link createOfflineAuthBridge}. */\nexport interface CreateOfflineAuthBridgeOptions<TIdentity extends OfflineRemoteIdentity = OfflineRemoteIdentity> {\n /** Coordinator override for tests or custom runtimes; otherwise injected from the current context. */\n readonly offline?: OfflineCoordinatorService;\n /**\n * Exchanges a stored or refreshed credential for a remote identity.\n *\n * @returns `null` or `false` when the product declines activation without treating it as an error.\n */\n readonly exchange: (context: OfflineAuthExchangeContext) => Promise<TIdentity | null | false>;\n /** Provider subject currently known to the product auth layer. */\n readonly currentAuthSubject: () => string | null | undefined;\n /** Classifies transport unavailability for guard fallback and recovery retry. */\n readonly isUnavailableError: (error: unknown) => boolean;\n /** Remote availability stream; defaults to `offline.networkState !== 'offline'`. */\n readonly availability?: () => Observable<boolean>;\n /** Optional stronger identity check in addition to the required auth-subject match. */\n readonly isIdentityCurrent?: (identity: TIdentity) => boolean;\n /** Optional product hook after the kit publishes remote access and transport resumes. */\n readonly onRemoteResumed?: (context: OfflineAuthResumeContext<TIdentity>) => Promise<void>;\n /** Delay before {@link KitAuthRecoveryService} retries recovery while local access remains active. */\n readonly retryDelayMs?: number;\n}\n\n/** {@link KitAuthConfig} hooks wired for offline-coordinated remote and local access. */\nexport type OfflineAuthBridgeConfig = Pick<KitAuthConfig, 'onAuthorized' | 'onUnavailable' | 'isUnavailableError' | 'remoteRecovery'>;\n\n/**\n * Builds the offline-aware {@link KitAuthConfig} fragment for guarded route activation and recovery.\n *\n * @remarks\n * The bridge owns `exchange` → {@link OfflineCoordinatorService.prepareRemoteSession} → kit\n * `grantRemote` → {@link OfflineCoordinatorService.resumeRemoteSession} ordering by returning\n * {@link KitRemoteAccessRecovery}. Product consent, error UI, and DTO mapping stay outside.\n *\n * @example\n * ```ts\n * provideKitAuth(() => ({\n * authState: () => auth.state$,\n * ...createOfflineAuthBridge({\n * exchange: async (ctx) => {\n * const identity = await auth.exchangeCredential(ctx);\n * const authSubject = auth.currentSubject();\n * return identity && authSubject ? { ...identity, authSubject } : false;\n * },\n * currentAuthSubject: () => auth.currentSubject(),\n * isUnavailableError: isOfflineFallbackError,\n * }),\n * redirects,\n * }));\n * ```\n */\nexport function createOfflineAuthBridge<TIdentity extends OfflineRemoteIdentity>(\n options: CreateOfflineAuthBridgeOptions<TIdentity>,\n): OfflineAuthBridgeConfig {\n const offline = options.offline ?? inject(OfflineCoordinatorService);\n const { exchange, currentAuthSubject, isUnavailableError, isIdentityCurrent, onRemoteResumed, retryDelayMs } = options;\n const defaultAvailability$ = options.availability\n ? undefined\n : toObservable(offline.networkState).pipe(\n map((state) => state !== 'offline'),\n distinctUntilChanged(),\n );\n const availability = options.availability ?? (() => defaultAvailability$!);\n\n const identityStillCurrent = (lease: KitAuthAccessLease, identity: TIdentity): boolean =>\n lease.isCurrent() && currentAuthSubject() === identity.authSubject && (isIdentityCurrent?.(identity) ?? true);\n\n const resolveRemoteAccess = async (\n phase: OfflineAuthExchangePhase,\n state: RouterStateSnapshot | undefined,\n lease: KitAuthAccessLease,\n ): Promise<KitRemoteAccessRecovery | false> => {\n if (!lease.isCurrent()) return false;\n const identity = await exchange({ phase, state, lease });\n if (!lease.isCurrent()) return false;\n if (identity === null || identity === false) return false;\n assertOfflineRemoteIdentity(identity);\n if (!identityStillCurrent(lease, identity)) return false;\n\n return {\n activate: async (activateLease) => {\n if (!identityStillCurrent(activateLease, identity)) return false;\n const identityLease: KitAuthAccessLease = {\n isCurrent: () => identityStillCurrent(activateLease, identity),\n };\n const prepared = await offline.prepareRemoteSession(identity.userId, identity.scopeIds, identity.authSubject, identityLease);\n return prepared && identityLease.isCurrent();\n },\n resume: async (resumeLease) => {\n const resumeStillCurrent = (): boolean =>\n (resumeLease?.isCurrent() ?? true) && currentAuthSubject() === identity.authSubject && (isIdentityCurrent?.(identity) ?? true);\n if (!resumeStillCurrent()) return;\n await offline.resumeRemoteSession(\n identity.foregroundScopeIds !== undefined ? { foregroundScopeIds: identity.foregroundScopeIds } : undefined,\n );\n if (!resumeStillCurrent()) return;\n if (onRemoteResumed) {\n await onRemoteResumed({\n phase,\n state,\n lease: resumeLease ?? lease,\n identity,\n });\n if (!resumeStillCurrent()) return;\n }\n },\n };\n };\n\n return {\n isUnavailableError,\n onAuthorized: (state, lease) => resolveRemoteAccess('authorize', state, lease),\n onUnavailable: async (_state, _error, lease) => {\n if (!lease.isCurrent()) return false;\n const manifest = await offline.activateOfflineSession(currentAuthSubject(), lease);\n if (!lease.isCurrent()) return false;\n return manifest !== null;\n },\n remoteRecovery: {\n retryDelayMs,\n availability,\n reauthenticate: (lease) => resolveRemoteAccess('recover', undefined, lease),\n },\n };\n}\n\nfunction assertOfflineRemoteIdentity(identity: OfflineRemoteIdentity): void {\n canonicalOfflinePrincipalId(identity.userId);\n if (!Array.isArray(identity.scopeIds) || identity.scopeIds.some((scopeId) => typeof scopeId !== 'string' || scopeId.length === 0)) {\n throw new Error('Offline remote identity scopeIds must contain only non-empty strings.');\n }\n if (typeof identity.authSubject !== 'string' || identity.authSubject.length === 0) {\n throw new Error('Offline remote identity authSubject must be a non-empty string.');\n }\n if (identity.foregroundScopeIds !== undefined) {\n if (\n !Array.isArray(identity.foregroundScopeIds) ||\n identity.foregroundScopeIds.some((scopeId) => typeof scopeId !== 'string' || scopeId.length === 0)\n ) {\n throw new Error('Offline remote identity foregroundScopeIds must contain only non-empty strings.');\n }\n const scopeIds = new Set(identity.scopeIds);\n for (const scopeId of identity.foregroundScopeIds) {\n if (!scopeIds.has(scopeId)) {\n throw new Error(`Offline remote identity foregroundScopeIds must be a subset of scopeIds: \"${scopeId}\".`);\n }\n }\n }\n}\n","export const COMMUNITY_SQLITE_ENCRYPTED = true;\nexport const COMMUNITY_SQLITE_MODE = 'secret';\nexport const COMMUNITY_SQLITE_VERSION = 1;\nexport const COMMUNITY_SQLITE_READONLY = false;\n","import { Capacitor } from '@capacitor/core';\nimport {\n COMMUNITY_SQLITE_ENCRYPTED,\n COMMUNITY_SQLITE_MODE,\n COMMUNITY_SQLITE_READONLY,\n COMMUNITY_SQLITE_VERSION,\n} from './offline-community-sqlite-config';\n\n/** Durable marker store used to request a cold-start local reset. */\nexport interface OfflineLocalResetMarkerStore {\n get(options: { key: string }): Promise<{ value: string | null }>;\n set(options: { key: string; value: string }): Promise<void>;\n remove(options: { key: string }): Promise<void>;\n}\n\n/** Minimal page reload surface used after a reset request is persisted. */\nexport interface OfflineLocalResetReloadTarget {\n reload(): void;\n}\n\n/** Native SQLite connection lifecycle required to delete Kit's encrypted database safely. */\nexport interface OfflineLocalResetSqliteConnection {\n checkConnectionsConsistency(): Promise<{ result?: boolean }>;\n isDatabase(database: string): Promise<{ result?: boolean }>;\n createConnection(\n database: string,\n encrypted: boolean,\n mode: string,\n version: number,\n readonly: boolean,\n ): Promise<{ delete(): Promise<void> }>;\n closeConnection(database: string, readonly: boolean): Promise<void>;\n}\n\n/** Options for {@link requestOfflineLocalReset}. */\nexport interface RequestOfflineLocalResetOptions {\n markerStore: OfflineLocalResetMarkerStore;\n markerKey: string;\n reloadTarget?: OfflineLocalResetReloadTarget;\n}\n\n/** Options for {@link recoverOfflineLocalReset}. */\nexport interface RecoverOfflineLocalResetOptions {\n markerStore: OfflineLocalResetMarkerStore;\n markerKey: string;\n sqliteConnection: OfflineLocalResetSqliteConnection;\n /**\n * Kit database followed only by product databases using Kit's same encrypted\n * secret-mode, connection-version-1, read/write lifecycle.\n * Delete databases with other connection settings in {@link additionalCleanup}.\n */\n kitCompatibleDatabaseNames: readonly [string, ...string[]];\n nativePlatform?: boolean;\n /** Product-owned cleanup, such as a media database or files, run before the marker is removed. */\n additionalCleanup?: () => Promise<void>;\n}\n\nconst OFFLINE_LOCAL_RESET_REQUESTED = 'requested';\n\n/** Persists an explicit destructive reset request, then reloads into a cold bootstrap. */\nexport async function requestOfflineLocalReset(options: RequestOfflineLocalResetOptions): Promise<void> {\n await options.markerStore.set({ key: options.markerKey, value: OFFLINE_LOCAL_RESET_REQUESTED });\n const reloadTarget = options.reloadTarget ?? globalThis.location;\n reloadTarget.reload();\n}\n\n/**\n * Recovers an explicit reset request before Angular and Kit open native SQLite.\n *\n * The marker is removed only after the Kit database and every product cleanup succeed.\n * Kit never invokes this helper automatically in response to a storage failure.\n */\nexport async function recoverOfflineLocalReset(options: RecoverOfflineLocalResetOptions): Promise<boolean> {\n if (!(options.nativePlatform ?? Capacitor.isNativePlatform())) return false;\n const marker = await options.markerStore.get({ key: options.markerKey });\n if (marker.value !== OFFLINE_LOCAL_RESET_REQUESTED) return false;\n\n await options.sqliteConnection.checkConnectionsConsistency();\n for (const databaseName of new Set(options.kitCompatibleDatabaseNames)) {\n const exists = await options.sqliteConnection.isDatabase(databaseName);\n if (exists.result) {\n const connection = await options.sqliteConnection.createConnection(\n databaseName,\n COMMUNITY_SQLITE_ENCRYPTED,\n COMMUNITY_SQLITE_MODE,\n COMMUNITY_SQLITE_VERSION,\n COMMUNITY_SQLITE_READONLY,\n );\n await deleteAndCloseOfflineDatabase(options.sqliteConnection, databaseName, connection);\n }\n }\n await options.additionalCleanup?.();\n await options.markerStore.remove({ key: options.markerKey });\n return true;\n}\n\ntype OfflineResetOperationResult = { ok: true } | { ok: false; error: unknown };\n\nasync function settleOfflineResetOperation(operation: () => Promise<void>): Promise<OfflineResetOperationResult> {\n return new Promise<void>((resolve) => resolve(operation())).then(\n () => ({ ok: true }),\n (error: unknown) => ({ ok: false, error }),\n );\n}\n\nasync function deleteAndCloseOfflineDatabase(\n sqliteConnection: OfflineLocalResetSqliteConnection,\n databaseName: string,\n connection: { delete(): Promise<void> },\n): Promise<void> {\n const deletion = await settleOfflineResetOperation(() => connection.delete());\n const closing = await settleOfflineResetOperation(() => sqliteConnection.closeConnection(databaseName, COMMUNITY_SQLITE_READONLY));\n if (!deletion.ok && !closing.ok) {\n throw new AggregateError([deletion.error, closing.error], `Offline database ${databaseName} delete and close both failed.`);\n }\n if (!deletion.ok) throw deletion.error;\n if (!closing.ok) throw closing.error;\n}\n","import { HttpErrorResponse } from '@angular/common/http';\n\n/** Identity policy for a successful offline mutation response. */\nexport type OfflineMutationEnvelopeIdPolicy = 'required' | 'optional' | 'forbidden';\n\n/** Values policy for a successful offline mutation response. */\nexport type OfflineMutationEnvelopeValuesPolicy = 'object' | 'tombstone' | 'object-or-tombstone' | 'optional-object-or-tombstone';\n\n/** Runtime validation policy for a successful offline mutation response. */\nexport interface OfflineMutationEnvelopeOptions {\n readonly id: OfflineMutationEnvelopeIdPolicy;\n readonly values: OfflineMutationEnvelopeValuesPolicy;\n readonly label?: string;\n readonly url?: string;\n}\n\n/** Canonical successful mutation response consumed by offline command adapters. */\nexport interface OfflineMutationEnvelope<T extends Record<string, unknown>> {\n readonly id: number | null;\n readonly revision: number;\n readonly values: T | null | undefined;\n}\n\n/**\n * A successful HTTP response that violates the offline mutation protocol.\n *\n * Status 502 deliberately keeps the response in the retryable server-failure class.\n */\nexport class OfflineMutationProtocolError extends HttpErrorResponse {\n constructor(message: string, url?: string) {\n super({\n error: { code: 'OFFLINE_MUTATION_PROTOCOL_ERROR', message },\n status: 502,\n statusText: 'Bad Gateway',\n url,\n });\n }\n}\n\nconst hasOwn = (value: Record<string, unknown>, key: string): boolean => Object.prototype.hasOwnProperty.call(value, key);\n\nconst isPositiveSafeInteger = (value: unknown): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/** Strictly parses the wire envelope returned by an offline mutation endpoint. */\nexport function parseOfflineMutationEnvelope<T extends Record<string, unknown> = Record<string, unknown>>(\n input: unknown,\n options: OfflineMutationEnvelopeOptions,\n): OfflineMutationEnvelope<T> {\n const label = options.label ?? 'Offline mutation response';\n const invalid = (detail: string): never => {\n throw new OfflineMutationProtocolError(`${label} ${detail}`, options.url);\n };\n\n const envelope = isRecord(input) ? input : invalid('must be an object.');\n\n let id: number | null = null;\n switch (options.id) {\n case 'required': {\n const rawId = envelope['id'];\n id = hasOwn(envelope, 'id') && isPositiveSafeInteger(rawId) ? rawId : invalid('id must be a positive safe integer.');\n break;\n }\n case 'optional': {\n if (hasOwn(envelope, 'id')) {\n const rawId = envelope['id'];\n id = isPositiveSafeInteger(rawId) ? rawId : invalid('id must be a positive safe integer when present.');\n }\n break;\n }\n case 'forbidden':\n if (['id', 'serverId', 'remoteId'].some((key) => hasOwn(envelope, key))) {\n invalid('must not contain id, serverId, or remoteId.');\n }\n break;\n }\n\n const rawRevision = envelope['revision'];\n const revision =\n hasOwn(envelope, 'revision') && isPositiveSafeInteger(rawRevision) ? rawRevision : invalid('revision must be a positive safe integer.');\n\n const values = envelope['values'];\n switch (options.values) {\n case 'object':\n if (!isRecord(values)) {\n invalid('values must be an object.');\n }\n break;\n case 'tombstone':\n if (values !== null) {\n invalid('values must be null.');\n }\n break;\n case 'object-or-tombstone':\n if (values !== null && !isRecord(values)) {\n invalid('values must be an object or null.');\n }\n break;\n case 'optional-object-or-tombstone':\n if (values !== undefined && values !== null && !isRecord(values)) {\n invalid('values must be an object, null, or undefined.');\n }\n break;\n }\n\n return { id, revision, values: values as T | null | undefined };\n}\n","import type { Provider, Type } from '@angular/core';\nimport { inject, Injectable, InjectionToken } from '@angular/core';\nimport type { HttpRequest, HttpResponse } from '@angular/common/http';\nimport { HttpContextToken } from '@angular/common/http';\n\n/** outbox再送時にoffline interceptorだけを迂回する。認証・retryは維持する。 */\nexport const OFFLINE_BYPASS = new HttpContextToken<boolean>(() => false);\n/** Header attached to synthetic local or optimistic responses. */\nexport const OFFLINE_RESPONSE_HEADER = 'X-Offline-Response';\n/** Header marking a local response as a complete collection snapshot. */\nexport const OFFLINE_RESPONSE_COMPLETE_HEADER = 'X-Offline-Response-Complete';\n/** Origin of a synthetic offline response. */\nexport type OfflineResponseSource = 'local' | 'optimistic';\n\n/** Source passed to a read policy's shared response projector. */\nexport type OfflineReadResponseSource = 'remote' | 'local';\n\n/** Value emitted by a local-first read together with its settlement metadata. */\nexport interface OfflineReadEmission<T> {\n readonly value: T;\n readonly source: OfflineReadResponseSource;\n readonly complete?: boolean;\n}\n\n/** Reads the source attached by the offline interceptor. */\nexport function offlineReadSource(response: HttpResponse<unknown>): OfflineReadResponseSource {\n return response.headers.get(OFFLINE_RESPONSE_HEADER) === 'local' ? 'local' : 'remote';\n}\n\n/** Converts an HTTP response into the shared local-first read emission contract. */\nexport function offlineReadEmission<T>(response: HttpResponse<unknown>, value: T): OfflineReadEmission<T> {\n const source = offlineReadSource(response);\n return {\n value,\n source,\n complete: source === 'remote' || response.headers.get(OFFLINE_RESPONSE_COMPLETE_HEADER) === 'true',\n };\n}\n\n/** Prevents an incomplete empty local collection from clearing usable UI state. */\nexport function shouldCommitOfflineCollection<T>(emission: OfflineReadEmission<readonly T[]>): boolean {\n return emission.source === 'remote' || emission.complete || emission.value.length > 0;\n}\n\n/** Controls GET emission order between local replica and remote transport. */\nexport type OfflineReadStrategy = 'network-first' | 'local-first';\n\n/** Product read policy backed by a local replica fallback for transport failures. */\nexport interface OfflineReadRequestPlan {\n kind: 'read';\n /**\n * Controls whether the interceptor hits the network first or emits a local\n * replica immediately and revalidates in the background. Defaults to\n * `network-first` when omitted so existing policies stay compatible.\n *\n * @remarks\n * `local-first` starts transport and `readLocal()` concurrently, emits\n * projected local first on hit, then drains the buffered remote response.\n * Callers must keep the HTTP observable subscribed through revalidation;\n * `firstValueFrom` and `take(1)` cancel in-flight transport.\n */\n readStrategy?: OfflineReadStrategy;\n /**\n * Persists and projects a remote response, or projects a local fallback.\n *\n * @remarks\n * Products may return a replacement response assembled from the local\n * replica. The source makes persistence remote-only while both paths share\n * one product-owned composer.\n */\n projectResponse?(response: HttpResponse<unknown>, source: OfflineReadResponseSource): Promise<HttpResponse<unknown>>;\n /** Reads the same request from the local replica. */\n readLocal(): Promise<HttpResponse<unknown> | null>;\n}\n\n/** Resolved offline handling strategy for an HTTP request. */\nexport type OfflineRequestPlan = OfflineReadRequestPlan;\n\n/** URL・DTO・replica key・feature flagは製品Policyだけが知る。 */\nexport interface OfflineRequestPolicy {\n resolve(request: HttpRequest<unknown>): OfflineRequestPlan | null;\n}\n\n/** A local-first mutation prepared before any HTTP transport is started. */\nexport interface OfflineMutationRequestPlan {\n kind: 'mutation';\n /**\n * Atomically updates the replica and appends its durable Outbox command,\n * then returns the optimistic response exposed to the original caller.\n */\n prepare(): Promise<HttpResponse<unknown>>;\n}\n\n/** Product policy that maps one write request to a local-first mutation. */\nexport interface OfflineMutationRequestPolicy {\n resolve(request: HttpRequest<unknown>): OfflineMutationRequestPlan | null;\n}\n\n/** Multi-provider token containing product request policies. */\nexport const OFFLINE_REQUEST_POLICIES = new InjectionToken<readonly OfflineRequestPolicy[]>('OFFLINE_REQUEST_POLICIES', {\n factory: () => [],\n});\n\n/** Multi-provider token containing product mutation policies. */\nexport const OFFLINE_MUTATION_REQUEST_POLICIES = new InjectionToken<readonly OfflineMutationRequestPolicy[]>(\n 'OFFLINE_MUTATION_REQUEST_POLICIES',\n { factory: () => [] },\n);\n\n/** Registers one product request policy with the offline interceptor. */\nexport function provideOfflineRequestPolicy(policy: Type<OfflineRequestPolicy>): Provider[] {\n return [policy, { provide: OFFLINE_REQUEST_POLICIES, useExisting: policy, multi: true }];\n}\n\n/** Registers one product mutation policy with the offline interceptor. */\nexport function provideOfflineMutationRequestPolicy(policy: Type<OfflineMutationRequestPolicy>): Provider[] {\n return [policy, { provide: OFFLINE_MUTATION_REQUEST_POLICIES, useExisting: policy, multi: true }];\n}\n\n/** Resolves the first product policy matching an HTTP request. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineRequestPolicyRegistry {\n readonly #policies = inject(OFFLINE_REQUEST_POLICIES);\n\n resolve(request: HttpRequest<unknown>): OfflineRequestPlan | null {\n for (const policy of this.#policies) {\n const plan = policy.resolve(request);\n if (plan) return plan;\n }\n return null;\n }\n}\n\n/** Raised when more than one mutation policy claims the same request. */\nexport class OfflineMutationPolicyConflictError extends Error {\n constructor(request: HttpRequest<unknown>, matchCount: number) {\n super(`${matchCount} offline mutation policies matched ${request.method} ${request.urlWithParams}`);\n this.name = 'OfflineMutationPolicyConflictError';\n }\n}\n\n/** Resolves the only product mutation policy matching a write request. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineMutationRequestPolicyRegistry {\n readonly #policies = inject(OFFLINE_MUTATION_REQUEST_POLICIES);\n\n resolve(request: HttpRequest<unknown>): OfflineMutationRequestPlan | null {\n let matched: OfflineMutationRequestPlan | null = null;\n let matchCount = 0;\n for (const policy of this.#policies) {\n const plan = policy.resolve(request);\n if (!plan) continue;\n matched = plan;\n matchCount += 1;\n }\n if (matchCount > 1) throw new OfflineMutationPolicyConflictError(request, matchCount);\n return matched;\n }\n}\n","import { inject, Injectable, InjectionToken } from '@angular/core';\nimport {\n canonicalOfflineReplicaIdentity,\n canonicalOfflinePrincipalId,\n commandIdentityFromReplicaIdentity,\n offlineGeneratedReplicaIdentity,\n offlineNaturalReplicaIdentity,\n parseOfflineCommandIdentity,\n parseOfflinePrincipalId,\n replicaAddressFromIdentity,\n serializeOfflineCommandIdentity,\n} from './offline-identity';\nimport { OFFLINE_KIT_OPTIONS } from './offline-kit-options';\nimport {\n assertOfflineReplicaGeneratedRemoteId,\n assertOfflineReplicaNaturalKeyBaseline,\n canonicalOfflineRemoteIdentity,\n decodeOfflineReplicaValues,\n encodeOfflineReplicaValues,\n normalizeOfflineNaturalKey,\n offlineNaturalKeyFromValues,\n projectOfflineReplicaValues,\n type OfflineGeneratedRemoteId,\n type OfflineReplicaEntitySchema,\n type OfflineReplicaRemoteIdentity,\n type OfflineReplicaSchemaBundle,\n sha256OfflineReplicaSchema,\n} from './offline-replica-schema';\nimport {\n OFFLINE_SCHEMA_VERSION,\n canonicalOfflineReplicaRowKey,\n type OfflineCommand,\n type OfflineCommandIdentity,\n type OfflinePrincipalId,\n type OfflinePullAttention,\n type OfflinePullAttentionReason,\n type OfflineReplicaAddress,\n type OfflineReplicaCursor,\n type OfflineReplicaIdentity,\n type OfflineReplicaRow,\n type OfflineReplicaRowKey,\n type OfflineReplicaRemoteIdRelease,\n type OfflineRepository,\n type OfflineRepositoryReader,\n type OfflineReplicaTransaction,\n type OfflineScope,\n} from './offline-repository';\nimport { OFFLINE_REPOSITORY_ATOMIC_MUTATION } from './offline-repository-concurrency';\nimport { OfflineStorageUnavailableError } from './offline-storage';\nimport {\n COMMUNITY_SQLITE_ENCRYPTED,\n COMMUNITY_SQLITE_MODE,\n COMMUNITY_SQLITE_READONLY,\n COMMUNITY_SQLITE_VERSION,\n} from './offline-community-sqlite-config';\n\n/** Minimal native SQLite driver surface required by the offline repository. */\nexport interface CommunitySqliteDriver {\n open(options: { databaseName: string; createEncryptionKey?: () => Promise<string> }): Promise<{ databaseId: string }>;\n execute(options: { databaseId: string; statement: string; values?: SQLiteValue[] }): Promise<unknown>;\n query(options: { databaseId: string; statement: string; values?: SQLiteValue[] }): Promise<{\n columns?: string[];\n rows?: unknown[];\n }>;\n beginTransaction(options: { databaseId: string }): Promise<void>;\n commitTransaction(options: { databaseId: string }): Promise<void>;\n rollbackTransaction(options: { databaseId: string }): Promise<void>;\n}\n\n/** Open community SQLite database surface used by the standard driver. */\nexport interface CommunitySqliteDatabase {\n open(): Promise<void>;\n run(statement: string, values?: unknown[], transaction?: boolean): Promise<unknown>;\n query(statement: string, values?: unknown[]): Promise<{ values?: unknown[] }>;\n beginTransaction(): Promise<unknown>;\n commitTransaction(): Promise<unknown>;\n rollbackTransaction(): Promise<unknown>;\n}\n\n/** Community SQLite connection surface used to provision encrypted databases. */\nexport interface CommunitySqliteConnection {\n isSecretStored(): Promise<{ result?: boolean }>;\n setEncryptionSecret(passphrase: string): Promise<void>;\n createConnection(\n database: string,\n encrypted: boolean,\n mode: string,\n version: number,\n readonly: boolean,\n ): Promise<CommunitySqliteDatabase>;\n}\n\n/** DI token for the native community SQLite driver. */\nexport const COMMUNITY_SQLITE = new InjectionToken<CommunitySqliteDriver | null>('COMMUNITY_SQLITE', {\n factory: () => null,\n});\n\n/**\n * Create a cryptographically random 256-bit key for a first-install offline SQLite database.\n *\n * The returned lower-case hexadecimal value is suitable for\n * `OfflineKitOptions.createEncryptionKey` and contains no device or user identifiers.\n */\nexport async function createRandomOfflineEncryptionKey(): Promise<string> {\n const bytes = crypto.getRandomValues(new Uint8Array(32));\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\nconst settledSqliteOperation = async (): Promise<void> => undefined;\n\n/** Create the standard encrypted `@capacitor-community/sqlite` driver. */\nexport function createCommunitySqliteDriver(connection: CommunitySqliteConnection): CommunitySqliteDriver {\n const databases = new Map<string, CommunitySqliteDatabase>();\n const database = (databaseId: string): CommunitySqliteDatabase => {\n const value = databases.get(databaseId);\n if (!value) throw new Error(`Offline SQLite database \"${databaseId}\" is not open`);\n return value;\n };\n return {\n async open({ databaseName, createEncryptionKey }) {\n const stored = await connection.isSecretStored();\n if (!stored.result) {\n const encryptionKey = await createEncryptionKey?.();\n if (!encryptionKey) throw new Error('Native offline storage requires a non-empty encryption key on first open');\n await connection.setEncryptionSecret(encryptionKey);\n }\n const value = await connection.createConnection(\n databaseName,\n COMMUNITY_SQLITE_ENCRYPTED,\n COMMUNITY_SQLITE_MODE,\n COMMUNITY_SQLITE_VERSION,\n COMMUNITY_SQLITE_READONLY,\n );\n await value.open();\n databases.set(databaseName, value);\n return { databaseId: databaseName };\n },\n async execute({ databaseId, statement, values = [] }) {\n await database(databaseId).run(statement, values, false);\n },\n async query({ databaseId, statement, values = [] }) {\n const result = await database(databaseId).query(statement, values);\n return { rows: result.values ?? [] };\n },\n async beginTransaction({ databaseId }) {\n await database(databaseId).beginTransaction();\n },\n async commitTransaction({ databaseId }) {\n await database(databaseId).commitTransaction();\n },\n async rollbackTransaction({ databaseId }) {\n await database(databaseId).rollbackTransaction();\n },\n };\n}\n\ntype SQLiteValue = string | number | null;\ntype SQLiteRow = Record<string, unknown>;\n\nconst SCHEMA = [\n `CREATE TABLE IF NOT EXISTS offline_metadata (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n schema_version INTEGER NOT NULL,\n last_user_id TEXT\n)`,\n `CREATE TABLE IF NOT EXISTS offline_session_manifests (\n user_id TEXT PRIMARY KEY,\n value_json TEXT NOT NULL\n)`,\n `CREATE TABLE IF NOT EXISTS offline_sync_commands (\n command_id TEXT PRIMARY KEY,\n user_id TEXT NOT NULL,\n scope_id TEXT NOT NULL,\n aggregate_type TEXT NOT NULL,\n source_key TEXT NOT NULL,\n identity_json TEXT NOT NULL,\n operation TEXT NOT NULL,\n payload_json TEXT NOT NULL,\n local_only_footprint_json TEXT,\n replica_mutation TEXT NOT NULL DEFAULT 'upsert',\n payload_hash TEXT NOT NULL,\n base_revision_json TEXT,\n state TEXT NOT NULL,\n attempts INTEGER NOT NULL,\n retry_at INTEGER,\n created_at INTEGER NOT NULL,\n last_error_code TEXT,\n server_commit_unknown INTEGER NOT NULL DEFAULT 0,\n reconciliation_identity_json TEXT\n)`,\n `CREATE INDEX IF NOT EXISTS offline_sync_commands_scope_created\n ON offline_sync_commands (user_id, scope_id, created_at)`,\n `CREATE TABLE IF NOT EXISTS offline_replica_schema_metadata (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n version INTEGER NOT NULL,\n schema_hash TEXT NOT NULL CHECK (length(schema_hash) = 64)\n)`,\n `CREATE TABLE IF NOT EXISTS offline_replica_cursors (\n user_id TEXT NOT NULL,\n scope_id TEXT NOT NULL,\n cursor TEXT NOT NULL,\n PRIMARY KEY (user_id, scope_id)\n )`,\n `CREATE TABLE IF NOT EXISTS offline_reconciliation_scopes (\n user_id TEXT NOT NULL,\n scope_id TEXT NOT NULL,\n PRIMARY KEY (user_id, scope_id)\n)`,\n `CREATE TABLE IF NOT EXISTS offline_pull_attentions (\n user_id TEXT NOT NULL,\n scope_id TEXT NOT NULL,\n reason TEXT NOT NULL,\n status INTEGER,\n PRIMARY KEY (user_id, scope_id)\n)`,\n];\n\n/** Native iOS/Android repository backed by encrypted `@capacitor-community/sqlite`. */\n@Injectable({ providedIn: 'root' })\nexport class SqliteOfflineRepository implements OfflineRepository {\n readonly #sqlite = inject(COMMUNITY_SQLITE);\n readonly #options = inject(OFFLINE_KIT_OPTIONS);\n #databaseId: string | null = null;\n #initialization: Promise<void> | null = null;\n #writes: Promise<void> = settledSqliteOperation();\n #activeReaders = 0;\n #readersIdle: Promise<void> = settledSqliteOperation();\n #resolveReadersIdle: (() => void) | null = null;\n #atomicMutationRevision: number | null = null;\n #atomicMutationCommitted = false;\n #atomicOperations: Promise<void> = settledSqliteOperation();\n #readSnapshotActive = false;\n #atomicIdle: Promise<void> = settledSqliteOperation();\n #resolveAtomicIdle: (() => void) | null = null;\n\n initialize(): Promise<void> {\n this.#initialization ??= this.#open();\n return this.#initialization;\n }\n\n async getLastUserId(): Promise<OfflinePrincipalId | null> {\n return this.#withCommittedRead(() => this.#readLastUserId());\n }\n\n async setLastUserId(userId: OfflinePrincipalId): Promise<void> {\n await this.#write(\n `INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, ?)\n ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version, last_user_id = excluded.last_user_id`,\n [OFFLINE_SCHEMA_VERSION, canonicalOfflinePrincipalId(userId)],\n );\n }\n\n async getSessionManifest<T>(userId: OfflinePrincipalId): Promise<T | null> {\n return this.#withCommittedRead(() => this.#readSessionManifest<T>(userId));\n }\n\n async putSessionManifest<T>(userId: OfflinePrincipalId, value: T): Promise<void> {\n await this.#write(\n `INSERT INTO offline_session_manifests (user_id, value_json) VALUES (?, ?)\n ON CONFLICT(user_id) DO UPDATE SET value_json = excluded.value_json`,\n [canonicalOfflinePrincipalId(userId), JSON.stringify(value)],\n );\n }\n\n async getReplicaRow<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n return this.#withCommittedRead(async () => {\n const row = await this.#queryReplicaRow(scope, sourceKey, identity, false);\n return row as OfflineReplicaRow<TValues> | null;\n });\n }\n\n async getReplicaRowIncludingPendingDelete<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n return this.#withCommittedRead(async () => {\n const row = await this.#queryReplicaRow(scope, sourceKey, identity, true);\n return row as OfflineReplicaRow<TValues> | null;\n });\n }\n\n async getReplicaRows<TValues = unknown>(scope: OfflineScope, sourceKey: string): Promise<OfflineReplicaRow<TValues>[]> {\n return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey));\n }\n\n async getReplicaRowByRemoteId<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n remoteId: OfflineGeneratedRemoteId,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated') return null;\n return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });\n }\n\n async getReplicaRowByRemoteIdentity<TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaRemoteIdentity,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n return this.#withCommittedRead(() => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity));\n }\n\n async getReplicaCursor(scope: OfflineScope): Promise<OfflineReplicaCursor | null> {\n return this.#withCommittedRead(() => this.#readReplicaCursor(scope));\n }\n\n async getPullAttentions(userId: OfflinePrincipalId): Promise<OfflinePullAttention[]> {\n return this.#withCommittedRead(() => this.#readPullAttentions(userId));\n }\n\n async getCommands(scope: OfflineScope): Promise<OfflineCommand[]> {\n return this.#withCommittedRead(() => this.#readCommands(scope));\n }\n\n async getCommandsForUser(userId: OfflinePrincipalId): Promise<OfflineCommand[]> {\n return this.#withCommittedRead(() => this.#readCommandsForUser(userId));\n }\n\n async runReadSnapshot<T>(read: (reader: OfflineRepositoryReader) => Promise<T>): Promise<T> {\n if (this.#atomicMutationRevision !== null) {\n throw new Error('Use the repository passed to an atomic mutation for snapshot reads.');\n }\n return this.#transaction(async () => {\n this.#readSnapshotActive = true;\n const executeRead = async (): Promise<T> => read(this.#reader());\n return executeRead().finally(() => (this.#readSnapshotActive = false));\n });\n }\n\n async [OFFLINE_REPOSITORY_ATOMIC_MUTATION]<T>(operation: (repository: OfflineRepository) => Promise<T>): Promise<T> {\n await this.initialize();\n await this.#writes;\n if (this.#atomicMutationRevision !== null) {\n throw new Error('Nested offline replica atomic mutations are not supported.');\n }\n this.#beginReaders();\n const executeAtomicMutation = async (): Promise<T> => {\n const databaseId = await this.#databaseConnection();\n this.#atomicOperations = settledSqliteOperation();\n this.#atomicMutationCommitted = false;\n this.#atomicIdle = new Promise<void>((resolve) => {\n this.#resolveAtomicIdle = resolve;\n });\n this.#atomicMutationRevision = await this.#nativeTransaction(databaseId, () => this.#dataVersion(databaseId));\n const result = await operation(this.#atomicRepository());\n await this.#atomicOperations;\n if (!this.#atomicMutationCommitted) {\n await this.#queueAtomicOperation(() => this.#atomicTransaction(databaseId, async () => undefined, false));\n }\n return result;\n };\n return executeAtomicMutation().finally(() => {\n this.#atomicMutationRevision = null;\n this.#endReaders();\n this.#resolveAtomicIdle?.();\n this.#resolveAtomicIdle = null;\n this.#atomicIdle = settledSqliteOperation();\n });\n }\n\n async putCommand(command: OfflineCommand): Promise<void> {\n await this.#queueWrite((databaseId) => this.#putCommand(databaseId, command));\n }\n\n replaceCommand(command: OfflineCommand): Promise<void> {\n return this.putCommand(command);\n }\n\n async removeCommand(commandId: string): Promise<void> {\n await this.#write('DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId]);\n }\n\n async putPullAttention(attention: OfflinePullAttention): Promise<void> {\n await this.#write(\n `INSERT INTO offline_pull_attentions (user_id, scope_id, reason, status) VALUES (?, ?, ?, ?)\n ON CONFLICT(user_id, scope_id) DO UPDATE SET reason = excluded.reason, status = excluded.status`,\n [\n canonicalOfflinePrincipalId(attention.userId),\n attention.scopeId,\n attention.reason,\n attention.status === undefined ? null : attention.status,\n ],\n );\n }\n\n async removePullAttention(scope: OfflineScope): Promise<void> {\n await this.#write('DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', [\n canonicalOfflinePrincipalId(scope.userId),\n scope.scopeId,\n ]);\n }\n\n async clearUser(userId: OfflinePrincipalId): Promise<void> {\n await this.#transaction((database) => this.#clearUser(database, userId));\n }\n\n async #clearUser(database: string, userId: OfflinePrincipalId): Promise<void> {\n const principal = canonicalOfflinePrincipalId(userId);\n await this.#execute(database, 'DELETE FROM offline_session_manifests WHERE user_id = ?', [principal]);\n await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ?', [principal]);\n await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ?', [principal]);\n await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ?', [principal]);\n await this.#execute(database, 'DELETE FROM offline_pull_attentions WHERE user_id = ?', [principal]);\n for (const entity of this.#options.replicaSchema.entities) {\n await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [principal]);\n }\n await this.#execute(database, 'UPDATE offline_metadata SET last_user_id = NULL WHERE id = 1 AND last_user_id = ?', [principal]);\n }\n\n async clearScope(scope: OfflineScope): Promise<void> {\n await this.#transaction((database) => this.#clearScope(database, scope));\n }\n\n async #clearScope(database: string, scope: OfflineScope): Promise<void> {\n const values = [canonicalOfflinePrincipalId(scope.userId), scope.scopeId];\n const partitionSourceKeys = this.#options.replicaSchema.entities\n .filter((entity) => entity.scope === 'partition')\n .map((entity) => entity.sourceKey);\n if (partitionSourceKeys.length > 0) {\n await this.#execute(\n database,\n `DELETE FROM offline_sync_commands\n WHERE user_id = ? AND scope_id = ? AND source_key IN (${partitionSourceKeys.map(() => '?').join(', ')})`,\n [...values, ...partitionSourceKeys],\n );\n }\n await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', values);\n await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ? AND scope_id = ?', values);\n await this.#execute(database, 'DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', values);\n for (const entity of this.#options.replicaSchema.entities) {\n if (entity.scope !== 'partition') continue;\n await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ? AND _offline_scope_id = ?`, values);\n }\n }\n\n async transactReplica(transaction: OfflineReplicaTransaction): Promise<void> {\n for (const row of transaction.putRows ?? []) this.#validateReplicaRow(row);\n const apply = (databaseId: string): Promise<void> => this.#applyReplicaTransaction(databaseId, transaction);\n await this.#transaction(apply);\n }\n\n async #applyReplicaTransaction(databaseId: string, transaction: OfflineReplicaTransaction): Promise<void> {\n const releases = new Map<string, OfflineReplicaRemoteIdRelease>();\n for (const release of transaction.releaseRemoteIds ?? []) {\n this.#assertValidReleaseRemoteId(release.remoteId);\n const key = this.#replicaRowKey(release);\n if (releases.has(key)) {\n throw new Error(\n `Offline replica remoteId release is duplicated for ${release.sourceKey}/${canonicalOfflineReplicaIdentity(release.identity)}.`,\n );\n }\n releases.set(key, release);\n }\n const consumedReleases = new Set<string>();\n for (const row of transaction.putRows ?? []) {\n const key = this.#replicaRowKey(row);\n const release = releases.get(key);\n await this.#putReplicaRow(databaseId, row, release);\n if (release) consumedReleases.add(key);\n }\n if (consumedReleases.size !== releases.size) {\n throw new Error('Offline replica remoteId release must match an existing row in putRows.');\n }\n for (const row of transaction.removeRows ?? []) await this.#removeReplicaRow(databaseId, row);\n for (const command of transaction.putCommands ?? []) await this.#putCommand(databaseId, command);\n for (const commandId of transaction.removeCommandIds ?? []) {\n await this.#execute(databaseId, 'DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId]);\n }\n for (const cursor of transaction.putCursors ?? []) await this.#putReplicaCursor(databaseId, cursor);\n for (const attention of transaction.putPullAttentions ?? []) {\n await this.#execute(\n databaseId,\n `INSERT INTO offline_pull_attentions (user_id, scope_id, reason, status) VALUES (?, ?, ?, ?)\n ON CONFLICT(user_id, scope_id) DO UPDATE SET reason = excluded.reason, status = excluded.status`,\n [\n canonicalOfflinePrincipalId(attention.userId),\n attention.scopeId,\n attention.reason,\n attention.status === undefined ? null : attention.status,\n ],\n );\n }\n for (const scope of transaction.removePullAttentions ?? []) {\n await this.#execute(databaseId, 'DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', [\n canonicalOfflinePrincipalId(scope.userId),\n scope.scopeId,\n ]);\n }\n }\n\n async #open(): Promise<void> {\n await this.#openDatabase().catch((error: unknown) => {\n throw this.#mapInitializationError(error);\n });\n }\n\n async #openDatabase(): Promise<void> {\n if (!this.#sqlite) {\n throw new OfflineStorageUnavailableError('storage_unavailable', 'Native offline storage requires a community SQLite connection');\n }\n const { databaseId } = await this.#sqlite.open({\n databaseName: this.#options.databaseName,\n createEncryptionKey: this.#wrapCreateEncryptionKey(this.#options.createEncryptionKey),\n });\n this.#databaseId = databaseId;\n for (const statement of SCHEMA) await this.#execute(databaseId, statement);\n const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');\n if (metadata.length === 0) {\n await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [\n OFFLINE_SCHEMA_VERSION,\n ]);\n } else {\n const storedVersion = this.#number(metadata[0]!['schema_version']);\n if (storedVersion !== OFFLINE_SCHEMA_VERSION) {\n throw new OfflineStorageUnavailableError(\n 'core_schema_incompatible',\n `Unsupported offline storage schema version ${storedVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +\n 'A lossless core schema migration is required before this database can be opened.',\n );\n }\n }\n await this.#initializeReplicaSchema(databaseId);\n }\n\n async #initializeReplicaSchema(databaseId: string): Promise<void> {\n const bundle = this.#options.replicaSchema;\n const targetVersion = bundle.version;\n const targetHash = await sha256OfflineReplicaSchema(bundle);\n const rows = await this.#queryDatabase(databaseId, 'SELECT version, schema_hash FROM offline_replica_schema_metadata WHERE id = 1');\n const storedVersion = rows[0] ? this.#number(rows[0]['version']) : null;\n const storedHash = rows[0] ? this.#string(rows[0]['schema_hash']) : null;\n\n if (storedVersion === null) {\n await this.#nativeTransaction(databaseId, async () => {\n await this.#executeReplicaCreateStatements(databaseId, bundle);\n await this.#upsertReplicaSchemaMetadata(databaseId, targetVersion, targetHash);\n });\n return;\n }\n\n if (storedVersion === targetVersion && storedHash === targetHash) {\n return;\n }\n\n if (storedVersion === targetVersion) {\n throw new OfflineStorageUnavailableError(\n 'replica_schema_mismatch',\n `Offline replica schema hash mismatch at version ${targetVersion}. Reinstall the application or bump replicaSchema.version after intentional schema changes.`,\n );\n }\n\n if (storedVersion > targetVersion) {\n throw new OfflineStorageUnavailableError(\n 'replica_schema_mismatch',\n `Offline replica schema version ${storedVersion} is newer than application version ${targetVersion}. Upgrade the application before opening this database.`,\n );\n }\n\n await this.#nativeTransaction(databaseId, async () => {\n for (let version = storedVersion; version < targetVersion; version++) {\n const migration = bundle.migrations.find((candidate) => candidate.fromVersion === version);\n if (!migration) {\n throw new OfflineStorageUnavailableError(\n 'migration_missing',\n `Missing offline replica schema migration from version ${version} to ${version + 1}.`,\n );\n }\n for (const statement of migration.statements) {\n await this.#execute(databaseId, statement);\n }\n }\n await this.#executeReplicaCreateStatements(databaseId, bundle);\n await this.#upsertReplicaSchemaMetadata(databaseId, targetVersion, targetHash);\n });\n }\n\n #wrapCreateEncryptionKey(createEncryptionKey: (() => Promise<string>) | undefined): (() => Promise<string>) | undefined {\n if (!createEncryptionKey) return undefined;\n return () => {\n const create = async (): Promise<string> => {\n const encryptionKey = await createEncryptionKey();\n if (!encryptionKey) {\n throw new OfflineStorageUnavailableError(\n 'encryption_key_unavailable',\n 'Native offline storage requires a non-empty encryption key on first open',\n );\n }\n return encryptionKey;\n };\n return create().catch((error: unknown) => {\n if (error instanceof OfflineStorageUnavailableError) throw error;\n throw new OfflineStorageUnavailableError(\n 'encryption_key_unavailable',\n error instanceof Error ? error.message : 'Offline encryption key is unavailable.',\n { cause: error },\n );\n });\n };\n }\n\n #mapInitializationError(error: unknown): OfflineStorageUnavailableError {\n if (error instanceof OfflineStorageUnavailableError) return error;\n const message = error instanceof Error ? error.message : 'Offline storage is unavailable.';\n if (message.includes('non-empty encryption key on first open')) {\n return new OfflineStorageUnavailableError('encryption_key_unavailable', message, { cause: error });\n }\n return new OfflineStorageUnavailableError('storage_unavailable', message || 'Offline storage is unavailable.', {\n cause: error,\n });\n }\n\n async #executeReplicaCreateStatements(databaseId: string, bundle: OfflineReplicaSchemaBundle): Promise<void> {\n for (const entity of bundle.entities) {\n for (const statement of entity.createTableSql) {\n await this.#execute(databaseId, statement);\n }\n }\n }\n\n async #upsertReplicaSchemaMetadata(databaseId: string, version: number, schemaHash: string): Promise<void> {\n await this.#execute(\n databaseId,\n `INSERT INTO offline_replica_schema_metadata (id, version, schema_hash) VALUES (1, ?, ?)\n ON CONFLICT(id) DO UPDATE SET version = excluded.version, schema_hash = excluded.schema_hash`,\n [version, schemaHash],\n );\n }\n\n async #nativeTransaction<T>(databaseId: string, run: () => Promise<T>): Promise<T> {\n await this.#sqlite!.beginTransaction({ databaseId });\n const execute = async (): Promise<T> => run();\n return execute()\n .then(async (result) => {\n await this.#sqlite!.commitTransaction({ databaseId });\n return result;\n })\n .catch(async (error: unknown) => {\n const rollback = await this.#sqlite!.rollbackTransaction({ databaseId }).then(\n () => ({ status: 'fulfilled' as const }),\n (rollbackError: unknown) => ({ status: 'rejected' as const, rollbackError }),\n );\n if (rollback.status === 'rejected') {\n throw new AggregateError([error, rollback.rollbackError], 'Offline SQLite transaction and rollback both failed.', {\n cause: error,\n });\n }\n throw error;\n });\n }\n\n async #databaseConnection(): Promise<string> {\n await this.initialize();\n if (!this.#databaseId) throw new Error('Offline SQLite database is not initialized');\n return this.#databaseId;\n }\n\n async #readLastUserId(): Promise<OfflinePrincipalId | null> {\n const rows = await this.#query('SELECT last_user_id FROM offline_metadata WHERE id = 1');\n const value = this.#stringOrNull(rows[0]?.['last_user_id']);\n return value === null ? null : parseOfflinePrincipalId(value);\n }\n\n async #readSessionManifest<T>(userId: OfflinePrincipalId): Promise<T | null> {\n const rows = await this.#query('SELECT value_json FROM offline_session_manifests WHERE user_id = ?', [\n canonicalOfflinePrincipalId(userId),\n ]);\n const row = rows[0];\n return row ? this.#parse<T>(row['value_json']) : null;\n }\n\n async #readReplicaRows<TValues>(scope: OfflineScope, sourceKey: string): Promise<OfflineReplicaRow<TValues>[]> {\n const schema = this.#resolveReplicaEntitySchema(sourceKey);\n const predicates = ['_offline_user_id = ?'];\n const values: SQLiteValue[] = [canonicalOfflinePrincipalId(scope.userId)];\n if (schema.scope === 'partition') {\n predicates.push('_offline_scope_id = ?');\n values.push(scope.scopeId);\n }\n const orderBy =\n schema.identity.kind === 'naturalKey'\n ? schema.identity.sourceKeys.map((key) => schema.fields.find((field) => field.sourceKey === key)!.sqliteColumnName!).join(', ')\n : 'local_id ASC';\n const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY ${orderBy}`, values);\n return rows\n .filter((row) => (row['_offline_visibility'] ?? 'present') !== 'pending_delete')\n .map((row) => this.#replicaRowFromSqliteRow<TValues>(schema, scope, sourceKey, row));\n }\n\n async #readReplicaRowByRemoteIdentity<TValues>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaRemoteIdentity,\n ): Promise<OfflineReplicaRow<TValues> | null> {\n const schema = this.#resolveReplicaEntitySchema(sourceKey);\n canonicalOfflineRemoteIdentity(schema, identity);\n if (schema.identity.kind === 'generated') {\n const predicates = ['server_id = ?', '_offline_user_id = ?'];\n const values: SQLiteValue[] = [identity.remoteId!, canonicalOfflinePrincipalId(scope.userId)];\n if (schema.scope === 'partition') {\n predicates.push('_offline_scope_id = ?');\n values.push(scope.scopeId);\n }\n const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);\n const row = rows[0];\n return row ? this.#replicaRowFromSqliteRow<TValues>(schema, scope, sourceKey, row) : null;\n }\n const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey!);\n const predicates = ['_offline_user_id = ?'];\n const values: SQLiteValue[] = [canonicalOfflinePrincipalId(scope.userId)];\n if (schema.scope === 'partition') {\n predicates.push('_offline_scope_id = ?');\n values.push(scope.scopeId);\n }\n for (const sourceKeyPart of schema.identity.sourceKeys) {\n const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart)!;\n predicates.push(`${field.sqliteColumnName!} = ?`);\n values.push(naturalKey[sourceKeyPart]!);\n }\n const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);\n const row = rows[0];\n return row ? this.#replicaRowFromSqliteRow<TValues>(schema, scope, sourceKey, row) : null;\n }\n\n async #readReplicaCursor(scope: OfflineScope): Promise<OfflineReplicaCursor | null> {\n const rows = await this.#query('SELECT cursor FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', [\n canonicalOfflinePrincipalId(scope.userId),\n scope.scopeId,\n ]);\n const row = rows[0];\n if (!row) return null;\n return { ...scope, cursor: this.#string(row['cursor']) };\n }\n\n async #readPullAttentions(userId: OfflinePrincipalId): Promise<OfflinePullAttention[]> {\n const rows = await this.#query('SELECT scope_id, reason, status FROM offline_pull_attentions WHERE user_id = ? ORDER BY scope_id', [\n canonicalOfflinePrincipalId(userId),\n ]);\n return rows.map((row) => {\n const status = row['status'];\n const attention: OfflinePullAttention = {\n userId,\n scopeId: this.#string(row['scope_id']),\n reason: this.#string(row['reason']) as OfflinePullAttentionReason,\n };\n if (status !== null && status !== undefined) attention.status = this.#number(status);\n return attention;\n });\n }\n\n async #readCommands(scope: OfflineScope): Promise<OfflineCommand[]> {\n const rows = await this.#query(\n 'SELECT * FROM offline_sync_commands WHERE user_id = ? AND scope_id = ? ORDER BY created_at ASC, command_id ASC',\n [canonicalOfflinePrincipalId(scope.userId), scope.scopeId],\n );\n return rows.map((row) => this.#command(row));\n }\n\n async #readCommandsForUser(userId: OfflinePrincipalId): Promise<OfflineCommand[]> {\n const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? ORDER BY created_at ASC, command_id ASC', [\n canonicalOfflinePrincipalId(userId),\n ]);\n return rows.map((row) => this.#command(row));\n }\n\n #reader(): OfflineRepositoryReader {\n return {\n getLastUserId: () => this.#readLastUserId(),\n getSessionManifest: (userId) => this.#readSessionManifest(userId),\n getReplicaRow: async <TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null> =>\n (await this.#queryReplicaRow(scope, sourceKey, identity, false)) as OfflineReplicaRow<TValues> | null,\n getReplicaRowIncludingPendingDelete: async <TValues = unknown>(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n ): Promise<OfflineReplicaRow<TValues> | null> =>\n (await this.#queryReplicaRow(scope, sourceKey, identity, true)) as OfflineReplicaRow<TValues> | null,\n getReplicaRows: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey),\n getReplicaRowByRemoteId: async (scope, sourceKey, remoteId) => {\n if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated') return null;\n return this.#readReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });\n },\n getReplicaRowByRemoteIdentity: (scope, sourceKey, identity) => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity),\n getReplicaCursor: (scope) => this.#readReplicaCursor(scope),\n getPullAttentions: (userId) => this.#readPullAttentions(userId),\n getCommands: (scope) => this.#readCommands(scope),\n getCommandsForUser: (userId) => this.#readCommandsForUser(userId),\n };\n }\n\n #atomicRepository(): OfflineRepository {\n const reader = this.#reader();\n const atomicTransaction = <T>(run: (databaseId: string) => Promise<T>, marksCommit = true): Promise<T> =>\n this.#queueAtomicOperation(() => this.#atomicTransaction(this.#databaseId!, run, marksCommit));\n return {\n initialize: settledSqliteOperation,\n ...reader,\n runReadSnapshot: (read) =>\n this.#queueAtomicOperation(() =>\n this.#nativeTransaction(this.#databaseId!, async () => {\n this.#readSnapshotActive = true;\n const executeRead = async () => read(reader);\n return executeRead().finally(() => (this.#readSnapshotActive = false));\n }),\n ),\n putCommand: (command) => atomicTransaction((databaseId) => this.#putCommand(databaseId, command)),\n replaceCommand: (command) => atomicTransaction((databaseId) => this.#putCommand(databaseId, command)),\n removeCommand: (commandId) =>\n atomicTransaction((databaseId) => this.#execute(databaseId, 'DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId])),\n putPullAttention: (attention) =>\n atomicTransaction((databaseId) => this.#applyReplicaTransaction(databaseId, { putPullAttentions: [attention] })),\n removePullAttention: (scope) =>\n atomicTransaction((databaseId) => this.#applyReplicaTransaction(databaseId, { removePullAttentions: [scope] })),\n setLastUserId: (userId) =>\n atomicTransaction((databaseId) =>\n this.#execute(\n databaseId,\n `INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, ?)\n ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version, last_user_id = excluded.last_user_id`,\n [OFFLINE_SCHEMA_VERSION, canonicalOfflinePrincipalId(userId)],\n ),\n ),\n putSessionManifest: (userId, value) =>\n atomicTransaction((databaseId) =>\n this.#execute(\n databaseId,\n `INSERT INTO offline_session_manifests (user_id, value_json) VALUES (?, ?)\n ON CONFLICT(user_id) DO UPDATE SET value_json = excluded.value_json`,\n [canonicalOfflinePrincipalId(userId), JSON.stringify(value)],\n ),\n ),\n clearUser: (userId) => atomicTransaction((databaseId) => this.#clearUser(databaseId, userId)),\n clearScope: (scope) => atomicTransaction((databaseId) => this.#clearScope(databaseId, scope)),\n transactReplica: (transaction) => {\n for (const row of transaction.putRows ?? []) this.#validateReplicaRow(row);\n return atomicTransaction((databaseId) => this.#applyReplicaTransaction(databaseId, transaction));\n },\n };\n }\n\n async #withCommittedRead<T>(operation: () => Promise<T>): Promise<T> {\n await this.initialize();\n if (this.#readSnapshotActive) {\n return operation();\n }\n if (this.#atomicMutationRevision !== null) {\n return this.#queueAtomicOperation(operation);\n }\n await this.#writes;\n this.#beginReaders();\n const read = async (): Promise<T> => operation();\n return read().finally(() => this.#endReaders());\n }\n\n #beginReaders(): void {\n if (this.#activeReaders === 0) {\n this.#readersIdle = new Promise<void>((resolve) => {\n this.#resolveReadersIdle = resolve;\n });\n }\n this.#activeReaders += 1;\n }\n\n #endReaders(): void {\n this.#activeReaders -= 1;\n if (this.#activeReaders === 0) {\n this.#resolveReadersIdle?.();\n this.#resolveReadersIdle = null;\n this.#readersIdle = settledSqliteOperation();\n }\n }\n\n async #query(statement: string, values: SQLiteValue[] = []): Promise<SQLiteRow[]> {\n return this.#queryDatabase(await this.#databaseConnection(), statement, values);\n }\n\n #write(statement: string, values: SQLiteValue[]): Promise<void> {\n return this.#queueWrite((databaseId) => this.#execute(databaseId, statement, values));\n }\n\n #queueWrite(run: (databaseId: string) => Promise<void>): Promise<void> {\n if (this.#atomicMutationRevision !== null) {\n return this.#atomicIdle.then(() => this.#queueWrite(run));\n }\n const write = this.#writes.then(async (): Promise<void> => {\n if (this.#activeReaders > 0) await this.#readersIdle;\n await run(await this.#databaseConnection());\n });\n this.#writes = write.catch((): void => undefined);\n return write;\n }\n\n #transaction<T>(run: (databaseId: string) => Promise<T>): Promise<T> {\n if (this.#atomicMutationRevision !== null) {\n return this.#atomicIdle.then(() => this.#transaction(run));\n }\n const transaction = this.#writes.then(async (): Promise<T> => {\n if (this.#activeReaders > 0) await this.#readersIdle;\n const databaseId = await this.#databaseConnection();\n return this.#nativeTransaction(databaseId, () => run(databaseId));\n });\n this.#writes = transaction.then(\n () => undefined,\n () => undefined,\n );\n return transaction;\n }\n\n async #atomicTransaction<T>(databaseId: string, run: (databaseId: string) => Promise<T>, marksCommit = true): Promise<T> {\n const expected = this.#atomicMutationRevision;\n if (expected === null) throw new Error('Offline replica atomic mutation is not active.');\n const result = await this.#nativeTransaction(databaseId, async () => {\n // A write, even when it leaves the value unchanged, obtains SQLite's\n // RESERVED lock before the revision check. No second connection can\n // commit between this check and the transaction commit.\n await this.#execute(databaseId, 'UPDATE offline_metadata SET schema_version = schema_version WHERE id = 1');\n const actual = await this.#dataVersion(databaseId);\n if (actual !== expected) {\n throw new Error('Offline replica changed through another SQLite connection; retry the operation from fresh state.');\n }\n return run(databaseId);\n });\n if (marksCommit) this.#atomicMutationCommitted = true;\n return result;\n }\n\n #queueAtomicOperation<T>(run: () => Promise<T>): Promise<T> {\n const operation = this.#atomicOperations.then(run);\n this.#atomicOperations = operation.then(\n () => undefined,\n () => undefined,\n );\n return operation;\n }\n\n async #dataVersion(databaseId: string): Promise<number> {\n const rows = await this.#queryDatabase(databaseId, 'PRAGMA data_version');\n return this.#number(rows[0]?.['data_version']);\n }\n\n #command(row: SQLiteRow): OfflineCommand {\n return {\n commandId: this.#string(row['command_id']),\n userId: parseOfflinePrincipalId(this.#string(row['user_id'])),\n scopeId: this.#string(row['scope_id']),\n aggregateType: this.#string(row['aggregate_type']),\n sourceKey: this.#string(row['source_key']),\n identity: parseOfflineCommandIdentity(this.#parse(row['identity_json'])),\n operation: this.#string(row['operation']),\n payload: this.#parse(row['payload_json']),\n ...(row['local_only_footprint_json'] === null || row['local_only_footprint_json'] === undefined\n ? {}\n : { localOnlyFootprint: this.#parse(row['local_only_footprint_json']) }),\n replicaMutation: this.#string(row['replica_mutation']) as 'upsert' | 'delete',\n baseRevision: this.#parseNullable(row['base_revision_json']),\n state: this.#string(row['state']) as OfflineCommand['state'],\n attempts: this.#number(row['attempts']),\n retryAt: this.#numberOrNull(row['retry_at']),\n createdAt: this.#number(row['created_at']),\n lastErrorCode: this.#stringOrNull(row['last_error_code']),\n serverCommitUnknown: this.#numberOrNull(row['server_commit_unknown']) === 1,\n ...(row['reconciliation_identity_json'] === null || row['reconciliation_identity_json'] === undefined\n ? {}\n : { reconciliationIdentity: this.#parse(row['reconciliation_identity_json']) as OfflineCommand['reconciliationIdentity'] }),\n };\n }\n\n #putCommand(databaseId: string, command: OfflineCommand): Promise<void> {\n return this.#execute(\n databaseId,\n `INSERT INTO offline_sync_commands\n (command_id, user_id, scope_id, aggregate_type, source_key, identity_json, operation, payload_json,\n local_only_footprint_json, replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code,\n server_commit_unknown, reconciliation_identity_json)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(command_id) DO UPDATE SET\n user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,\n source_key = excluded.source_key,\n identity_json = excluded.identity_json, operation = excluded.operation, payload_json = excluded.payload_json,\n local_only_footprint_json = excluded.local_only_footprint_json,\n replica_mutation = excluded.replica_mutation,\n payload_hash = excluded.payload_hash,\n base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,\n retry_at = excluded.retry_at, created_at = excluded.created_at, last_error_code = excluded.last_error_code,\n server_commit_unknown = excluded.server_commit_unknown,\n reconciliation_identity_json = excluded.reconciliation_identity_json`,\n [\n command.commandId,\n canonicalOfflinePrincipalId(command.userId),\n command.scopeId,\n command.aggregateType,\n command.sourceKey,\n serializeOfflineCommandIdentity(command.identity),\n command.operation,\n JSON.stringify(command.payload),\n command.localOnlyFootprint === undefined ? null : JSON.stringify(command.localOnlyFootprint),\n command.replicaMutation ?? 'upsert',\n '',\n this.#stringifyNullable(command.baseRevision),\n command.state,\n command.attempts,\n command.retryAt,\n command.createdAt,\n command.lastErrorCode,\n command.serverCommitUnknown === true ? 1 : 0,\n command.reconciliationIdentity === undefined ? null : JSON.stringify(command.reconciliationIdentity),\n ],\n );\n }\n\n async #queryReplicaRow(\n scope: OfflineScope,\n sourceKey: string,\n identity: OfflineReplicaAddress,\n includePendingDelete: boolean,\n ): Promise<OfflineReplicaRow | null> {\n const schema = this.#resolveReplicaEntitySchema(sourceKey);\n const predicates = ['_offline_user_id = ?'];\n const values: SQLiteValue[] = [canonicalOfflinePrincipalId(scope.userId)];\n if (schema.scope === 'partition') {\n predicates.push('_offline_scope_id = ?');\n values.push(scope.scopeId);\n }\n if (identity.kind === 'generated' || identity.kind === 'local') {\n if (\n (identity.kind === 'generated' && schema.identity.kind !== 'generated') ||\n (identity.kind === 'local' && schema.identity.kind !== 'localOnly')\n ) {\n return null;\n }\n predicates.push('local_id = ?');\n values.push(identity.localId);\n } else {\n const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey);\n for (const sourceKeyPart of schema.identity.sourceKeys) {\n const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart)!;\n predicates.push(`${field.sqliteColumnName!} = ?`);\n values.push(naturalKey[sourceKeyPart]!);\n }\n }\n const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);\n const row = rows[0];\n if (!row || (!includePendingDelete && (row['_offline_visibility'] ?? 'present') === 'pending_delete')) return null;\n return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row);\n }\n\n async #putReplicaRow(databaseId: string, row: OfflineReplicaRow, release: OfflineReplicaRemoteIdRelease | undefined): Promise<void> {\n const schema = this.#resolveReplicaEntitySchema(row.sourceKey);\n if (row.identity.kind === 'generated') {\n assertOfflineReplicaGeneratedRemoteId(schema, row.identity.remoteId);\n }\n if (schema.identity.kind === 'naturalKey') {\n if (row.identity.kind !== 'natural') {\n throw new Error(`Offline replica source \"${row.sourceKey}\" requires natural identity.`);\n }\n const valuesIdentity = offlineNaturalKeyFromValues(schema, row.values)!;\n if (\n canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) !==\n canonicalOfflineRemoteIdentity(schema, { naturalKey: valuesIdentity })\n ) {\n throw new Error(`Offline replica identity naturalKey must match values for \"${schema.sourceKey}\".`);\n }\n }\n const encoded = encodeOfflineReplicaValues(schema, row.values);\n if (row.confirmedValues !== null) encodeOfflineReplicaValues(schema, row.confirmedValues);\n assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);\n const existing = await this.#queryReplicaRow(row, row.sourceKey, replicaAddressFromIdentity(row.identity), true);\n if (!existing && release) {\n throw new Error(\n `Offline replica remoteId release requires an existing row for ${row.sourceKey}/${canonicalOfflineReplicaIdentity(row.identity)}.`,\n );\n }\n if (existing) this.#assertReplicaIdentityAssignment(schema, existing, row, release);\n const confirmedValues = row.confirmedValues === null ? null : projectOfflineReplicaValues(schema, row.confirmedValues);\n const { sql, domainColumns } = this.#buildReplicaUpsertStatement(schema);\n const values: SQLiteValue[] = [];\n if (schema.identity.kind === 'generated' || schema.identity.kind === 'localOnly') {\n const expectedKind = schema.identity.kind === 'generated' ? 'generated' : 'local';\n if (row.identity.kind !== expectedKind) {\n throw new Error(`Offline replica source \"${row.sourceKey}\" requires ${expectedKind} identity.`);\n }\n values.push(row.identity.localId);\n }\n values.push(canonicalOfflinePrincipalId(row.userId));\n if (schema.scope === 'partition') values.push(row.scopeId);\n if (schema.identity.kind === 'generated') {\n if (row.identity.kind !== 'generated') {\n throw new Error(`Offline replica source \"${row.sourceKey}\" requires generated identity.`);\n }\n values.push(row.identity.remoteId);\n }\n values.push(\n confirmedValues === null ? null : JSON.stringify(confirmedValues),\n row.serverRevision == null ? null : JSON.stringify(row.serverRevision),\n row.syncState,\n row.visibility ?? 'present',\n row.fetchedAt,\n ...domainColumns.map((column) => encoded[column] ?? null),\n );\n await this.#execute(databaseId, sql, values);\n }\n\n #removeReplicaRow(databaseId: string, key: OfflineReplicaRowKey): Promise<void> {\n const schema = this.#resolveReplicaEntitySchema(key.sourceKey);\n const predicates = ['_offline_user_id = ?'];\n const values: SQLiteValue[] = [canonicalOfflinePrincipalId(key.userId)];\n if (schema.scope === 'partition') {\n predicates.push('_offline_scope_id = ?');\n values.push(key.scopeId);\n }\n if (key.identity.kind === 'generated' || key.identity.kind === 'local') {\n predicates.push('local_id = ?');\n values.push(key.identity.localId);\n } else {\n for (const sourceKeyPart of schema.identity.sourceKeys) {\n const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart)!;\n predicates.push(`${field.sqliteColumnName!} = ?`);\n values.push(key.identity.naturalKey[sourceKeyPart]!);\n }\n }\n return this.#execute(databaseId, `DELETE FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);\n }\n\n #putReplicaCursor(databaseId: string, cursor: OfflineReplicaCursor): Promise<void> {\n return this.#execute(\n databaseId,\n `INSERT INTO offline_replica_cursors (user_id, scope_id, cursor) VALUES (?, ?, ?)\n ON CONFLICT(user_id, scope_id) DO UPDATE SET cursor = excluded.cursor`,\n [canonicalOfflinePrincipalId(cursor.userId), cursor.scopeId, cursor.cursor],\n );\n }\n\n #buildReplicaUpsertStatement(schema: OfflineReplicaEntitySchema<Record<string, unknown>>): {\n sql: string;\n domainColumns: readonly string[];\n } {\n const insertColumns = ['_offline_user_id'];\n const updateSets = ['_offline_user_id = excluded._offline_user_id'];\n const conflictTarget: string[] = ['_offline_user_id'];\n if (schema.scope === 'partition') {\n insertColumns.push('_offline_scope_id');\n updateSets.push('_offline_scope_id = excluded._offline_scope_id');\n conflictTarget.push('_offline_scope_id');\n }\n if (schema.identity.kind === 'generated') {\n insertColumns.unshift('local_id');\n insertColumns.push('server_id');\n updateSets.push('server_id = excluded.server_id');\n conflictTarget.push('local_id');\n } else if (schema.identity.kind === 'naturalKey') {\n for (const sourceKey of schema.identity.sourceKeys) {\n const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKey)!;\n conflictTarget.push(field.sqliteColumnName!);\n }\n } else {\n insertColumns.unshift('local_id');\n conflictTarget.push('local_id');\n }\n insertColumns.push(\n '_offline_confirmed_json',\n '_offline_server_revision_json',\n '_offline_sync_state',\n '_offline_visibility',\n '_offline_fetched_at',\n );\n updateSets.push(\n '_offline_confirmed_json = excluded._offline_confirmed_json',\n '_offline_server_revision_json = excluded._offline_server_revision_json',\n '_offline_sync_state = excluded._offline_sync_state',\n '_offline_visibility = excluded._offline_visibility',\n '_offline_fetched_at = excluded._offline_fetched_at',\n );\n const domainColumns: string[] = [];\n for (const field of schema.fields) {\n if (field.policy !== 'column' || field.sqliteColumnName === null) continue;\n insertColumns.push(field.sqliteColumnName);\n updateSets.push(`${field.sqliteColumnName} = excluded.${field.sqliteColumnName}`);\n domainColumns.push(field.sqliteColumnName);\n }\n const placeholders = insertColumns.map(() => '?').join(', ');\n return {\n sql: `INSERT INTO ${schema.tableName} (${insertColumns.join(', ')})\n VALUES (${placeholders})\n ON CONFLICT(${conflictTarget.join(', ')}) DO UPDATE SET ${updateSets.join(', ')}`,\n domainColumns,\n };\n }\n\n #replicaRowFromSqliteRow<TValues>(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n scope: OfflineScope,\n sourceKey: string,\n row: SQLiteRow,\n ): OfflineReplicaRow<TValues> {\n const identity = this.#identityFromSqliteRow(schema, row);\n return {\n ...scope,\n sourceKey,\n identity,\n values: decodeOfflineReplicaValues(schema, row) as TValues,\n confirmedValues: this.#parseNullable<TValues>(row['_offline_confirmed_json']),\n serverRevision: this.#parseNullable<string | number>(row['_offline_server_revision_json']),\n fetchedAt: this.#number(row['_offline_fetched_at']),\n syncState: this.#string(row['_offline_sync_state']) as OfflineReplicaRow['syncState'],\n visibility: (row['_offline_visibility'] ?? 'present') as 'present' | 'pending_delete',\n };\n }\n\n #identityFromSqliteRow(schema: OfflineReplicaEntitySchema<Record<string, unknown>>, row: SQLiteRow): OfflineReplicaIdentity {\n if (schema.identity.kind === 'naturalKey') {\n return offlineNaturalReplicaIdentity(schema, decodeOfflineReplicaValues(schema, row));\n }\n const localId = this.#string(row['local_id']);\n if (schema.identity.kind === 'localOnly') return { kind: 'local', localId };\n const remoteId = row['server_id'];\n if (remoteId == null) return offlineGeneratedReplicaIdentity(localId, null);\n if (schema.identity.kind === 'generated' && schema.identity.affinity === 'TEXT') {\n return offlineGeneratedReplicaIdentity(localId, this.#string(remoteId));\n }\n return offlineGeneratedReplicaIdentity(localId, this.#number(remoteId));\n }\n\n #resolveReplicaEntitySchema(sourceKey: string): OfflineReplicaEntitySchema<Record<string, unknown>> {\n const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);\n if (!schema) throw new Error(`Unknown offline replica source key \"${sourceKey}\".`);\n return schema;\n }\n\n #validateReplicaRow(row: OfflineReplicaRow): void {\n const schema = this.#resolveReplicaEntitySchema(row.sourceKey);\n if (schema.identity.kind === 'localOnly') {\n if (row.identity.kind !== 'local') {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" requires local identity.`);\n }\n } else if (schema.identity.kind === 'generated') {\n if (row.identity.kind !== 'generated') {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" requires generated identity.`);\n }\n assertOfflineReplicaGeneratedRemoteId(schema, row.identity.remoteId);\n } else {\n if (row.identity.kind !== 'natural') {\n throw new Error(`Offline replica source \"${schema.sourceKey}\" requires natural identity.`);\n }\n const fromValues = offlineNaturalKeyFromValues(schema, row.values)!;\n if (\n canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) !==\n canonicalOfflineRemoteIdentity(schema, { naturalKey: fromValues })\n ) {\n throw new Error(`Offline replica identity naturalKey must match values for \"${schema.sourceKey}\".`);\n }\n }\n encodeOfflineReplicaValues(schema, row.values);\n if (row.confirmedValues !== null) encodeOfflineReplicaValues(schema, row.confirmedValues);\n assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);\n }\n\n #replicaRowKey(row: OfflineReplicaRowKey): string {\n const schema = this.#resolveReplicaEntitySchema(row.sourceKey);\n return canonicalOfflineReplicaRowKey(schema, row);\n }\n\n #assertReplicaIdentityAssignment(\n schema: OfflineReplicaEntitySchema<Record<string, unknown>>,\n existing: OfflineReplicaRow,\n incoming: OfflineReplicaRow,\n release: OfflineReplicaRemoteIdRelease | undefined,\n ): void {\n if (release && schema.identity.kind !== 'generated') {\n throw new Error(`Offline replica remoteId release is unsupported for source \"${incoming.sourceKey}\".`);\n }\n if (schema.identity.kind === 'localOnly') {\n if (existing.identity.kind !== 'local' || incoming.identity.kind !== 'local') {\n throw new Error(`Offline replica local identity is required for \"${incoming.sourceKey}\".`);\n }\n if (existing.identity.localId !== incoming.identity.localId) {\n throw new Error(`Offline replica localId is immutable for \"${schema.sourceKey}\".`);\n }\n return;\n }\n if (schema.identity.kind === 'generated') {\n if (existing.identity.kind !== 'generated' || incoming.identity.kind !== 'generated') {\n throw new Error(`Offline replica generated identity is required for \"${incoming.sourceKey}\".`);\n }\n if (release) {\n if (existing.identity.remoteId !== release.remoteId || incoming.identity.remoteId !== null) {\n throw new Error(\n `Offline replica remoteId release must transition current=${String(existing.identity.remoteId)} to incoming=null for ${incoming.sourceKey}/${incoming.identity.localId}.`,\n );\n }\n return;\n }\n if (existing.identity.localId !== incoming.identity.localId) {\n throw new Error(`Offline replica localId is immutable for \"${schema.sourceKey}\".`);\n }\n if (existing.identity.remoteId !== null && existing.identity.remoteId !== incoming.identity.remoteId) {\n throw new Error(\n `Offline replica remoteId is immutable: current=${String(existing.identity.remoteId)}, incoming=${String(incoming.identity.remoteId)}.`,\n );\n }\n return;\n }\n if (schema.identity.kind === 'naturalKey') {\n if (existing.identity.kind !== 'natural' || incoming.identity.kind !== 'natural') {\n throw new Error(`Offline replica natural identity is required for \"${schema.sourceKey}\".`);\n }\n const current = canonicalOfflineRemoteIdentity(schema, { naturalKey: existing.identity.naturalKey });\n const next = canonicalOfflineRemoteIdentity(schema, { naturalKey: incoming.identity.naturalKey });\n if (current !== next) throw new Error(`Offline replica naturalKey is immutable for \"${schema.sourceKey}\".`);\n }\n }\n\n #assertValidReleaseRemoteId(remoteId: import('./offline-replica-schema').OfflineGeneratedRemoteId): void {\n if (typeof remoteId === 'number') {\n if (!Number.isSafeInteger(remoteId) || remoteId <= 0) {\n throw new Error(`Offline replica release has invalid remoteId ${String(remoteId)}.`);\n }\n return;\n }\n if (typeof remoteId !== 'string' || remoteId.length === 0) {\n throw new Error(`Offline replica release has invalid remoteId ${String(remoteId)}.`);\n }\n }\n\n async #execute(databaseId: string, statement: string, values: SQLiteValue[] = []): Promise<void> {\n await this.#sqlite!.execute({ databaseId, statement, values });\n }\n\n async #queryDatabase(databaseId: string, statement: string, values: SQLiteValue[] = []): Promise<SQLiteRow[]> {\n const result = await this.#sqlite!.query({ databaseId, statement, values });\n return (result.rows ?? []).map((row) => {\n if (!Array.isArray(row)) return row as SQLiteRow;\n return Object.fromEntries(row.map((value, index) => [result.columns?.[index] ?? String(index), value]));\n });\n }\n\n #parse<T>(value: unknown): T {\n if (typeof value !== 'string') throw new Error('Invalid JSON value in offline SQLite database');\n return JSON.parse(value) as T;\n }\n\n #parseNullable<T>(value: unknown): T | null {\n return value == null ? null : this.#parse<T>(value);\n }\n\n #stringifyNullable(value: unknown): string | null {\n return value == null ? null : JSON.stringify(value);\n }\n\n #number(value: unknown): number {\n if (typeof value !== 'number') throw new Error('Invalid numeric value in offline SQLite database');\n return value;\n }\n\n #numberOrNull(value: unknown): number | null {\n return value == null ? null : this.#number(value);\n }\n\n #string(value: unknown): string {\n if (typeof value !== 'string') throw new Error('Invalid string value in offline SQLite database');\n return value;\n }\n\n #stringOrNull(value: unknown): string | null {\n return value == null ? null : this.#string(value);\n }\n}\n","import type { EnvironmentProviders, Provider, Type } from '@angular/core';\nimport { ErrorHandler, inject, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';\nimport { Capacitor } from '@capacitor/core';\nimport type { OfflineCommandExecutor, OfflineCommandResult } from './offline-command-executor';\nimport { OFFLINE_COMMAND_EXECUTOR, OFFLINE_SYNC_CONTEXT } from './offline-command-executor';\nimport type { OfflineCommandHooks } from './offline-command-hooks';\nimport { OFFLINE_COMMAND_HOOKS } from './offline-command-hooks';\nimport type { OfflineKitOptions } from './offline-kit-options';\nimport { OFFLINE_KIT_OPTIONS } from './offline-kit-options';\nimport { OfflineCoordinatorService } from './offline-coordinator.service';\nimport {\n OFFLINE_MUTATION_PERSISTENCE_ADAPTER,\n OFFLINE_MUTATION_PERSISTENCE_ENABLED,\n OfflineMutationPersistenceService,\n} from './offline-mutation-persistence.service';\nimport {\n IonicOfflineRepository,\n OFFLINE_REPOSITORY,\n selectOfflineRepository,\n supportsSynchronizedOfflineRepository,\n} from './offline-repository';\nimport type { OfflineMutationRequestPolicy, OfflineRequestPolicy } from './offline-request-policy';\nimport { provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy } from './offline-request-policy';\nimport type { OfflineAggregateIntentProjector } from './offline-aggregate-intent-projector';\nimport { OFFLINE_AGGREGATE_INTENT_PROJECTOR } from './offline-aggregate-intent-projector';\nimport type { OfflineReplicaProjector, OfflineReplicaPuller } from './offline-replica-puller';\nimport { OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER } from './offline-replica-puller';\nimport { OfflineSessionService } from './offline-session.service';\nimport {\n COMMUNITY_SQLITE,\n type CommunitySqliteConnection,\n createCommunitySqliteDriver,\n SqliteOfflineRepository,\n} from './sqlite-offline-repository';\n\n/** Configuration for the standard offline repository, outbox, and request-policy runtime. */\ninterface ProvideOfflineOptionsBase extends OfflineKitOptions {\n /** Product policies that map URLs and DTOs to generic replica/outbox operations. */\n requestPolicies: readonly Type<OfflineRequestPolicy>[];\n /** Optional product hooks for entity projection and command cleanup. */\n commandHooks?: Type<OfflineCommandHooks>;\n /** Optional additional providers required by product adapters. */\n providers?: readonly Provider[];\n /** Optional pure adapter for product-owned local-only projections applied inside the Kit pull transaction. */\n replicaProjector?: Type<OfflineReplicaProjector>;\n /** Application-installed `@capacitor-community/sqlite` connection. Required only on iOS and Android. */\n sqliteConnection?: CommunitySqliteConnection;\n}\n\n/** Full replica pull and durable Outbox synchronization. */\nexport interface ProvideSynchronizedOfflineOptions extends ProvideOfflineOptionsBase {\n mode?: 'synchronized';\n /** Creates the encrypted native database key on first install. */\n createEncryptionKey: () => Promise<string>;\n /** Product policies that replace matched writes with atomic local-first mutations. */\n mutationPolicies?: readonly Type<OfflineMutationRequestPolicy>[];\n /** Product adapter that sends opaque commands to its API. */\n commandExecutor: Type<OfflineCommandExecutor>;\n /** Product transport for explicit cursor-based server delta pulls. */\n replicaPuller: Type<OfflineReplicaPuller>;\n /**\n * Required pure adapter that rematerializes one aggregate from its\n * authoritative confirmed base/localOnly values and remaining Outbox intents.\n *\n * Kit calls it inside {@link OfflineReplicaMutationCoordinator} after enqueue,\n * replacement, discard, transport success, and pull acknowledgement. Do not\n * call the projector from product code.\n */\n aggregateIntentProjector: Type<OfflineAggregateIntentProjector>;\n}\n\n/** Server- or external-source read cache with no mutation transport or Outbox. */\nexport interface ProvideReadCacheOfflineOptions extends ProvideOfflineOptionsBase {\n mode: 'readCacheOnly';\n /** Creates the encrypted native cache database key on first install. Unused by the web repository. */\n createEncryptionKey: () => Promise<string>;\n mutationPolicies?: never;\n mutationPersistence?: never;\n commandExecutor?: never;\n replicaPuller?: never;\n}\n\nexport type ProvideOfflineOptions = ProvideSynchronizedOfflineOptions | ProvideReadCacheOfflineOptions;\n\nconst READ_CACHE_ONLY_COMMAND_EXECUTOR: OfflineCommandExecutor = {\n execute: async (): Promise<OfflineCommandResult> => {\n throw new Error('This offline provider is configured as a read-only cache.');\n },\n};\n\nconst READ_CACHE_ONLY_REPLICA_PULLER: OfflineReplicaPuller = {\n pull: async (request) => ({\n schemaVersion: request.schemaVersion,\n schemaHash: request.schemaHash,\n changes: [],\n nextCursor: request.cursor,\n hasMore: false,\n }),\n};\n\n/**\n * Provide the standard scoped offline runtime.\n *\n * @remarks\n * Web uses Ionic Storage. Native iOS/Android uses encrypted `@capacitor-community/sqlite`. The application owns\n * URL/DTO policy and command execution; the kit owns persistence, ordering, retries, and session\n * isolation.\n *\n * Optional {@link OfflineKitOptions.onStorageUnavailable} opts into online-only startup when\n * local storage cannot be opened; without it, the app initializer still throws.\n */\nexport function provideOffline(options: ProvideOfflineOptions): EnvironmentProviders {\n const synchronized = options.mode !== 'readCacheOnly';\n return makeEnvironmentProviders([\n ...(synchronized ? [options.commandExecutor, options.replicaPuller] : []),\n {\n provide: OFFLINE_KIT_OPTIONS,\n useValue: {\n mode: options.mode ?? 'synchronized',\n databaseName: options.databaseName,\n createEncryptionKey: options.createEncryptionKey,\n replicaSchema: options.replicaSchema,\n wireProtocol: options.wireProtocol,\n outboxLimits: options.outboxLimits,\n mutationPersistence: options.mutationPersistence,\n onStorageUnavailable: options.onStorageUnavailable,\n },\n },\n {\n provide: COMMUNITY_SQLITE,\n useValue: options.sqliteConnection ? createCommunitySqliteDriver(options.sqliteConnection) : null,\n },\n {\n provide: OFFLINE_REPOSITORY,\n useFactory: () => selectOfflineRepository(Capacitor.getPlatform(), inject(IonicOfflineRepository), inject(SqliteOfflineRepository)),\n },\n {\n provide: OFFLINE_MUTATION_PERSISTENCE_ENABLED,\n useFactory: () => inject(OfflineMutationPersistenceService).enabled,\n },\n ...(options.mutationPersistence\n ? [\n options.mutationPersistence.adapter,\n { provide: OFFLINE_MUTATION_PERSISTENCE_ADAPTER, useExisting: options.mutationPersistence.adapter },\n ]\n : []),\n { provide: OFFLINE_SYNC_CONTEXT, useExisting: OfflineSessionService },\n synchronized\n ? { provide: OFFLINE_COMMAND_EXECUTOR, useExisting: options.commandExecutor }\n : { provide: OFFLINE_COMMAND_EXECUTOR, useValue: READ_CACHE_ONLY_COMMAND_EXECUTOR },\n synchronized\n ? { provide: OFFLINE_REPLICA_PULLER, useExisting: options.replicaPuller }\n : { provide: OFFLINE_REPLICA_PULLER, useValue: READ_CACHE_ONLY_REPLICA_PULLER },\n ...(options.commandHooks ? [options.commandHooks, { provide: OFFLINE_COMMAND_HOOKS, useExisting: options.commandHooks }] : []),\n ...(options.replicaProjector\n ? [options.replicaProjector, { provide: OFFLINE_REPLICA_PROJECTOR, useExisting: options.replicaProjector }]\n : []),\n ...(synchronized && 'aggregateIntentProjector' in options && options.aggregateIntentProjector\n ? [options.aggregateIntentProjector, { provide: OFFLINE_AGGREGATE_INTENT_PROJECTOR, useExisting: options.aggregateIntentProjector }]\n : []),\n ...options.requestPolicies.flatMap((policy) => provideOfflineRequestPolicy(policy)),\n ...(options.mutationPolicies ?? []).flatMap((policy) => provideOfflineMutationRequestPolicy(policy)),\n ...(options.providers ?? []),\n provideAppInitializer(() => {\n assertSupportedOfflineMode(Capacitor.getPlatform(), options.mode ?? 'synchronized');\n const coordinator = inject(OfflineCoordinatorService);\n const errorHandler = inject(ErrorHandler);\n const localInitialization = coordinator.initializeLocal();\n void coordinator.initialize().catch(async (error: unknown) => {\n const localSucceeded = await localInitialization.then(\n () => true,\n () => false,\n );\n if (!localSucceeded) return;\n try {\n errorHandler.handleError(error);\n } catch {\n // Error reporting must not create an unhandled background rejection.\n }\n });\n return localInitialization;\n }),\n ]);\n}\n\n/** Prevents unsupported multi-tab Web writes from silently losing Outbox state. */\nexport function assertSupportedOfflineMode(platform: string, mode: 'synchronized' | 'readCacheOnly'): void {\n if (!supportsSynchronizedOfflineRepository(platform) && mode === 'synchronized') {\n throw new Error(\n 'Offline synchronized mode is supported only by native repositories. Use readCacheOnly until the selected repository provides cross-context locking.',\n );\n }\n}\n","import type { HttpEvent, HttpInterceptorFn, HttpRequest } from '@angular/common/http';\nimport { HttpResponse as AngularHttpResponse } from '@angular/common/http';\nimport { ErrorHandler, inject, Injectable } from '@angular/core';\nimport type { Notification, Observable, ObservableNotification } from 'rxjs';\nimport {\n catchError,\n concat,\n concatMap,\n connect,\n defer,\n dematerialize,\n EMPTY,\n from,\n map,\n materialize,\n of,\n ReplaySubject,\n take,\n tap,\n throwError,\n} from 'rxjs';\nimport { isOfflineFallbackError, OfflineNetworkService } from './offline-network.service';\nimport { OFFLINE_MUTATION_PERSISTENCE_ENABLED } from './offline-mutation-persistence.service';\nimport {\n OFFLINE_BYPASS,\n OFFLINE_RESPONSE_HEADER,\n OfflineMutationRequestPolicyRegistry,\n OfflineRequestPolicyRegistry,\n type OfflineReadRequestPlan,\n} from './offline-request-policy';\n\nconst LOCAL_FIRST_MUTATION_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);\n\ntype MaterializedTransport = Notification<HttpEvent<unknown>> & ObservableNotification<HttpEvent<unknown>>;\n\n/** Applies product read and local-first mutation policies while observing real API reachability. */\nexport const offlineInterceptor: HttpInterceptorFn = (request, next) => {\n const network = inject(OfflineNetworkService);\n const transport = () => observeTransport(next(request), network);\n if (request.context.get(OFFLINE_BYPASS)) return transport();\n if (request.method === 'GET') {\n const registry = inject(OfflineRequestPolicyRegistry);\n const fallback = inject(OfflineRequestFallbackService);\n const plan = registry.resolve(request);\n if (!plan) return transport();\n if (plan.readStrategy === 'local-first') {\n return readLocalFirst(request, plan, transport, fallback, inject(ErrorHandler));\n }\n return readNetworkFirst(request, plan, transport, fallback);\n }\n if (LOCAL_FIRST_MUTATION_METHODS.has(request.method)) {\n if (!inject(OFFLINE_MUTATION_PERSISTENCE_ENABLED)()) return transport();\n const plan = inject(OfflineMutationRequestPolicyRegistry).resolve(request);\n if (plan) {\n return defer(() => from(plan.prepare())).pipe(\n map((response) => response.clone({ headers: response.headers.set(OFFLINE_RESPONSE_HEADER, 'optimistic') })),\n );\n }\n }\n return transport();\n};\n\nfunction readNetworkFirst(\n request: HttpRequest<unknown>,\n plan: OfflineReadRequestPlan,\n transport: () => Observable<HttpEvent<unknown>>,\n fallback: OfflineRequestFallbackService,\n): Observable<HttpEvent<unknown>> {\n return defer(transport).pipe(\n catchError((error: unknown) => fallback.handle(request, error, plan) ?? throwError(() => error)),\n concatMap((event) => projectReadResponse(event, plan)),\n );\n}\n\n/**\n * Stale-while-revalidate local-first GET handling.\n *\n * @remarks\n * Starts raw transport and `readLocal()` concurrently at outer subscription,\n * buffers materialized remote notifications until the local attempt settles,\n * emits a projected local response first on hit, then drains/projects the\n * buffered transport. Remote projection begins only after the local decision.\n *\n * Consumers must keep the returned observable subscribed through revalidation;\n * `firstValueFrom` and `take(1)` cancel in-flight transport and suppress\n * further emissions.\n */\nfunction readLocalFirst(\n request: HttpRequest<unknown>,\n plan: OfflineReadRequestPlan,\n transport: () => Observable<HttpEvent<unknown>>,\n fallback: OfflineRequestFallbackService,\n errorHandler: ErrorHandler,\n): Observable<HttpEvent<unknown>> {\n return defer(transport).pipe(\n materialize(),\n connect(\n (bufferedTransport$) =>\n resolveLocalAttempt(plan, errorHandler).pipe(\n concatMap((localResponse) =>\n localResponse\n ? concat(of(localResponse), drainRemoteAfterLocal(bufferedTransport$, plan))\n : drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback),\n ),\n ),\n { connector: () => new ReplaySubject<MaterializedTransport>() },\n ),\n );\n}\n\nfunction resolveLocalAttempt(plan: OfflineReadRequestPlan, errorHandler: ErrorHandler): Observable<HttpEvent<unknown> | null> {\n return defer(() =>\n from(plan.readLocal()).pipe(\n catchError((localError: unknown) => {\n errorHandler.handleError(localError);\n return of(null);\n }),\n ),\n ).pipe(\n concatMap((local) => (local ? tryProjectLocal(local, plan, errorHandler) : of(null))),\n take(1),\n );\n}\n\nfunction tryProjectLocal(\n cached: AngularHttpResponse<unknown>,\n plan: OfflineReadRequestPlan,\n errorHandler: ErrorHandler,\n): Observable<HttpEvent<unknown> | null> {\n return emitTaggedLocalResponse(cached, plan).pipe(\n catchError((error: unknown) => {\n errorHandler.handleError(error);\n return of(null);\n }),\n );\n}\n\nfunction emitTaggedLocalResponse(cached: AngularHttpResponse<unknown>, plan: OfflineReadRequestPlan): Observable<HttpEvent<unknown>> {\n return projectReadResponse(cached.clone({ headers: cached.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }), plan);\n}\n\nfunction drainRemoteAfterLocal(\n bufferedTransport$: Observable<MaterializedTransport>,\n plan: OfflineReadRequestPlan,\n): Observable<HttpEvent<unknown>> {\n return bufferedTransport$.pipe(\n dematerialize(),\n catchError((error: unknown) => (isOfflineFallbackError(error) ? EMPTY : throwError(() => error))),\n concatMap((event) => projectReadResponse(event, plan)),\n );\n}\n\nfunction drainRemoteNetworkFirst(\n bufferedTransport$: Observable<MaterializedTransport>,\n request: HttpRequest<unknown>,\n plan: OfflineReadRequestPlan,\n fallback: OfflineRequestFallbackService,\n): Observable<HttpEvent<unknown>> {\n return bufferedTransport$.pipe(\n dematerialize(),\n catchError((error: unknown) => fallback.handle(request, error, plan) ?? throwError(() => error)),\n concatMap((event) => projectReadResponse(event, plan)),\n );\n}\n\nfunction projectReadResponse(event: HttpEvent<unknown>, plan: OfflineReadRequestPlan): Observable<HttpEvent<unknown>> {\n if (!(event instanceof AngularHttpResponse) || !plan.projectResponse) return of(event);\n const source = event.headers.get(OFFLINE_RESPONSE_HEADER) === 'local' ? 'local' : 'remote';\n return from(plan.projectResponse(event, source)).pipe(\n map((response) =>\n source === 'local' ? response.clone({ headers: response.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }) : response,\n ),\n );\n}\n\nfunction observeTransport(source: Observable<HttpEvent<unknown>>, network: OfflineNetworkService): Observable<HttpEvent<unknown>> {\n return source.pipe(\n tap({\n next: (event) => {\n if (!(event instanceof AngularHttpResponse)) return;\n if (event.headers.get(OFFLINE_RESPONSE_HEADER) === 'local') {\n network.markApiFailure();\n return;\n }\n network.markApiSuccess();\n },\n error: (error: unknown) => {\n if (isOfflineFallbackError(error)) network.markApiFailure();\n },\n }),\n );\n}\n\n/** Resolves transport failures from the local replica without hiding HTTP errors. */\n@Injectable({ providedIn: 'root' })\nexport class OfflineRequestFallbackService {\n readonly #registry = inject(OfflineRequestPolicyRegistry);\n readonly #errorHandler = inject(ErrorHandler);\n\n handle(\n request: HttpRequest<unknown>,\n error: unknown,\n resolvedPlan?: ReturnType<OfflineRequestPolicyRegistry['resolve']>,\n ): Observable<HttpEvent<unknown>> | null {\n if (request.context.get(OFFLINE_BYPASS) || request.method !== 'GET' || !isOfflineFallbackError(error)) return null;\n const plan = resolvedPlan ?? this.#registry.resolve(request);\n if (!plan || plan.kind !== 'read') return null;\n return defer(() => from(plan.readLocal())).pipe(\n catchError((localError: unknown) => {\n this.#errorHandler.handleError(localError);\n return throwError(() => error);\n }),\n concatMap((cached) =>\n cached ? of(cached.clone({ headers: cached.headers.set(OFFLINE_RESPONSE_HEADER, 'local') })) : throwError(() => error),\n ),\n );\n }\n}\n","/** Standard scoped local replica and outbox runtime for offline-capable Ionic applications. */\nexport * from './lib/offline-replica-schema';\nexport * from './lib/offline-identity';\nexport * from './lib/offline-aggregate-intent-projector';\nexport * from './lib/offline-replica-puller';\nexport * from './lib/offline-replica-pull.service';\nexport * from './lib/offline-replica-mutation-coordinator';\nexport * from './lib/offline-command-executor';\nexport * from './lib/offline-command-hooks';\nexport * from './lib/offline-auth-bridge';\nexport * from './lib/offline-coordinator.service';\nexport * from './lib/offline-kit-options';\nexport * from './lib/offline-local-reset';\nexport * from './lib/offline-mutation-envelope';\nexport { OfflineMutationPersistenceDisabledError } from './lib/offline-mutation-admission.service';\nexport {\n OfflineMutationPersistencePendingError,\n OfflineMutationPersistenceRequiresOnlineError,\n OfflineMutationPersistenceService,\n} from './lib/offline-mutation-persistence.service';\nexport * from './lib/offline-network.service';\nexport * from './lib/offline-provider';\nexport * from './lib/offline-repository';\nexport * from './lib/offline-request-policy';\nexport * from './lib/offline-session.service';\nexport * from './lib/offline-storage';\nexport * from './lib/offline-sync.service';\nexport * from './lib/offline.interceptor';\nexport * from './lib/sqlite-offline-repository';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":["isPlainObject","compareOfflineCommands","map","AngularHttpResponse"],"mappings":";;;;;;;;;;;AAmBA,MAAM,kCAAkC,GAAG,IAAI;AA6J/C,MAAM,kBAAkB,GAAG,mBAAmB;AAC9C,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC;IACpC,UAAU;IACV,kBAAkB;IAClB,mBAAmB;IACnB,WAAW;IACX,yBAAyB;IACzB,+BAA+B;IAC/B,qBAAqB;IACrB,qBAAqB;AACtB,CAAA,CAAC;AAEF;;;;;;AAMG;SACa,mBAAmB,GAAA;IACjC,OAAO,SAAS,yBAAyB,CAEvC,UAA4D,EAAA;AAC5D,QAAA,OAAO,+BAA+B,CAAU;YAC9C,KAAK,EAAE,UAAU,CAAC,KAAK;YACvB,SAAS,EAAE,UAAU,CAAC,SAAS;YAC/B,KAAK,EAAE,UA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