@keepkit/core 0.28.14 → 0.28.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -1
- package/dist/{chunk-WKXLHEAK.js → chunk-HTTOCLOC.js} +1 -1
- package/dist/chunk-HTTOCLOC.js.map +1 -0
- package/dist/{chunk-36NNVLEU.js → chunk-OLGYOC3D.js} +2 -2
- package/dist/core.d.ts +4 -4
- package/dist/core.js +2 -2
- package/dist/react.d.ts +4 -4
- package/dist/react.js +11 -5
- package/dist/react.js.map +1 -1
- package/dist/schema.d.ts +1 -1
- package/dist/storage.d.ts +2 -2
- package/dist/storage.js +1 -1
- package/dist/{store-D-ZFtgDn.d.ts → store-3LwroO9A.d.ts} +1 -1
- package/dist/{types-KNIY89_m.d.ts → types-Bnc0c8CB.d.ts} +2 -0
- package/package.json +1 -1
- package/dist/chunk-WKXLHEAK.js.map +0 -1
- /package/dist/{chunk-36NNVLEU.js.map → chunk-OLGYOC3D.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/features/items/types.ts","../src/features/persistence/helpers.ts","../src/features/persistence/scope.ts","../src/features/persistence/serialization.ts","../src/features/persistence/migration.ts","../src/features/persistence/backup.ts","../src/features/persistence/write-lock.ts","../src/storage/recovery-journal.ts","../src/storage/sync.ts","../src/storage/index.ts"],"sourcesContent":["import type { KeepStorageRecovery } from \"../../storage/recovery-journal\";\n\nexport type KeepItemStatus = \"available\" | \"expired\" | \"removed\" | \"deleted\" | \"private\" | \"unknown\";\n\nexport type SyncScope = {\n userId?: string;\n tenantId?: string;\n};\n\nexport type KeepCollectionDefinition = {\n id: string;\n name: string;\n scope?: SyncScope;\n /** Server revision used for optimistic collection conflict checks. */\n revision?: string;\n updatedAt?: number;\n};\n\n/** A course-specific membership; the same item may have memberships in several collections. */\nexport type KeepCollectionMembership = {\n collectionId: string;\n itemId: string;\n /** Zero-based order within this collection. */\n order: number;\n scope?: SyncScope;\n};\n\nexport type KeepItem<TMeta = Record<string, unknown>> = {\n id: string;\n savedAt: number;\n updatedAt: number;\n meta: TMeta;\n /** Optional zero-based position in the user's custom viewing order. */\n order?: number;\n /** Whether the item is hidden from the default active list. */\n archived?: boolean;\n /** Whether the item should be shown before unpinned items. */\n pinned?: boolean;\n /** Timestamp for the last time the saved item was opened. */\n lastOpenedAt?: number;\n /** Optional derived collection identifier. */\n collectionId?: string;\n targetType?: string;\n note?: string;\n tags?: string[];\n schemaVersion?: number;\n /** Optional server-provided revision used by synchronizing adapters. */\n revision?: string;\n /** Timestamp for the last successful refresh of source metadata. */\n metaUpdatedAt?: number;\n /** Source availability as last determined by a revalidator. Omitted means available. */\n status?: KeepItemStatus;\n /** Optional human-readable or machine-provided reason for a non-available status. */\n statusReason?: string;\n /** Optional user/tenant scope used by a synchronizing adapter. */\n scope?: SyncScope;\n};\n\n/** The minimal item description accepted by save controls and hooks. */\nexport type KeepItemInput<TMeta = Record<string, unknown>> = {\n id: string;\n meta: TMeta;\n order?: number;\n targetType?: string;\n note?: string;\n tags?: string[];\n archived?: boolean;\n pinned?: boolean;\n collectionId?: string;\n};\n\nexport interface StorageAdapter<TMeta = Record<string, unknown>> {\n /** Active user/tenant scope when this adapter is scoped. */\n readonly scope?: SyncScope;\n /** Optional local fallback status and explicitly invoked repair tools. */\n readonly recovery?: KeepStorageRecovery<TMeta>;\n getAll(): Promise<KeepItem<TMeta>[]>;\n /** Optional local collection metadata; independent of saved items and item backups. */\n getCollections?(): Promise<KeepCollectionDefinition[]>;\n /** Upsert by collection ID within the provided scope. */\n setCollection?(collection: KeepCollectionDefinition): Promise<void>;\n removeCollection?(id: string, scope?: SyncScope): Promise<void>;\n getCollectionMemberships?(): Promise<KeepCollectionMembership[]>;\n /** Upsert by collection ID and item ID within the provided scope. */\n setCollectionMembership?(membership: KeepCollectionMembership): Promise<void>;\n removeCollectionMembership?(collectionId: string, itemId: string, scope?: SyncScope): Promise<void>;\n set(item: KeepItem<TMeta>): Promise<void>;\n setMany?(items: KeepItem<TMeta>[]): Promise<void>;\n remove(id: string, scope?: SyncScope): Promise<void>;\n removeMany?(ids: string[], scope?: SyncScope): Promise<void>;\n clear(): Promise<void>;\n merge?(localItems: KeepItem<TMeta>[]): Promise<KeepItem<TMeta>[]>;\n subscribe?(listener: () => void): () => void;\n readonly storageKey?: string;\n}\n\nexport type KeepAction =\n | \"refresh\"\n | \"import\"\n | \"export\"\n | \"save\"\n | \"updateNote\"\n | \"updateTags\"\n | \"updateTagsBatch\"\n | \"archive\"\n | \"pin\"\n | \"open\"\n | \"collection\"\n | \"revalidate\"\n | \"remove\"\n | \"removeBatch\"\n | \"undo\"\n | \"reorder\"\n | \"clear\";\n\nexport type KeepChangePhase = \"local\" | \"synced\";\n\nexport type KeepChangeContext<TMeta = Record<string, unknown>> = {\n action: KeepAction;\n id?: string;\n item?: KeepItem<TMeta>;\n items?: KeepItem<TMeta>[];\n phase: KeepChangePhase;\n};\n\nexport type KeepPluginContext<TMeta = Record<string, unknown>> = {\n action: KeepAction;\n id?: string;\n item?: KeepItem<TMeta>;\n items?: KeepItem<TMeta>[];\n};\n\nexport type KeepPlugin<TMeta = Record<string, unknown>> = {\n name?: string;\n before?: (context: KeepPluginContext<TMeta>) => void | Promise<void>;\n after?: (context: KeepPluginContext<TMeta>) => void | Promise<void>;\n onError?: (error: unknown, context: KeepErrorContext) => void;\n};\n\nexport type KeepSchemaParseResult<T> = { success: true; data: T } | { success: false; error?: unknown };\n\nexport type KeepSchema<T> =\n | { parse: (value: unknown) => T | Promise<T> }\n | { safeParse: (value: unknown) => KeepSchemaParseResult<T> | Promise<KeepSchemaParseResult<T>> }\n | {\n \"~standard\": {\n validate: (\n value: unknown,\n ) => { value?: T; issues?: readonly unknown[] } | Promise<{ value?: T; issues?: readonly unknown[] }>;\n };\n };\n\nexport type KeepInvalidItemPolicy = \"error\" | \"drop\";\n\nexport type KeepSyncStatus = \"idle\" | \"pending\" | \"syncing\" | \"synced\" | \"conflict\" | \"error\";\n\nexport type KeepSyncResolution = \"local\" | \"remote\" | \"manual\";\n\nexport type KeepSyncConflict<TMeta = Record<string, unknown>> = {\n id: string;\n operation: SyncOperation<TMeta>;\n remote: KeepItem<TMeta>;\n revision?: string;\n};\n\nexport type KeepSyncRejectedOperation<TMeta = Record<string, unknown>> = {\n operation: KeepSyncQueueOperation<TMeta>;\n error: unknown;\n};\n\nexport type KeepSyncState<TMeta = Record<string, unknown>> = {\n status: KeepSyncStatus;\n pendingCount: number;\n conflictIds: string[];\n /** Detailed conflict records when the adapter supports interactive resolution. */\n conflicts?: KeepSyncConflict<TMeta>[];\n collectionConflicts?: KeepCollectionSyncConflict[];\n /** Permanently rejected operations stay queued until the host retries or discards them. */\n rejectedOperations?: KeepSyncRejectedOperation<TMeta>[];\n lastSyncedAt?: number;\n error?: unknown;\n};\n\nexport type SyncOperation<TMeta = Record<string, unknown>> = {\n operationId: string;\n type: \"upsert\" | \"remove\";\n /** Collection operations use a separate driver hook while sharing the durable queue format. */\n entity?: \"item\" | \"collection\";\n id: string;\n item?: KeepItem<TMeta>;\n collection?: KeepCollectionDefinition;\n createdAt: number;\n baseRevision?: string;\n attempts?: number;\n scope?: SyncScope;\n};\n\nexport type KeepCollectionSyncOperation = {\n operationId: string;\n type: \"upsert\" | \"remove\";\n entity: \"collection\";\n id: string;\n collection?: KeepCollectionDefinition;\n createdAt: number;\n baseRevision?: string;\n attempts?: number;\n scope?: SyncScope;\n};\n\n/** A conflict carries a tombstone or the complete definition needed to inspect or apply its state. */\ntype KeepCollectionConflictState =\n | { deleted: true; collection?: never }\n | { deleted: false; collection: KeepCollectionDefinition };\n\nexport type KeepCollectionSyncResult =\n | { type: \"synced\"; collection?: KeepCollectionDefinition; deleted?: boolean; revision?: string }\n | ({ type: \"conflict\"; resolution: \"local\" | \"remote\" | \"manual\"; revision?: string } & KeepCollectionConflictState);\n\nexport type KeepCollectionSyncConflict = {\n operation: KeepCollectionSyncOperation;\n resolution: \"local\" | \"remote\" | \"manual\";\n revision?: string;\n} & KeepCollectionConflictState;\n\nexport type KeepMembershipSyncOperation = {\n operationId: string;\n type: \"upsert\" | \"remove\";\n entity: \"membership\";\n id: string;\n collectionId: string;\n itemId: string;\n membership?: KeepCollectionMembership;\n createdAt: number;\n attempts?: number;\n scope?: SyncScope;\n};\n\nexport type KeepSyncQueueOperation<TMeta = Record<string, unknown>> =\n | SyncOperation<TMeta>\n | KeepCollectionSyncOperation\n | KeepMembershipSyncOperation;\n\nexport type KeepSyncAuthStatus = 401 | 403;\n\n/** Indicates that a sync request needs the host application to re-authenticate. */\nexport class KeepSyncAuthError<TMeta = Record<string, unknown>> extends Error {\n readonly status: KeepSyncAuthStatus;\n readonly operation?: SyncOperation<TMeta>;\n readonly scope?: SyncScope;\n readonly cause?: unknown;\n\n constructor(\n status: KeepSyncAuthStatus,\n options: { operation?: SyncOperation<TMeta>; scope?: SyncScope; cause?: unknown },\n ) {\n super(`KeepKit sync authorization failed with status ${status}.`);\n this.name = \"KeepSyncAuthError\";\n this.status = status;\n this.operation = options.operation;\n this.scope = options.scope;\n if (options.cause !== undefined) this.cause = options.cause;\n }\n}\n\nexport function isKeepSyncAuthError(error: unknown): error is KeepSyncAuthError {\n return error instanceof KeepSyncAuthError;\n}\n\nexport type RemoteSyncResult<TMeta = Record<string, unknown>> =\n | { type: \"synced\"; item?: KeepItem<TMeta>; revision?: string }\n | { type: \"conflict\"; remote: KeepItem<TMeta>; revision?: string };\n\nexport type KeepConflictContext<TMeta = Record<string, unknown>> = {\n operation: SyncOperation<TMeta>;\n remoteRevision?: string;\n};\n\nexport type KeepConflictResolver<TMeta = Record<string, unknown>> = (\n local: KeepItem<TMeta> | undefined,\n remote: KeepItem<TMeta>,\n context: KeepConflictContext<TMeta>,\n) => KeepItem<TMeta> | undefined | Promise<KeepItem<TMeta> | undefined>;\n\nexport interface RemoteSyncDriver<TMeta = Record<string, unknown>> {\n push(operation: SyncOperation<TMeta>): Promise<RemoteSyncResult<TMeta>>;\n /** Return remote items for the active scope; with `itemPullMode: \"snapshot\"` this must be the complete list. */\n pull?: () => Promise<KeepItem<TMeta>[]>;\n /** Push collection operations through the same scoped, durable queue as item operations. */\n // biome-ignore lint/suspicious/noConfusingVoidType: Existing drivers may return void; new drivers can return conflict results.\n pushCollection?(operation: KeepCollectionSyncOperation): Promise<void | KeepCollectionSyncResult>;\n /** Return the complete collection snapshot for the active authenticated scope. */\n pullCollections?: () => Promise<KeepCollectionDefinition[]>;\n /** Push collection/item membership operations through the same durable queue. */\n pushMembership?(operation: KeepMembershipSyncOperation): Promise<void>;\n /** Return the complete membership snapshot for the active authenticated scope. */\n pullMemberships?: () => Promise<KeepCollectionMembership[]>;\n}\n\nexport interface SyncQueueAdapter<TMeta = Record<string, unknown>> {\n getAll(): Promise<KeepSyncQueueOperation<TMeta>[]>;\n /** Upsert each operation by operation ID without replacing unrelated queued work. */\n setMany(operations: KeepSyncQueueOperation<TMeta>[]): Promise<void>;\n remove(operationIds: string[]): Promise<void>;\n clear(): Promise<void>;\n}\n\nexport interface SyncCapableStorageAdapter<TMeta = Record<string, unknown>> extends StorageAdapter<TMeta> {\n getSyncState(): KeepSyncState<TMeta>;\n subscribeSync(listener: () => void): () => void;\n subscribeScope?(listener: () => void): () => void;\n flushSync(): Promise<void>;\n retrySync?(): Promise<void>;\n resolveSyncConflict?(id: string, resolution: KeepSyncResolution, item?: KeepItem<TMeta>): Promise<void>;\n resolveRejectedSyncOperation?(operationId: string, resolution: \"retry\" | \"discard\"): Promise<void>;\n resolveCollectionSyncConflict?(\n id: string,\n resolution: \"local\" | \"remote\",\n collection?: KeepCollectionDefinition,\n ): Promise<void>;\n dispose?(): void;\n}\n\nexport type KeepStorageOperation = \"getAll\" | \"set\" | \"remove\" | \"clear\" | \"merge\";\n\nexport class KeepStorageError extends Error {\n readonly operation: KeepStorageOperation;\n readonly storageKey?: string;\n readonly cause?: unknown;\n\n constructor(\n message: string,\n options: {\n operation: KeepStorageOperation;\n storageKey?: string;\n cause?: unknown;\n },\n ) {\n super(message);\n this.name = \"KeepStorageError\";\n this.operation = options.operation;\n this.storageKey = options.storageKey;\n if (options.cause !== undefined) this.cause = options.cause;\n }\n}\n\nexport class KeepStorageQuotaError extends KeepStorageError {\n constructor(options: { operation: KeepStorageOperation; storageKey?: string; cause?: unknown }) {\n super(\"KeepKit storage quota was exceeded.\", options);\n this.name = \"KeepStorageQuotaError\";\n }\n}\n\nexport class KeepStorageAccessError extends KeepStorageError {\n constructor(options: { operation: KeepStorageOperation; storageKey?: string; cause?: unknown }) {\n super(\"KeepKit could not access the configured storage.\", options);\n this.name = \"KeepStorageAccessError\";\n }\n}\n\nexport class KeepStorageParseError extends KeepStorageError {\n constructor(options: { operation: KeepStorageOperation; storageKey?: string; cause?: unknown }) {\n super(\"KeepKit found invalid data in the configured storage.\", options);\n this.name = \"KeepStorageParseError\";\n }\n}\n\nexport class KeepStorageSerializationError extends KeepStorageError {\n constructor(options: { operation: KeepStorageOperation; storageKey?: string; cause?: unknown }) {\n super(\"KeepKit cannot store this value without losing data in JSON.\", options);\n this.name = \"KeepStorageSerializationError\";\n }\n}\n\nexport type KeepErrorContext = {\n action: KeepAction;\n id?: string;\n /** The mutation was persisted; only a subsequent notification failed. */\n phase?: \"notification\";\n};\n\nexport type KeepErrorHandler = (error: unknown, context: KeepErrorContext) => void;\n\nexport type KeepEventHandlers<TMeta = Record<string, unknown>> = {\n onSave?: (item: KeepItem<TMeta>) => void;\n onRemove?: (item: KeepItem<TMeta>) => void;\n onNoteUpdate?: (id: string, note?: string) => void;\n onTagsUpdate?: (id: string, tags?: string[]) => void;\n onChange?: (context: KeepChangeContext<TMeta>) => void | Promise<void>;\n onUndo?: (items: KeepItem<TMeta>[]) => void;\n onError?: KeepErrorHandler;\n};\n\nexport type KeepUndoState = {\n canUndo: boolean;\n ids: string[];\n startedAt?: number;\n expiresAt?: number;\n};\n\nexport function normalizeKeepTags(tags?: string[]): string[] | undefined {\n if (!tags) return undefined;\n const normalized = [...new Set(tags.map((tag) => tag.trim()).filter(Boolean))];\n return normalized.length > 0 ? normalized : undefined;\n}\n","import type {\n KeepCollectionDefinition,\n KeepCollectionMembership,\n KeepItem,\n StorageAdapter,\n SyncScope,\n} from \"../items/types\";\n\nexport async function persistKeepItems<TMeta>(storage: StorageAdapter<TMeta>, items: KeepItem<TMeta>[]): Promise<void> {\n if (storage.setMany) {\n await storage.setMany(items);\n return;\n }\n for (const item of items) await storage.set(item);\n}\n\nexport async function removeKeepItems<TMeta>(storage: StorageAdapter<TMeta>, ids: string[]): Promise<void> {\n if (storage.removeMany) {\n await storage.removeMany(ids);\n return;\n }\n for (const id of ids) await storage.remove(id);\n}\n\nexport function mergeKeepItemLists<TMeta>(\n remoteItems: KeepItem<TMeta>[],\n localItems: KeepItem<TMeta>[],\n): KeepItem<TMeta>[] {\n const byScopeAndId = new Map(remoteItems.map((item) => [itemStorageKey(item), item]));\n for (const localItem of localItems) {\n const key = itemStorageKey(localItem);\n const remoteItem = byScopeAndId.get(key);\n if (!remoteItem) {\n byScopeAndId.set(key, localItem);\n continue;\n }\n const content = localItem.updatedAt > remoteItem.updatedAt ? localItem : remoteItem;\n const lastOpenedAt =\n remoteItem.lastOpenedAt === undefined\n ? localItem.lastOpenedAt\n : localItem.lastOpenedAt === undefined\n ? remoteItem.lastOpenedAt\n : Math.max(remoteItem.lastOpenedAt, localItem.lastOpenedAt);\n byScopeAndId.set(key, lastOpenedAt === undefined ? content : { ...content, lastOpenedAt });\n }\n return [...byScopeAndId.values()].sort((a, b) => b.updatedAt - a.updatedAt);\n}\n\nfunction itemStorageKey(item: Pick<KeepItem, \"id\" | \"scope\">): string {\n return JSON.stringify([item.scope?.tenantId ?? null, item.scope?.userId ?? null, item.id]);\n}\n\nexport function isKeepItem(value: unknown): value is KeepItem {\n if (!isRecord(value)) return false;\n return (\n typeof value.id === \"string\" &&\n typeof value.savedAt === \"number\" &&\n Number.isFinite(value.savedAt) &&\n typeof value.updatedAt === \"number\" &&\n Number.isFinite(value.updatedAt) &&\n \"meta\" in value &&\n (value.order === undefined || (typeof value.order === \"number\" && Number.isFinite(value.order))) &&\n (value.archived === undefined || typeof value.archived === \"boolean\") &&\n (value.pinned === undefined || typeof value.pinned === \"boolean\") &&\n (value.lastOpenedAt === undefined ||\n (typeof value.lastOpenedAt === \"number\" && Number.isFinite(value.lastOpenedAt))) &&\n (value.collectionId === undefined || typeof value.collectionId === \"string\") &&\n (value.targetType === undefined || typeof value.targetType === \"string\") &&\n (value.note === undefined || typeof value.note === \"string\") &&\n (value.schemaVersion === undefined ||\n (typeof value.schemaVersion === \"number\" && Number.isFinite(value.schemaVersion))) &&\n (value.revision === undefined || typeof value.revision === \"string\") &&\n (value.metaUpdatedAt === undefined ||\n (typeof value.metaUpdatedAt === \"number\" && Number.isFinite(value.metaUpdatedAt))) &&\n (value.status === undefined ||\n value.status === \"available\" ||\n value.status === \"expired\" ||\n value.status === \"removed\" ||\n value.status === \"deleted\" ||\n value.status === \"private\" ||\n value.status === \"unknown\") &&\n (value.statusReason === undefined || typeof value.statusReason === \"string\") &&\n (value.scope === undefined || isSyncScope(value.scope)) &&\n (value.tags === undefined || (Array.isArray(value.tags) && value.tags.every((tag) => typeof tag === \"string\")))\n );\n}\n\nexport function isKeepItemArray(value: unknown): value is KeepItem[] {\n return Array.isArray(value) && value.every(isKeepItem);\n}\n\nexport function isKeepCollectionDefinition(value: unknown): value is KeepCollectionDefinition {\n return (\n isRecord(value) &&\n typeof value.id === \"string\" &&\n value.id.trim().length > 0 &&\n typeof value.name === \"string\" &&\n value.name.trim().length > 0 &&\n (value.revision === undefined || typeof value.revision === \"string\") &&\n (value.updatedAt === undefined || (typeof value.updatedAt === \"number\" && Number.isFinite(value.updatedAt))) &&\n (value.scope === undefined || isSyncScope(value.scope))\n );\n}\n\nexport function isKeepCollectionMembership(value: unknown): value is KeepCollectionMembership {\n return (\n isRecord(value) &&\n typeof value.collectionId === \"string\" &&\n value.collectionId.trim().length > 0 &&\n typeof value.itemId === \"string\" &&\n value.itemId.trim().length > 0 &&\n typeof value.order === \"number\" &&\n Number.isInteger(value.order) &&\n Number.isFinite(value.order) &&\n value.order >= 0 &&\n (value.scope === undefined || isSyncScope(value.scope))\n );\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isSyncScope(value: unknown): value is SyncScope {\n return (\n isRecord(value) &&\n (value.userId === undefined || typeof value.userId === \"string\") &&\n (value.tenantId === undefined || typeof value.tenantId === \"string\")\n );\n}\n","import type { KeepStorageRecovery } from \"../../storage/recovery-journal\";\nimport type {\n KeepCollectionDefinition,\n KeepCollectionMembership,\n KeepItem,\n KeepSyncQueueOperation,\n StorageAdapter,\n SyncQueueAdapter,\n SyncScope,\n} from \"../items/types\";\nimport { mergeKeepItemLists } from \"./helpers\";\n\nexport type KeepScope = SyncScope;\n\n/** Return a stable, human-readable namespace for browser storage and queues. */\nexport function getKeepScopeKey(scope?: KeepScope): string {\n if (scope?.userId === undefined && scope?.tenantId === undefined) return \"\";\n return `:${encodeURIComponent(scope.tenantId ?? \"_\")}:${encodeURIComponent(scope.userId ?? \"_\")}`;\n}\n\nexport function isSameKeepScope(left: KeepScope | undefined, right: KeepScope | undefined): boolean {\n return left?.userId === right?.userId && left?.tenantId === right?.tenantId;\n}\n\n/**\n * Adds an isolated user/tenant view over any StorageAdapter. Writes preserve\n * records belonging to other scopes, which makes account switching safe even\n * when applications share one physical localStorage key.\n */\nexport class ScopedStorageAdapter<TMeta = Record<string, unknown>> implements StorageAdapter<TMeta> {\n readonly scope?: KeepScope;\n readonly storageKey?: string;\n readonly recovery?: KeepStorageRecovery<TMeta>;\n readonly getCollections?: () => Promise<KeepCollectionDefinition[]>;\n readonly setCollection?: (collection: KeepCollectionDefinition) => Promise<void>;\n readonly removeCollection?: (id: string, scope?: SyncScope) => Promise<void>;\n readonly getCollectionMemberships?: () => Promise<KeepCollectionMembership[]>;\n readonly setCollectionMembership?: (membership: KeepCollectionMembership) => Promise<void>;\n readonly removeCollectionMembership?: (collectionId: string, itemId: string, scope?: SyncScope) => Promise<void>;\n private readonly base: StorageAdapter<TMeta>;\n\n constructor(base: StorageAdapter<TMeta>, scope?: KeepScope) {\n this.base = base;\n this.scope = scope;\n if (base.recovery && isSameKeepScope(base.scope, scope)) this.recovery = base.recovery;\n const scopeKey = getKeepScopeKey(scope);\n this.storageKey = base.storageKey\n ? base.storageKey.endsWith(scopeKey) && scopeKey\n ? base.storageKey\n : `${base.storageKey}${scopeKey}`\n : undefined;\n if (base.getCollections && base.setCollection && base.removeCollection) {\n const getCollections = base.getCollections.bind(base);\n const setCollection = base.setCollection.bind(base);\n const removeCollection = base.removeCollection.bind(base);\n this.getCollections = async () => {\n const collections = await getCollections();\n return this.scope\n ? collections.filter((collection) => isSameKeepScope(collection.scope, this.scope))\n : collections;\n };\n this.setCollection = async (collection) => {\n this.assertWritableScope();\n await setCollection({ ...collection, ...(this.scope ? { scope: this.scope } : {}) });\n };\n this.removeCollection = async (id) => {\n this.assertWritableScope();\n await removeCollection(id, this.scope);\n };\n }\n if (base.getCollectionMemberships && base.setCollectionMembership && base.removeCollectionMembership) {\n const getMemberships = base.getCollectionMemberships.bind(base);\n const setMembership = base.setCollectionMembership.bind(base);\n const removeMembership = base.removeCollectionMembership.bind(base);\n this.getCollectionMemberships = async () => {\n const memberships = await getMemberships();\n return this.scope\n ? memberships.filter((membership) => isSameKeepScope(membership.scope, this.scope))\n : memberships;\n };\n this.setCollectionMembership = async (membership) => {\n this.assertWritableScope();\n await setMembership({ ...membership, ...(this.scope ? { scope: this.scope } : {}) });\n };\n this.removeCollectionMembership = async (collectionId, itemId) => {\n this.assertWritableScope();\n await removeMembership(collectionId, itemId, this.scope);\n };\n }\n }\n\n async getAll(): Promise<KeepItem<TMeta>[]> {\n const items = await this.base.getAll();\n return this.scope ? items.filter((item) => isSameKeepScope(item.scope, this.scope)) : items;\n }\n\n async set(item: KeepItem<TMeta>): Promise<void> {\n await this.setMany([item]);\n }\n\n async setMany(items: KeepItem<TMeta>[]): Promise<void> {\n this.assertWritableScope();\n const scoped = items.map((item) => ({ ...item, ...(this.scope ? { scope: this.scope } : {}) }));\n if (this.base.setMany) await this.base.setMany(scoped);\n else for (const item of scoped) await this.base.set(item);\n }\n\n async remove(id: string): Promise<void> {\n this.assertWritableScope();\n await this.base.remove(id, this.scope);\n await this.removeMembershipsForItems([id]);\n }\n\n async removeMany(ids: string[]): Promise<void> {\n this.assertWritableScope();\n const uniqueIds = [...new Set(ids)];\n if (this.base.removeMany) await this.base.removeMany(uniqueIds, this.scope);\n else for (const id of uniqueIds) await this.base.remove(id, this.scope);\n await this.removeMembershipsForItems(uniqueIds);\n }\n\n async clear(): Promise<void> {\n this.assertWritableScope();\n const removedIds = (await this.getAll()).map((item) => item.id);\n await this.removeMany(removedIds);\n await this.clearMembershipsForScope();\n }\n\n async merge(items: KeepItem<TMeta>[]): Promise<KeepItem<TMeta>[]> {\n this.assertWritableScope();\n const scopedItems = items.map((item) => ({ ...item, ...(this.scope ? { scope: this.scope } : {}) }));\n const merged = mergeKeepItemLists(await this.getAll(), scopedItems);\n await this.setMany(merged);\n return merged;\n }\n\n subscribe(listener: () => void): () => void {\n return this.base.subscribe?.(listener) ?? (() => undefined);\n }\n\n private assertWritableScope(): void {\n if (this.base.scope && this.scope && !isSameKeepScope(this.base.scope, this.scope))\n throw new Error(\"Cannot write through an adapter bound to a different storage scope.\");\n }\n\n private async removeMembershipsForItems(ids: string[]): Promise<void> {\n if (!this.base.getCollectionMemberships || !this.base.removeCollectionMembership || ids.length === 0) return;\n const removedIds = new Set(ids);\n const memberships = await this.base.getCollectionMemberships();\n for (const membership of memberships) {\n if (removedIds.has(membership.itemId) && isSameKeepScope(membership.scope, this.scope)) {\n await this.base.removeCollectionMembership(membership.collectionId, membership.itemId, this.scope);\n }\n }\n }\n\n private async clearMembershipsForScope(): Promise<void> {\n if (!this.base.getCollectionMemberships || !this.base.removeCollectionMembership) return;\n const memberships = await this.base.getCollectionMemberships();\n for (const membership of memberships) {\n if (isSameKeepScope(membership.scope, this.scope)) {\n await this.base.removeCollectionMembership(membership.collectionId, membership.itemId, this.scope);\n }\n }\n }\n}\n\nexport function createScopedStorageAdapter<TMeta = Record<string, unknown>>(\n base: StorageAdapter<TMeta>,\n scope?: KeepScope,\n): ScopedStorageAdapter<TMeta> {\n return new ScopedStorageAdapter(base, scope);\n}\n\n/** Scope a durable synchronization queue so a user switch cannot flush another user's operations. */\nexport class ScopedSyncQueueAdapter<TMeta = Record<string, unknown>> implements SyncQueueAdapter<TMeta> {\n private readonly base: SyncQueueAdapter<TMeta>;\n private readonly scope?: KeepScope;\n\n constructor(base: SyncQueueAdapter<TMeta>, scope?: KeepScope) {\n this.base = base;\n this.scope = scope;\n }\n\n async getAll(): Promise<KeepSyncQueueOperation<TMeta>[]> {\n const operations = await this.base.getAll();\n return this.scope ? operations.filter((operation) => isSameKeepScope(operation.scope, this.scope)) : operations;\n }\n\n async setMany(operations: KeepSyncQueueOperation<TMeta>[]): Promise<void> {\n const current = await this.base.getAll();\n const scoped = operations.map((operation) => ({ ...operation, ...(this.scope ? { scope: this.scope } : {}) }));\n const ids = new Set(scoped.map((operation) => operation.operationId));\n await this.base.setMany([\n ...current.filter(\n (operation) => !ids.has(operation.operationId) || !isSameKeepScope(operation.scope, this.scope),\n ),\n ...scoped,\n ]);\n }\n\n async remove(operationIds: string[]): Promise<void> {\n const ids = new Set(operationIds);\n const scopedIds = (await this.base.getAll())\n .filter((operation) => ids.has(operation.operationId) && isSameKeepScope(operation.scope, this.scope))\n .map((operation) => operation.operationId);\n await this.base.remove(scopedIds);\n }\n\n async clear(): Promise<void> {\n const operationIds = (await this.base.getAll())\n .filter((operation) => isSameKeepScope(operation.scope, this.scope))\n .map((operation) => operation.operationId);\n await this.base.remove(operationIds);\n }\n}\n","import { type KeepStorageOperation, KeepStorageSerializationError } from \"../items/types\";\n\nconst optionalFields = new Set([\n \"scope\",\n \"userId\",\n \"tenantId\",\n \"order\",\n \"archived\",\n \"pinned\",\n \"lastOpenedAt\",\n \"collectionId\",\n \"targetType\",\n \"note\",\n \"tags\",\n \"schemaVersion\",\n \"revision\",\n \"metaUpdatedAt\",\n \"status\",\n \"statusReason\",\n \"updatedAt\",\n \"snapshot\",\n \"archives\",\n \"backups\",\n \"scopes\",\n \"initialized\",\n \"capturedAt\",\n \"issue\",\n \"item\",\n \"collection\",\n \"membership\",\n \"entity\",\n \"baseRevision\",\n \"attempts\",\n]);\n\n/** Reject values whose JSON representation would silently change or discard data. */\nexport function serializeKeepStorage(\n value: unknown,\n options: { operation: KeepStorageOperation; storageKey?: string },\n): string {\n const ancestors = new Set<object>();\n const visit = (entry: unknown, inMeta: boolean): unknown => {\n if (entry === null || typeof entry === \"string\" || typeof entry === \"boolean\") return entry;\n if (typeof entry === \"number\" && Number.isFinite(entry)) return entry;\n if (typeof entry !== \"object\" || entry === null) throw new Error(\"The value cannot be represented in JSON.\");\n if (ancestors.has(entry)) throw new Error(\"Circular references cannot be represented in JSON.\");\n ancestors.add(entry);\n try {\n if (Array.isArray(entry)) {\n const result: unknown[] = [];\n for (let index = 0; index < entry.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(entry, index);\n if (!descriptor) throw new Error(\"Sparse arrays cannot be represented in JSON.\");\n if (!(\"value\" in descriptor)) throw new Error(\"Accessors cannot be represented in JSON.\");\n result.push(visit(descriptor.value, inMeta));\n }\n if (\n Reflect.ownKeys(entry).some(\n (key) =>\n typeof key !== \"string\" ||\n (key !== \"length\" && (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= entry.length)),\n )\n )\n throw new Error(\"Extra array properties cannot be represented in JSON.\");\n return result;\n }\n const prototype = Object.getPrototypeOf(entry);\n if (prototype !== Object.prototype && prototype !== null)\n throw new Error(\"Only plain JSON objects are supported.\");\n if (Reflect.ownKeys(entry).some((key) => typeof key === \"symbol\"))\n throw new Error(\"Symbol keys are unsupported.\");\n if (Object.getOwnPropertyNames(entry).some((key) => !Object.getOwnPropertyDescriptor(entry, key)?.enumerable))\n throw new Error(\"Non-enumerable properties cannot be represented in JSON.\");\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(entry).sort()) {\n const descriptor = Object.getOwnPropertyDescriptor(entry, key);\n if (!descriptor || !(\"value\" in descriptor)) throw new Error(\"Accessors cannot be represented in JSON.\");\n const field: unknown = descriptor.value;\n if (field === undefined && !inMeta && optionalFields.has(key)) continue;\n Object.defineProperty(result, key, { value: visit(field, inMeta || key === \"meta\"), enumerable: true });\n }\n return result;\n } finally {\n ancestors.delete(entry);\n }\n };\n try {\n return JSON.stringify(visit(value, false));\n } catch (cause) {\n throw new KeepStorageSerializationError({ ...options, cause });\n }\n}\n","import type { KeepCollectionMembership, KeepItem, StorageAdapter, SyncScope } from \"../items/types\";\nimport { mergeKeepItemLists } from \"./helpers\";\n\n/** Merge anonymous local items into a signed-in or remote adapter. */\nexport async function mergeKeepItems<TMeta>(\n localItems: KeepItem<TMeta>[],\n target: StorageAdapter<TMeta>,\n): Promise<KeepItem<TMeta>[]> {\n if (target.merge) return target.merge(localItems);\n\n const merged = mergeKeepItemLists(await target.getAll(), localItems);\n await Promise.all(merged.map((item) => target.set(item)));\n return merged;\n}\n\n/** Read anonymous items, merge them into the target, then clear the source. */\nexport async function migrateKeepItems<TMeta>(\n source: StorageAdapter<TMeta>,\n target: StorageAdapter<TMeta>,\n): Promise<KeepItem<TMeta>[]> {\n const localItems = await source.getAll();\n const merged = await mergeKeepItems(localItems, target);\n await source.clear();\n return merged;\n}\n\nexport type LegacyCollectionMigrationResult = {\n migrated: number;\n skipped: number;\n missingCollectionIds: string[];\n};\n\n/** Move legacy single-collection item fields into course-specific memberships once. */\nexport async function migrateLegacyCollectionMemberships<TMeta>(\n storage: StorageAdapter<TMeta>,\n): Promise<LegacyCollectionMigrationResult> {\n if (!storage.getCollectionMemberships || !storage.setCollectionMembership) {\n throw new TypeError(\"The storage adapter does not support collection memberships.\");\n }\n\n const [items, memberships, collections] = await Promise.all([\n storage.getAll(),\n storage.getCollectionMemberships(),\n storage.getCollections?.() ?? Promise.resolve([]),\n ]);\n const existing = new Set(memberships.map(membershipKey));\n const collectionIds = new Set(collections.map((collection) => collectionKey(collection.id, collection.scope)));\n const missingCollectionIds = new Set<string>();\n let migrated = 0;\n let skipped = 0;\n\n for (const item of items) {\n if (!item.collectionId) continue;\n const membership: KeepCollectionMembership = {\n collectionId: item.collectionId,\n itemId: item.id,\n order: item.order ?? 0,\n ...(item.scope ? { scope: item.scope } : {}),\n };\n const key = membershipKey(membership);\n if (!collectionIds.has(collectionKey(item.collectionId, item.scope))) {\n missingCollectionIds.add(item.collectionId);\n }\n if (existing.has(key)) {\n skipped += 1;\n const { collectionId: _legacyCollectionId, ...migratedItem } = item;\n await storage.set(migratedItem);\n continue;\n }\n await storage.setCollectionMembership(membership);\n existing.add(key);\n migrated += 1;\n const { collectionId: _legacyCollectionId, ...migratedItem } = item;\n await storage.set(migratedItem);\n }\n\n return { migrated, skipped, missingCollectionIds: [...missingCollectionIds] };\n}\n\nfunction membershipKey(membership: KeepCollectionMembership): string {\n return `${membership.scope?.tenantId ?? \"\"}\\u0000${membership.scope?.userId ?? \"\"}\\u0000${membership.collectionId}\\u0000${membership.itemId}`;\n}\n\nfunction collectionKey(collectionId: string, scope?: SyncScope): string {\n return `${scope?.tenantId ?? \"\"}\\u0000${scope?.userId ?? \"\"}\\u0000${collectionId}`;\n}\n","import type {\n KeepCollectionDefinition,\n KeepCollectionMembership,\n KeepInvalidItemPolicy,\n KeepItem,\n KeepSchema,\n StorageAdapter,\n SyncScope,\n} from \"../items/types\";\nimport { isKeepCollectionDefinition, isKeepCollectionMembership, isKeepItem, isRecord } from \"./helpers\";\nimport { mergeKeepItems } from \"./migration\";\nimport { validateKeepItem } from \"./schema\";\nimport { serializeKeepStorage } from \"./serialization\";\n\nexport const KEEP_BACKUP_FORMAT = \"keepkit\";\nexport const KEEP_BACKUP_VERSION = 2;\n\nexport type KeepBackupV1<TMeta = Record<string, unknown>> = {\n format: typeof KEEP_BACKUP_FORMAT;\n version: 1;\n exportedAt: number;\n items: KeepItem<TMeta>[];\n};\n\nexport type KeepBackupV2<TMeta = Record<string, unknown>> = {\n format: typeof KEEP_BACKUP_FORMAT;\n version: typeof KEEP_BACKUP_VERSION;\n exportedAt: number;\n items: KeepItem<TMeta>[];\n collections: KeepCollectionDefinition[];\n memberships: KeepCollectionMembership[];\n /** Scopes represented by the records in this backup. Omitted by early v2 backups. */\n scopes?: SyncScope[];\n};\n\nexport type KeepBackup<TMeta = Record<string, unknown>> = KeepBackupV1<TMeta> | KeepBackupV2<TMeta>;\n\ntype ParsedKeepBackup<TMeta> = Omit<KeepBackupV2<TMeta>, \"version\"> & { version: 1 | typeof KEEP_BACKUP_VERSION };\n\nexport type KeepBackupSummary = {\n version: 1 | typeof KEEP_BACKUP_VERSION;\n exportedAt: number;\n itemCount: number;\n collectionCount: number;\n membershipCount: number;\n scopes: SyncScope[];\n};\n\n/** Validate a serialized backup and return its record counts without modifying storage. */\nexport function inspectKeepBackup<TMeta = Record<string, unknown>>(\n data: string | KeepBackup<TMeta>,\n): KeepBackupSummary {\n const backup = parseBackup<TMeta>(data);\n return {\n version: backup.version,\n exportedAt: backup.exportedAt,\n itemCount: backup.items.length,\n collectionCount: backup.collections.length,\n membershipCount: backup.memberships.length,\n scopes: collectScopes(backup.items, backup.collections, backup.memberships, backup.scopes),\n };\n}\n\nexport type ImportItemsOptions<TMeta = unknown> = {\n mode?: \"replace\" | \"merge\";\n schema?: KeepSchema<TMeta>;\n invalidItemPolicy?: KeepInvalidItemPolicy;\n onInvalidItem?: (error: unknown, item: KeepItem<unknown>) => void;\n /** Resolves a same-ID collection name collision when merging. Defaults to the backup name. */\n collectionNameConflict?: \"backup\" | \"existing\";\n};\n\nexport type KeepBackupDataType = \"items\" | \"collections\" | \"memberships\";\nexport type KeepBackupAppliedCounts = { items: number; collections: number; memberships: number };\n\nexport type ImportItemsResult<TMeta = Record<string, unknown>> = {\n mode: \"replace\" | \"merge\";\n imported: number;\n failed: number;\n total: number;\n items: KeepItem<TMeta>[];\n applied: KeepBackupAppliedCounts;\n missingCollectionIds: string[];\n includedData: KeepBackupDataType[];\n scopes: SyncScope[];\n};\n\nexport class KeepBackupParseError extends Error {\n readonly cause?: unknown;\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"KeepBackupParseError\";\n if (options?.cause !== undefined) this.cause = options.cause;\n }\n}\n\nexport class KeepBackupImportError extends Error {\n readonly mode: \"replace\" | \"merge\";\n readonly imported: number;\n readonly failed: number;\n readonly applied: KeepBackupAppliedCounts;\n readonly failedStage: \"items\" | \"collections\" | \"memberships\" | \"clear\" | \"validation\";\n readonly cause?: unknown;\n\n constructor(\n message: string,\n options: {\n mode: \"replace\" | \"merge\";\n imported: number;\n failed: number;\n applied?: KeepBackupAppliedCounts;\n failedStage?: \"items\" | \"collections\" | \"memberships\" | \"clear\" | \"validation\";\n cause?: unknown;\n },\n ) {\n super(message);\n this.name = \"KeepBackupImportError\";\n this.mode = options.mode;\n this.imported = options.imported;\n this.failed = options.failed;\n this.applied = options.applied ?? { items: options.imported, collections: 0, memberships: 0 };\n this.failedStage = options.failedStage ?? \"items\";\n if (options.cause !== undefined) this.cause = options.cause;\n }\n}\n\n/** Serialize all adapter data into a versioned JSON backup. */\nexport async function exportItems<TMeta>(adapter: StorageAdapter<TMeta>): Promise<string> {\n const items = await adapter.getAll();\n const collections = (await adapter.getCollections?.()) ?? [];\n const memberships = (await adapter.getCollectionMemberships?.()) ?? [];\n const backup: KeepBackupV2<TMeta> = {\n format: KEEP_BACKUP_FORMAT,\n version: KEEP_BACKUP_VERSION,\n exportedAt: Date.now(),\n items,\n collections,\n memberships,\n scopes: collectScopes(items, collections, memberships, adapter.scope ? [adapter.scope] : []),\n };\n const serialized = serializeKeepStorage(backup, { operation: \"getAll\", storageKey: adapter.storageKey });\n const json: unknown = JSON.parse(serialized);\n return JSON.stringify(json, null, 2);\n}\n\n/** Format saved items as a portable Markdown list for notes, docs, or sharing. */\nexport function formatItemsAsMarkdown<TMeta = Record<string, unknown>>(\n items: readonly KeepItem<TMeta>[],\n options: { collectionLabels?: Record<string, string> } = {},\n): string {\n if (items.length === 0) return \"\";\n return items\n .map((item) => {\n const meta: Record<string, unknown> = isRecord(item.meta) ? item.meta : {};\n const rawTitle = typeof meta.title === \"string\" && meta.title.trim() ? meta.title.trim() : item.id;\n const rawUrl = typeof meta.url === \"string\" && meta.url.trim() ? meta.url.trim() : undefined;\n const link = rawUrl ? `[${rawTitle}](${rawUrl})` : rawTitle;\n const details: string[] = [];\n if (item.collectionId) {\n details.push(`Collection: ${options.collectionLabels?.[item.collectionId] ?? item.collectionId}`);\n }\n if (item.tags && item.tags.length > 0) {\n details.push(`Tags: ${item.tags.map((tag) => `#${tag}`).join(\" \")}`);\n }\n if (item.note?.trim()) {\n details.push(item.note.trim());\n }\n return details.length > 0 ? `- ${link} — ${details.join(\" | \")}` : `- ${link}`;\n })\n .join(\"\\n\");\n}\n\n/** Validate and restore a backup, either replacing or merging existing data. */\nexport async function importItems<TMeta>(\n adapter: StorageAdapter<TMeta>,\n data: string | KeepBackup<TMeta>,\n options: ImportItemsOptions<TMeta> = {},\n): Promise<ImportItemsResult<TMeta>> {\n const backup = parseBackup<TMeta>(data);\n const mode = options.mode ?? \"merge\";\n const scopes = collectScopes(backup.items, backup.collections, backup.memberships, backup.scopes);\n if (adapter.scope && scopes.some((scope) => !sameScope(scope, adapter.scope))) {\n throw new KeepBackupImportError(\"The backup contains data outside the active storage scope.\", {\n mode,\n imported: 0,\n failed: backup.items.length + backup.collections.length + backup.memberships.length,\n applied: { items: 0, collections: 0, memberships: 0 },\n failedStage: \"validation\",\n });\n }\n if (\n (backup.collections.length > 0 &&\n (!adapter.getCollections || !adapter.setCollection || !adapter.removeCollection)) ||\n (backup.memberships.length > 0 &&\n (!adapter.getCollectionMemberships || !adapter.setCollectionMembership || !adapter.removeCollectionMembership))\n ) {\n throw new KeepBackupImportError(\"The storage adapter cannot restore collection data from this backup.\", {\n mode,\n imported: 0,\n failed: backup.items.length + backup.collections.length + backup.memberships.length,\n applied: { items: 0, collections: 0, memberships: 0 },\n failedStage: \"validation\",\n });\n }\n const validItems: KeepItem<TMeta>[] = [];\n let failed = 0;\n for (const item of backup.items) {\n if (!options.schema) {\n validItems.push(item);\n continue;\n }\n try {\n validItems.push(await validateKeepItem(item, options.schema));\n } catch (cause) {\n options.onInvalidItem?.(cause, item);\n if ((options.invalidItemPolicy ?? \"error\") === \"drop\") {\n failed += 1;\n continue;\n }\n throw cause;\n }\n }\n const applied: KeepBackupAppliedCounts = { items: 0, collections: 0, memberships: 0 };\n const missingCollectionIds =\n backup.version === 1\n ? [...new Set(backup.items.flatMap((item) => (item.collectionId ? [item.collectionId] : [])))]\n : [];\n\n try {\n if (mode === \"replace\") {\n await adapter.clear();\n await restoreCollections(adapter, [], \"replace\", \"backup\", applied);\n await restoreMemberships(adapter, [], \"replace\", applied);\n }\n } catch (cause) {\n throw new KeepBackupImportError(\"KeepKit could not clear the data being replaced.\", {\n mode,\n imported: applied.items,\n failed: validItems.length + failed,\n applied,\n failedStage: \"clear\",\n cause,\n });\n }\n\n for (const item of validItems) {\n try {\n if (mode === \"merge\") await mergeKeepItems([item], adapter);\n else await adapter.set(item);\n applied.items += 1;\n } catch (cause) {\n throw new KeepBackupImportError(`KeepKit could not restore item ${item.id}.`, {\n mode,\n imported: applied.items,\n failed: validItems.length + failed - applied.items,\n applied,\n failedStage: \"items\",\n cause,\n });\n }\n }\n\n try {\n await restoreCollections(adapter, backup.collections, mode, options.collectionNameConflict ?? \"backup\", applied);\n } catch (cause) {\n throw new KeepBackupImportError(\"KeepKit could not restore collection definitions.\", {\n mode,\n imported: applied.items,\n failed: validItems.length + failed - applied.items,\n applied,\n failedStage: \"collections\",\n cause,\n });\n }\n try {\n await restoreMemberships(adapter, backup.memberships, mode, applied);\n } catch (cause) {\n throw new KeepBackupImportError(\"KeepKit could not restore collection memberships.\", {\n mode,\n imported: applied.items,\n failed: validItems.length + failed - applied.items,\n applied,\n failedStage: \"memberships\",\n cause,\n });\n }\n let items: KeepItem<TMeta>[];\n try {\n items = await adapter.getAll();\n } catch (cause) {\n throw new KeepBackupImportError(\"KeepKit restored the backup but could not read the resulting items.\", {\n mode,\n imported: applied.items,\n failed: failed,\n applied,\n failedStage: \"items\",\n cause,\n });\n }\n\n return {\n mode,\n imported: applied.items,\n failed,\n total: items.length,\n items,\n applied,\n missingCollectionIds,\n includedData: backup.version === 1 ? [\"items\"] : [\"items\", \"collections\", \"memberships\"],\n scopes,\n };\n}\n\nfunction parseBackup<TMeta>(data: string | KeepBackup<TMeta>): ParsedKeepBackup<TMeta> {\n let value: unknown = data;\n if (typeof data === \"string\") {\n try {\n value = JSON.parse(data);\n } catch (cause) {\n throw new KeepBackupParseError(\"KeepKit backup is not valid JSON.\", { cause });\n }\n }\n\n if (!isRecord(value)) throw new KeepBackupParseError(\"KeepKit backup must be an object.\");\n if (value.format !== KEEP_BACKUP_FORMAT || (value.version !== 1 && value.version !== KEEP_BACKUP_VERSION)) {\n throw new KeepBackupParseError(\"KeepKit backup format or version is unsupported.\");\n }\n if (typeof value.exportedAt !== \"number\" || !Number.isFinite(value.exportedAt)) {\n throw new KeepBackupParseError(\"KeepKit backup has an invalid export timestamp.\");\n }\n if (!Array.isArray(value.items) || !value.items.every(isKeepItem)) {\n throw new KeepBackupParseError(\"KeepKit backup contains invalid items.\");\n }\n if (value.version === 1) {\n return {\n format: KEEP_BACKUP_FORMAT,\n version: 1,\n exportedAt: value.exportedAt,\n items: value.items as KeepItem<TMeta>[],\n collections: [],\n memberships: [],\n scopes: [],\n };\n }\n if (\n !Array.isArray(value.collections) ||\n !value.collections.every(isKeepCollectionDefinition) ||\n !Array.isArray(value.memberships) ||\n !value.memberships.every(isKeepCollectionMembership)\n ) {\n throw new KeepBackupParseError(\"KeepKit backup contains invalid collection data.\");\n }\n if (value.scopes !== undefined && (!Array.isArray(value.scopes) || !value.scopes.every(isSyncScope))) {\n throw new KeepBackupParseError(\"KeepKit backup contains invalid scope data.\");\n }\n return value as ParsedKeepBackup<TMeta>;\n}\n\nfunction collectScopes(\n items: KeepItem<unknown>[],\n collections: KeepCollectionDefinition[],\n memberships: KeepCollectionMembership[],\n declaredScopes: SyncScope[] = [],\n): SyncScope[] {\n const scopes = [\n ...declaredScopes,\n ...[...items, ...collections, ...memberships].flatMap((record) => (record.scope ? [record.scope] : [])),\n ].filter((scope, index, all) => all.findIndex((entry) => sameScope(entry, scope)) === index);\n return scopes.map((scope) => ({ ...scope }));\n}\n\nfunction sameScope(left: SyncScope, right: SyncScope | undefined): boolean {\n return left.userId === right?.userId && left.tenantId === right?.tenantId;\n}\n\nfunction isSyncScope(value: unknown): value is SyncScope {\n return (\n isRecord(value) &&\n (value.userId === undefined || typeof value.userId === \"string\") &&\n (value.tenantId === undefined || typeof value.tenantId === \"string\")\n );\n}\n\nasync function restoreCollections<TMeta>(\n adapter: StorageAdapter<TMeta>,\n collections: KeepCollectionDefinition[],\n mode: \"merge\" | \"replace\",\n conflict: \"backup\" | \"existing\",\n applied: KeepBackupAppliedCounts,\n): Promise<void> {\n if (!adapter.getCollections || !adapter.setCollection || !adapter.removeCollection) return;\n const existing = await adapter.getCollections();\n if (mode === \"replace\") {\n for (const collection of existing) await adapter.removeCollection(collection.id, collection.scope);\n }\n for (const collection of collections) {\n const current = existing.find(\n (entry) => entry.id === collection.id && sameScope(entry.scope ?? {}, collection.scope),\n );\n const value =\n mode === \"merge\" && conflict === \"existing\" && current ? { ...collection, name: current.name } : collection;\n await adapter.setCollection(value);\n applied.collections += 1;\n }\n}\n\nasync function restoreMemberships<TMeta>(\n adapter: StorageAdapter<TMeta>,\n memberships: KeepCollectionMembership[],\n mode: \"merge\" | \"replace\",\n applied: KeepBackupAppliedCounts,\n): Promise<void> {\n if (!adapter.getCollectionMemberships || !adapter.setCollectionMembership || !adapter.removeCollectionMembership)\n return;\n if (mode === \"replace\") {\n const current = await adapter.getCollectionMemberships();\n for (const membership of current) {\n await adapter.removeCollectionMembership(membership.collectionId, membership.itemId, membership.scope);\n }\n }\n for (const membership of memberships) {\n await adapter.setCollectionMembership(membership);\n applied.memberships += 1;\n }\n}\n","const writeQueues = new Map<string, Promise<unknown>>();\n\n/** Serialize same-key writes in one realm and, where available, across browser tabs. */\nexport function withLocalStorageWriteLock<T>(\n key: string,\n operation: () => Promise<T>,\n lockUnavailableError: Error,\n): Promise<T> {\n const lockName = `keepkit:local-storage:${key}`;\n if (typeof navigator !== \"undefined\" && navigator.locks) {\n return navigator.locks.request(lockName, operation);\n }\n if (typeof window !== \"undefined\") return Promise.reject(lockUnavailableError);\n\n const previous = writeQueues.get(lockName) ?? Promise.resolve();\n const next = previous.catch(() => undefined).then(operation);\n writeQueues.set(lockName, next);\n return next.finally(() => {\n if (writeQueues.get(lockName) === next) writeQueues.delete(lockName);\n });\n}\n","import {\n type KeepCollectionDefinition,\n type KeepCollectionMembership,\n type KeepItem,\n KeepStorageAccessError,\n KeepStorageParseError,\n KeepStorageQuotaError,\n type StorageAdapter,\n} from \"../features/items/types\";\nimport { KEEP_BACKUP_FORMAT, KEEP_BACKUP_VERSION, type KeepBackupV2 } from \"../features/persistence/backup\";\nimport {\n isKeepCollectionDefinition,\n isKeepCollectionMembership,\n isKeepItem,\n isKeepItemArray,\n isRecord,\n mergeKeepItemLists,\n persistKeepItems,\n} from \"../features/persistence/helpers\";\nimport { isSameKeepScope, type KeepScope } from \"../features/persistence/scope\";\nimport { serializeKeepStorage } from \"../features/persistence/serialization\";\nimport { withLocalStorageWriteLock } from \"../features/persistence/write-lock\";\n\nexport type FallbackRecoveryOperation<TMeta = Record<string, unknown>> =\n | { type: \"setItems\"; items: KeepItem<TMeta>[] }\n | { type: \"removeItems\"; ids: string[]; scope?: KeepScope }\n | { type: \"clearItems\" }\n | { type: \"setCollection\"; collection: KeepCollectionDefinition }\n | { type: \"removeCollection\"; id: string; scope?: KeepScope }\n | { type: \"setMembership\"; membership: KeepCollectionMembership }\n | { type: \"removeMembership\"; collectionId: string; itemId: string; scope?: KeepScope };\n\nexport type FallbackRecoverySnapshot<TMeta = Record<string, unknown>> = {\n items: KeepItem<TMeta>[];\n collections: KeepCollectionDefinition[];\n memberships: KeepCollectionMembership[];\n capabilities: { collections: boolean; memberships: boolean };\n capturedAt: number;\n};\n\nexport type FallbackRecoveryJournalV2<TMeta = Record<string, unknown>> = {\n version: 2;\n operations: FallbackRecoveryOperation<TMeta>[];\n snapshot?: FallbackRecoverySnapshot<TMeta>;\n archives?: FallbackRecoverySnapshot<TMeta>[];\n backups?: KeepBackupV2<TMeta>[];\n /** An established primary history must never import old fallback deletions again. */\n initialized?: boolean;\n};\n\nexport type FallbackRecoveryJournalState<TMeta = Record<string, unknown>> =\n | { version: 1; operations: FallbackRecoveryOperation<TMeta>[] }\n | FallbackRecoveryJournalV2<TMeta>;\n\nexport interface FallbackRecoveryJournal<TMeta = Record<string, unknown>> {\n read(): Promise<FallbackRecoveryJournalState<TMeta> | undefined>;\n write(state: FallbackRecoveryJournalState<TMeta>): Promise<void>;\n /** Use one backend-wide lock across every scope's journal and adapter operations. */\n runExclusive<T>(operation: () => Promise<T>): Promise<T>;\n subscribe?(listener: () => void): () => void;\n}\n\nexport type KeepRecoveryState = {\n source: \"primary\" | \"fallback\";\n pendingOperations: number;\n snapshotStale: boolean;\n capturedAt?: number;\n issue?: unknown;\n repairSupported: boolean;\n};\nexport type KeepRecoveryResult = { status: \"applied\" | \"pending\"; pendingOperations: number };\nexport type KeepRecoveryRow<TMeta = Record<string, unknown>> = {\n key: string;\n kind: \"item\" | \"collection\" | \"membership\";\n id: string;\n candidates: Array<{\n source: string;\n value: KeepItem<TMeta> | KeepCollectionDefinition | KeepCollectionMembership;\n }>;\n conflict: boolean;\n selectedSource?: string;\n};\nexport type KeepRecoveryInspection<TMeta = Record<string, unknown>> = {\n token: string;\n sources: Array<{ id: string; label: string; snapshot: FallbackRecoverySnapshot<TMeta> }>;\n rows: KeepRecoveryRow<TMeta>[];\n issues: string[];\n operations: FallbackRecoveryOperation<TMeta>[];\n backups: KeepBackupV2<TMeta>[];\n retainedBackups?: KeepBackupV2<TMeta>[];\n};\nexport interface KeepStorageRecovery<TMeta = Record<string, unknown>> {\n getState(): KeepRecoveryState;\n subscribe(listener: () => void): () => void;\n inspect?(options?: { selections?: Record<string, string> }): Promise<KeepRecoveryInspection<TMeta>>;\n apply?(options: { token: string; selections: Record<string, string> }): Promise<KeepRecoveryResult>;\n retry?(): Promise<KeepRecoveryResult>;\n}\n\nclass RecoveryLockUnavailableError extends KeepStorageAccessError {}\n\n/** A sidecar journal; storage and lock keys deliberately have separate scopes. */\nexport class LocalStorageRecoveryJournal<TMeta = Record<string, unknown>> implements FallbackRecoveryJournal<TMeta> {\n constructor(\n private readonly key: string,\n private readonly storage: Storage | undefined,\n private readonly lockKey: string = key,\n ) {}\n\n async read(): Promise<FallbackRecoveryJournalState<TMeta> | undefined> {\n let raw: string | null;\n try {\n raw = this.storage?.getItem(this.key) ?? null;\n } catch (cause) {\n throw new KeepStorageAccessError({ operation: \"getAll\", storageKey: this.key, cause });\n }\n if (raw === null) return undefined;\n try {\n return parseRecoveryState<TMeta>(JSON.parse(raw), this.key);\n } catch (cause) {\n if (cause instanceof KeepStorageParseError) throw cause;\n throw new KeepStorageParseError({ operation: \"getAll\", storageKey: this.key, cause });\n }\n }\n\n async write(state: FallbackRecoveryJournalState<TMeta>): Promise<void> {\n if (!this.storage) throw new KeepStorageAccessError({ operation: \"set\", storageKey: this.key });\n const serialized = serializeKeepStorage(state, { operation: \"set\", storageKey: this.key });\n try {\n this.storage.setItem(this.key, serialized);\n } catch (cause) {\n if (isRecord(cause) && (cause.name === \"QuotaExceededError\" || cause.code === 22)) {\n throw new KeepStorageQuotaError({ operation: \"set\", storageKey: this.key, cause });\n }\n throw new KeepStorageAccessError({ operation: \"set\", storageKey: this.key, cause });\n }\n }\n\n runExclusive<T>(operation: () => Promise<T>): Promise<T> {\n return withLocalStorageWriteLock(\n this.lockKey,\n async () => {\n // Firefox commits localStorage snapshots at task boundaries, so keep the lock across both boundaries.\n if (typeof window !== \"undefined\") await nextStorageTask();\n try {\n return await operation();\n } finally {\n if (typeof window !== \"undefined\") await nextStorageTask();\n }\n },\n new RecoveryLockUnavailableError({ operation: \"set\", storageKey: this.key }),\n );\n }\n\n subscribe(listener: () => void): () => void {\n if (typeof window === \"undefined\") return () => undefined;\n const onStorage = (event: StorageEvent) => {\n if (event.key === null || event.key === this.key) listener();\n };\n window.addEventListener(\"storage\", onStorage);\n return () => window.removeEventListener(\"storage\", onStorage);\n }\n}\n\nfunction nextStorageTask(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, 0));\n}\n\ntype RecoveryOptions<TMeta> = {\n primary?: StorageAdapter<TMeta>;\n fallback: StorageAdapter<TMeta>;\n journal: FallbackRecoveryJournal<TMeta>;\n scope?: KeepScope;\n migrateFallbackOnEmpty: boolean;\n shouldFallback: (error: unknown) => boolean;\n mirrorWrites: boolean;\n onSourceChange: (source: \"primary\" | \"fallback\", error?: unknown) => void;\n onError: (error: unknown) => void;\n};\ntype Notify = (notification: () => void) => void;\ntype RecoveryResult<TMeta> = { ready: false } | { ready: true; snapshot?: FallbackRecoverySnapshot<TMeta> };\n\nexport class RecoveryJournalController<TMeta> implements KeepStorageRecovery<TMeta> {\n hasJournal = false;\n private readonly listeners = new Set<() => void>();\n private unsubscribeExternal?: () => void;\n private state: KeepRecoveryState;\n\n constructor(private readonly options: RecoveryOptions<TMeta>) {\n this.state = {\n source: options.primary ? \"primary\" : \"fallback\",\n pendingOperations: 0,\n snapshotStale: true,\n repairSupported: true,\n };\n }\n\n getState(): KeepRecoveryState {\n return { ...this.state };\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n this.unsubscribeExternal ??= this.options.journal.subscribe?.(() => {\n void this.refreshExternalState();\n });\n return () => {\n this.listeners.delete(listener);\n if (this.listeners.size === 0) {\n this.unsubscribeExternal?.();\n this.unsubscribeExternal = undefined;\n }\n };\n }\n\n subscribeJournalChanges(listener: () => void): () => void {\n return this.options.journal.subscribe?.(listener) ?? (() => undefined);\n }\n\n private async refreshExternalState(): Promise<void> {\n try {\n const loaded = await this.options.journal.read();\n if (!loaded) return;\n const state = parseRecoveryState<TMeta>(loaded);\n const next: FallbackRecoveryJournalV2<TMeta> =\n state.version === 2 ? state : { version: 2, operations: state.operations, initialized: true };\n this.validateScope(next);\n this.hasJournal = true;\n const pending = next.operations.length > 0;\n this.state = {\n source: pending || !this.options.primary ? \"fallback\" : \"primary\",\n pendingOperations: next.operations.length,\n snapshotStale: pending || !next.snapshot,\n capturedAt: next.snapshot?.capturedAt,\n repairSupported: true,\n };\n } catch (issue) {\n this.state = { ...this.state, snapshotStale: true, issue };\n }\n for (const listener of this.listeners) {\n try {\n listener();\n } catch {\n /* A status observer cannot break another observer. */\n }\n }\n }\n\n readItems(): Promise<KeepItem<TMeta>[]> {\n return this.read(\n (adapter) => adapter.getAll(),\n overlayItems,\n (snapshot) => snapshot.items,\n );\n }\n readCollections(): Promise<KeepCollectionDefinition[]> {\n return this.read(\n (adapter) => adapter.getCollections?.() ?? Promise.resolve([]),\n overlayCollections,\n (snapshot) => snapshot.collections,\n );\n }\n readMemberships(): Promise<KeepCollectionMembership[]> {\n return this.read(\n (adapter) => adapter.getCollectionMemberships?.() ?? Promise.resolve([]),\n overlayMemberships,\n (snapshot) => snapshot.memberships,\n );\n }\n\n write(\n operation: FallbackRecoveryOperation<TMeta>,\n execute: (adapter: StorageAdapter<TMeta>) => Promise<void> = (adapter) =>\n applyRecoveryOperation(adapter, operation),\n ): Promise<void> {\n return this.run(async (state, locked, notify) => {\n const { ready } = await this.preparePrimaryWrite(state, locked, notify);\n if (ready && this.options.primary) {\n let committed = false;\n try {\n await execute(this.options.primary);\n committed = true;\n } catch (cause) {\n if (!this.options.shouldFallback(cause)) throw cause;\n this.setSource(\"fallback\", cause, notify);\n }\n if (committed) {\n // Checkpoint, mirror and observer failures cannot undo a primary commit.\n const canMirror = await this.refresh(state, locked, notify);\n if (canMirror) await this.mirror(operation, execute, notify);\n this.setSource(\"primary\", undefined, notify);\n return;\n }\n }\n await this.commitFallback(state, operation, locked, notify);\n });\n }\n\n merge(items: KeepItem<TMeta>[]): Promise<KeepItem<TMeta>[]> {\n return this.run(async (state, locked, notify) => {\n const { ready } = await this.preparePrimaryWrite(state, locked, notify);\n const primary = this.options.primary;\n if (ready && primary) {\n let merged: KeepItem<TMeta>[] | undefined;\n try {\n const candidate = primary.merge\n ? await primary.merge(items)\n : mergeKeepItemLists(await primary.getAll(), items);\n if (!primary.merge) await persistKeepItems(primary, candidate);\n merged = candidate;\n } catch (cause) {\n if (!this.options.shouldFallback(cause)) throw cause;\n this.setSource(\"fallback\", cause, notify);\n }\n if (merged) {\n const canMirror = await this.refresh(state, locked, notify);\n if (canMirror) await this.mirror({ type: \"setItems\", items: merged }, undefined, notify);\n this.setSource(\"primary\", undefined, notify);\n return merged;\n }\n }\n const current = state.snapshot?.items ?? (await this.options.fallback.getAll());\n const merged = mergeKeepItemLists(overlayItems(current, state.operations), items);\n await this.commitFallback(state, { type: \"setItems\", items: merged }, locked, notify);\n return merged;\n });\n }\n\n inspect(options: { selections?: Record<string, string> } = {}): Promise<KeepRecoveryInspection<TMeta>> {\n return this.run((state) => this.inspection(state, options.selections ?? {}));\n }\n\n apply(options: { token: string; selections: Record<string, string> }): Promise<KeepRecoveryResult> {\n return this.run(async (state, locked, notify) => {\n if (!locked) throw new RecoveryLockUnavailableError({ operation: \"set\" });\n if (state.operations.length > 0)\n throw new Error(\"Recovery is pending. Retry the saved operations before submitting another repair.\");\n const inspection = await this.inspection(state, options.selections);\n if (inspection.token !== options.token)\n throw new Error(\"Recovery data changed. Inspect it again before applying.\");\n if (inspection.issues.length > 0) throw new Error(\"Resolve recovery conflicts and dependencies before applying.\");\n if (inspection.operations.length === 0) return { status: \"applied\", pendingOperations: 0 };\n const next = this.normalized({\n ...state,\n operations: [...state.operations, ...inspection.operations],\n backups: [...(state.backups ?? []), ...inspection.backups],\n initialized: true,\n });\n // Both the complete approved sequence and the backups commit before replay starts.\n await this.options.journal.write(next);\n Object.assign(state, next);\n this.hasJournal = true;\n this.updateState(state, notify);\n const result = await this.recover(state, locked, notify);\n return { status: result.ready ? \"applied\" : \"pending\", pendingOperations: state.operations.length };\n });\n }\n\n retry(): Promise<KeepRecoveryResult> {\n return this.run(async (state, locked, notify) => {\n if (!locked) throw new RecoveryLockUnavailableError({ operation: \"set\" });\n const result = await this.recover(state, locked, notify);\n if (result.ready) await this.refresh(state, locked, notify);\n return { status: result.ready ? \"applied\" : \"pending\", pendingOperations: state.operations.length };\n });\n }\n\n private read<T>(\n read: (adapter: StorageAdapter<TMeta>) => Promise<T>,\n overlay: (value: T, operations: FallbackRecoveryOperation<TMeta>[]) => T,\n fromSnapshot: (snapshot: FallbackRecoverySnapshot<TMeta>) => T,\n ): Promise<T> {\n return this.run(async (state, locked, notify) => {\n const result = await this.recover(state, locked, notify);\n if (result.ready && this.options.primary) {\n if (result.snapshot) return fromSnapshot(result.snapshot);\n try {\n const snapshot = await this.capture(this.options.primary);\n const migration = await this.bootstrap(state, snapshot, locked, notify);\n if (!migration.ready) return overlay(fromSnapshot(state.snapshot ?? snapshot), state.operations);\n const current = migration.snapshot ?? snapshot;\n await this.refresh(state, locked, notify, current);\n this.setSource(\"primary\", undefined, notify);\n return fromSnapshot(current);\n } catch (cause) {\n // A failed metadata capture must not hide a successful item read.\n this.degraded(cause, notify);\n try {\n const value = await read(this.options.primary);\n this.setSource(\"primary\", undefined, notify);\n return value;\n } catch (readCause) {\n if (!this.options.shouldFallback(readCause)) throw readCause;\n this.setSource(\"fallback\", readCause, notify);\n }\n }\n }\n const base = state.snapshot ? fromSnapshot(state.snapshot) : await read(this.options.fallback);\n return overlay(base, state.operations);\n });\n }\n\n private async run<T>(\n operation: (state: FallbackRecoveryJournalV2<TMeta>, locked: boolean, notify: Notify) => Promise<T>,\n ): Promise<T> {\n const notifications: Array<() => void> = [];\n const execute = async (locked: boolean) => {\n const loaded = await this.options.journal.read();\n this.hasJournal = loaded !== undefined;\n const parsed = loaded ? parseRecoveryState<TMeta>(loaded) : undefined;\n const state: FallbackRecoveryJournalV2<TMeta> =\n parsed?.version === 2\n ? parsed\n : { version: 2, operations: parsed?.operations ?? [], initialized: parsed !== undefined };\n this.validateScope(state);\n this.updateState(state, (notification) => notifications.push(notification));\n return operation(state, locked, (notification) => notifications.push(notification));\n };\n try {\n try {\n return await this.options.journal.runExclusive(() => execute(true));\n } catch (cause) {\n if (!(cause instanceof RecoveryLockUnavailableError)) throw cause;\n return await execute(false);\n }\n } finally {\n for (const notification of notifications) {\n try {\n notification();\n } catch {\n /* Observers cannot reject committed mutations. */\n }\n }\n }\n }\n\n private async capture(adapter: StorageAdapter<TMeta>): Promise<FallbackRecoverySnapshot<TMeta>> {\n const snapshot = {\n items: await adapter.getAll(),\n collections: (await adapter.getCollections?.()) ?? [],\n memberships: (await adapter.getCollectionMemberships?.()) ?? [],\n capabilities: {\n collections: Boolean(adapter.getCollections),\n memberships: Boolean(adapter.getCollectionMemberships),\n },\n capturedAt: Date.now(),\n };\n this.validateSnapshotScope(snapshot);\n return snapshot;\n }\n\n private async bootstrap(\n state: FallbackRecoveryJournalV2<TMeta>,\n snapshot: FallbackRecoverySnapshot<TMeta>,\n locked: boolean,\n notify: Notify,\n ): Promise<RecoveryResult<TMeta>> {\n if (state.initialized || !this.options.migrateFallbackOnEmpty || !this.options.primary || !locked)\n return { ready: true, snapshot };\n const legacy = await this.capture(this.options.fallback);\n const operations: FallbackRecoveryOperation<TMeta>[] = [];\n if (snapshot.items.length === 0 && legacy.items.length > 0)\n operations.push({ type: \"setItems\", items: legacy.items });\n if (snapshot.collections.length === 0 && legacy.collections.length > 0 && this.options.primary.setCollection) {\n for (const collection of legacy.collections) operations.push({ type: \"setCollection\", collection });\n }\n if (\n snapshot.memberships.length === 0 &&\n legacy.memberships.length > 0 &&\n this.options.primary.setCollectionMembership\n ) {\n for (const membership of legacy.memberships) operations.push({ type: \"setMembership\", membership });\n }\n if (operations.length === 0) return { ready: true, snapshot };\n // Partial migrations replay from the durable log even once the primary is nonempty.\n const next = this.normalized({ ...state, snapshot, archives: [legacy], operations, initialized: true });\n await this.options.journal.write(next);\n Object.assign(state, next);\n this.hasJournal = true;\n this.updateState(state, notify);\n return this.recover(state, locked, notify);\n }\n\n private async preparePrimaryWrite(\n state: FallbackRecoveryJournalV2<TMeta>,\n locked: boolean,\n notify: Notify,\n ): Promise<RecoveryResult<TMeta>> {\n const result = await this.recover(state, locked, notify);\n if (!result.ready || state.initialized || !this.options.migrateFallbackOnEmpty || !this.options.primary || !locked)\n return result;\n let snapshot: FallbackRecoverySnapshot<TMeta>;\n try {\n snapshot = await this.capture(this.options.primary);\n } catch (cause) {\n if (!this.options.shouldFallback(cause)) throw cause;\n this.degraded(cause, notify);\n return { ready: false };\n }\n // The first mutation must not make an empty primary look like established history.\n return this.bootstrap(state, snapshot, locked, notify);\n }\n\n private async refresh(\n state: FallbackRecoveryJournalV2<TMeta>,\n locked: boolean,\n notify: Notify,\n supplied?: FallbackRecoverySnapshot<TMeta>,\n ): Promise<boolean> {\n try {\n if (!this.options.primary) return false;\n if (!locked) throw new RecoveryLockUnavailableError({ operation: \"set\" });\n const snapshot = supplied ?? (await this.capture(this.options.primary));\n const archives = state.archives ?? [await this.capture(this.options.fallback)];\n const next = this.normalized({ ...state, snapshot, archives, initialized: true });\n const unchanged =\n state.initialized &&\n state.archives !== undefined &&\n state.snapshot &&\n snapshotContent(state.snapshot) === snapshotContent(snapshot);\n if (!unchanged) {\n await this.options.journal.write(next);\n Object.assign(state, next);\n this.hasJournal = true;\n }\n this.updateState(state, notify, false);\n return true;\n } catch (cause) {\n this.degraded(cause, notify);\n // Mirroring must not overwrite a legacy branch before its archive is durable.\n return state.archives !== undefined;\n }\n }\n\n private async recover(\n state: FallbackRecoveryJournalV2<TMeta>,\n locked: boolean,\n notify: Notify,\n ): Promise<RecoveryResult<TMeta>> {\n const primary = this.options.primary;\n if (!primary) {\n this.setSource(\"fallback\", undefined, notify);\n return { ready: false };\n }\n if (state.operations.length === 0) return { ready: true };\n this.setSource(\"fallback\", undefined, notify);\n if (!locked) return { ready: false };\n const replayedOperations = state.operations;\n let snapshot: FallbackRecoverySnapshot<TMeta>;\n try {\n for (const operation of state.operations) await applyRecoveryOperation(primary, operation);\n snapshot = await this.capture(primary);\n const archives = state.archives ?? [await this.capture(this.options.fallback)];\n const next = this.normalized({ ...state, snapshot, archives, operations: [], initialized: true });\n await this.options.journal.write(next);\n Object.assign(state, next);\n } catch (cause) {\n this.degraded(cause, notify);\n return { ready: false };\n }\n this.updateState(state, notify, false);\n for (const operation of replayedOperations) await this.mirror(operation, undefined, notify);\n this.setSource(\"primary\", undefined, notify);\n return { ready: true, snapshot };\n }\n\n private async commitFallback(\n state: FallbackRecoveryJournalV2<TMeta>,\n operation: FallbackRecoveryOperation<TMeta>,\n locked: boolean,\n notify: Notify,\n ): Promise<void> {\n if (!locked) throw new RecoveryLockUnavailableError({ operation: \"set\" });\n const next = this.normalized({ ...state, operations: [...state.operations, operation] });\n this.validateScope(next);\n await this.options.journal.write(next);\n this.hasJournal = true;\n Object.assign(state, next);\n this.updateState(state, notify);\n this.setSource(\"fallback\", undefined, notify);\n notify(() => this.options.onSourceChange(\"fallback\"));\n try {\n for (const pending of next.operations) await applyRecoveryOperation(this.options.fallback, pending);\n } catch (cause) {\n this.degraded(cause, notify);\n }\n }\n\n private normalized(state: FallbackRecoveryJournalV2<TMeta>): FallbackRecoveryJournalV2<TMeta> {\n const value: unknown = JSON.parse(serializeKeepStorage(state, { operation: \"set\" }));\n const parsed = parseRecoveryState<TMeta>(value);\n if (parsed.version !== 2) throw new KeepStorageParseError({ operation: \"set\" });\n return parsed;\n }\n\n private async mirror(\n operation: FallbackRecoveryOperation<TMeta>,\n execute: ((adapter: StorageAdapter<TMeta>) => Promise<void>) | undefined,\n notify: Notify,\n ): Promise<void> {\n if (!this.options.mirrorWrites) return;\n try {\n await (execute ? execute(this.options.fallback) : applyRecoveryOperation(this.options.fallback, operation));\n } catch (cause) {\n this.degraded(cause, notify);\n }\n }\n\n private setSource(source: \"primary\" | \"fallback\", error: unknown, notify: Notify): void {\n if (this.state.source === source) return;\n this.state = { ...this.state, source };\n notify(() => this.options.onSourceChange(source, error));\n for (const listener of this.listeners) notify(listener);\n }\n private degraded(issue: unknown, notify: Notify): void {\n const identity = (error: unknown) => (error instanceof Error ? `${error.name}:${error.message}` : String(error));\n if (this.state.snapshotStale && this.state.issue !== undefined && identity(this.state.issue) === identity(issue))\n return;\n this.state = { ...this.state, snapshotStale: true, issue };\n notify(() => this.options.onError(issue));\n for (const listener of this.listeners) notify(listener);\n }\n private updateState(\n state: FallbackRecoveryJournalV2<TMeta>,\n notify: Notify,\n stale = state.operations.length > 0 || this.state.snapshotStale,\n ): void {\n const next = {\n ...this.state,\n pendingOperations: state.operations.length,\n capturedAt: state.snapshot?.capturedAt,\n snapshotStale: stale,\n };\n if (!stale) delete next.issue;\n if (\n next.pendingOperations === this.state.pendingOperations &&\n next.capturedAt === this.state.capturedAt &&\n next.snapshotStale === this.state.snapshotStale\n )\n return;\n this.state = next;\n for (const listener of this.listeners) notify(listener);\n }\n private validateSnapshotScope(snapshot: FallbackRecoverySnapshot<TMeta>): void {\n if (!this.options.scope) return;\n if (\n [...snapshot.items, ...snapshot.collections, ...snapshot.memberships].some(\n (record) => !isSameKeepScope(record.scope, this.options.scope),\n )\n ) {\n throw new KeepStorageParseError({ operation: \"getAll\" });\n }\n }\n private validateScope(state: FallbackRecoveryJournalV2<TMeta>): void {\n for (const snapshot of [state.snapshot, ...(state.archives ?? [])])\n if (snapshot) this.validateSnapshotScope(snapshot);\n for (const backup of state.backups ?? [])\n this.validateSnapshotScope({\n ...backup,\n capabilities: { collections: true, memberships: true },\n capturedAt: backup.exportedAt,\n });\n if (!this.options.scope) return;\n if (state.backups?.some((backup) => backup.scopes?.some((scope) => !isSameKeepScope(scope, this.options.scope)))) {\n throw new KeepStorageParseError({ operation: \"getAll\" });\n }\n for (const operation of state.operations) {\n if (operation.type === \"setItems\") {\n if (operation.items.some((item) => !isSameKeepScope(item.scope, this.options.scope)))\n throw new KeepStorageParseError({ operation: \"getAll\" });\n } else if (operation.type === \"setCollection\") {\n if (!isSameKeepScope(operation.collection.scope, this.options.scope))\n throw new KeepStorageParseError({ operation: \"getAll\" });\n } else if (operation.type === \"setMembership\") {\n if (!isSameKeepScope(operation.membership.scope, this.options.scope))\n throw new KeepStorageParseError({ operation: \"getAll\" });\n } else if (operation.type !== \"clearItems\" && !isSameKeepScope(operation.scope, this.options.scope))\n throw new KeepStorageParseError({ operation: \"getAll\" });\n }\n }\n\n private async inspection(\n state: FallbackRecoveryJournalV2<TMeta>,\n selections: Record<string, string>,\n ): Promise<KeepRecoveryInspection<TMeta>> {\n const sources: KeepRecoveryInspection<TMeta>[\"sources\"] = [];\n const issues: string[] = [];\n for (const [id, adapter] of [\n [\"primary\", this.options.primary],\n [\"fallback\", this.options.fallback],\n ] as const) {\n if (!adapter) continue;\n try {\n sources.push({ id, label: id, snapshot: { ...(await this.capture(adapter)), capturedAt: 0 } });\n } catch (cause) {\n issues.push(`source-unavailable:${id}:${cause instanceof Error ? cause.message : String(cause)}`);\n }\n }\n if (state.snapshot)\n sources.push({\n id: \"checkpoint\",\n label: \"checkpoint\",\n snapshot: overlaySnapshot(state.snapshot, state.operations),\n });\n else if (state.operations.length > 0) {\n const fallback = sources.find((source) => source.id === \"fallback\");\n if (fallback)\n sources.push({\n id: \"checkpoint\",\n label: \"checkpoint\",\n snapshot: overlaySnapshot(fallback.snapshot, state.operations),\n });\n }\n for (const [index, snapshot] of (state.archives ?? []).entries())\n sources.push({ id: `legacy:${index}`, label: `legacy:${index}`, snapshot });\n const token = serializeKeepStorage({ scope: this.options.scope, state, sources }, { operation: \"getAll\" });\n const rows = buildRows(sources, selections, issues);\n const desired: FallbackRecoverySnapshot<TMeta> = {\n items: [],\n collections: [],\n memberships: [],\n capabilities: { collections: true, memberships: true },\n capturedAt: Date.now(),\n };\n for (const row of rows) {\n const candidate = row.candidates.find((entry) => entry.source === row.selectedSource);\n if (!candidate) continue;\n if (row.kind === \"item\" && isRecoveryItem<TMeta>(candidate.value)) desired.items.push(candidate.value);\n if (row.kind === \"collection\" && isKeepCollectionDefinition(candidate.value))\n desired.collections.push(candidate.value);\n if (row.kind === \"membership\" && isKeepCollectionMembership(candidate.value))\n desired.memberships.push(candidate.value);\n }\n const removedCollections = rows.filter((row) => row.kind === \"collection\" && row.selectedSource === \"__remove__\");\n const removedItems = rows.filter((row) => row.kind === \"item\" && row.selectedSource === \"__remove__\");\n desired.items = desired.items.map((item) => {\n if (!item.collectionId) return item;\n const exists = desired.collections.some(\n (collection) => collection.id === item.collectionId && isSameKeepScope(collection.scope, item.scope),\n );\n if (exists) return item;\n if (removedCollections.some((row) => row.key === recordKey(\"collection\", item.collectionId ?? \"\", item.scope))) {\n const { collectionId: _collectionId, ...unassigned } = item;\n return unassigned;\n }\n issues.push(`missing-collection:${item.id}:${item.collectionId}`);\n return item;\n });\n desired.memberships = desired.memberships.filter((membership) => {\n const itemExists = desired.items.some(\n (item) => item.id === membership.itemId && isSameKeepScope(item.scope, membership.scope),\n );\n const collectionExists = desired.collections.some(\n (collection) =>\n collection.id === membership.collectionId && isSameKeepScope(collection.scope, membership.scope),\n );\n if (itemExists && collectionExists) return true;\n if (\n removedItems.some((row) => row.key === recordKey(\"item\", membership.itemId, membership.scope)) ||\n removedCollections.some((row) => row.key === recordKey(\"collection\", membership.collectionId, membership.scope))\n )\n return false;\n issues.push(`invalid-membership:${membership.collectionId}/${membership.itemId}`);\n return true;\n });\n const current = sources.find((source) => source.id === \"primary\")?.snapshot ?? emptySnapshot<TMeta>();\n const fallback = sources.find((source) => source.id === \"fallback\")?.snapshot ?? emptySnapshot<TMeta>();\n const proposedOperations = [\n ...replacementOperations(overlaySnapshot(current, state.operations), desired),\n ...replacementOperations(overlaySnapshot(fallback, state.operations), desired),\n ];\n const uniqueOperations = new Map<string, FallbackRecoveryOperation<TMeta>>();\n for (const operation of proposedOperations) {\n uniqueOperations.set(serializeKeepStorage(operation, { operation: \"getAll\" }), operation);\n }\n const operations = [...uniqueOperations.values()];\n for (const operation of operations) {\n if (\n (operation.type === \"setCollection\" && !this.options.primary?.setCollection) ||\n (operation.type === \"removeCollection\" && !this.options.primary?.removeCollection)\n )\n issues.push(\"primary-collections-unavailable\");\n if (\n (operation.type === \"setMembership\" && !this.options.primary?.setCollectionMembership) ||\n (operation.type === \"removeMembership\" && !this.options.primary?.removeCollectionMembership)\n )\n issues.push(\"primary-memberships-unavailable\");\n }\n const backups: KeepBackupV2<TMeta>[] = sources.map(({ snapshot }) => ({\n format: KEEP_BACKUP_FORMAT,\n version: KEEP_BACKUP_VERSION,\n exportedAt: Date.now(),\n items: snapshot.items,\n collections: snapshot.collections,\n memberships: snapshot.memberships,\n ...(this.options.scope ? { scopes: [this.options.scope] } : {}),\n }));\n return { token, sources, rows, issues, operations, backups, retainedBackups: state.backups ?? [] };\n }\n}\n\nfunction emptySnapshot<TMeta>(): FallbackRecoverySnapshot<TMeta> {\n return {\n items: [],\n collections: [],\n memberships: [],\n capabilities: { collections: false, memberships: false },\n capturedAt: 0,\n };\n}\nfunction snapshotContent<TMeta>(snapshot: FallbackRecoverySnapshot<TMeta>): string {\n const { capturedAt: _capturedAt, ...data } = snapshot;\n return serializeKeepStorage(data, { operation: \"set\" });\n}\nfunction overlaySnapshot<TMeta>(\n snapshot: FallbackRecoverySnapshot<TMeta>,\n operations: FallbackRecoveryOperation<TMeta>[],\n): FallbackRecoverySnapshot<TMeta> {\n return {\n ...snapshot,\n items: overlayItems(snapshot.items, operations),\n collections: overlayCollections(snapshot.collections, operations),\n memberships: overlayMemberships(snapshot.memberships, operations),\n };\n}\nfunction recordKey(kind: string, id: string, scope?: KeepScope): string {\n return JSON.stringify([kind, scope?.tenantId ?? null, scope?.userId ?? null, id]);\n}\nfunction buildRows<TMeta>(\n sources: KeepRecoveryInspection<TMeta>[\"sources\"],\n selections: Record<string, string>,\n issues: string[],\n): KeepRecoveryRow<TMeta>[] {\n const byKey = new Map<string, KeepRecoveryRow<TMeta>>();\n for (const source of sources) {\n for (const [kind, records] of [\n [\"item\", source.snapshot.items],\n [\"collection\", source.snapshot.collections],\n [\"membership\", source.snapshot.memberships],\n ] as const) {\n for (const value of records) {\n const id = \"id\" in value ? value.id : `${value.collectionId}/${value.itemId}`;\n const identity = \"id\" in value ? value.id : JSON.stringify([value.collectionId, value.itemId]);\n const key = recordKey(kind, identity, value.scope);\n const row = byKey.get(key) ?? { key, kind, id, candidates: [], conflict: false };\n row.candidates.push({ source: source.id, value });\n byKey.set(key, row);\n }\n }\n }\n for (const row of byKey.values()) {\n const values = new Set(row.candidates.map(({ value }) => serializeKeepStorage(value, { operation: \"getAll\" })));\n row.conflict = values.size > 1;\n row.selectedSource = selections[row.key] ?? (row.conflict ? undefined : row.candidates[0]?.source);\n if (\n row.selectedSource !== undefined &&\n row.selectedSource !== \"__remove__\" &&\n !row.candidates.some(({ source }) => source === row.selectedSource)\n )\n issues.push(`invalid-selection:${row.id}`);\n if (row.conflict && row.selectedSource === undefined) issues.push(`unresolved-conflict:${row.id}`);\n }\n for (const key of Object.keys(selections)) if (!byKey.has(key)) issues.push(\"invalid-selection\");\n return [...byKey.values()];\n}\nfunction replacementOperations<TMeta>(\n current: FallbackRecoverySnapshot<TMeta>,\n desired: FallbackRecoverySnapshot<TMeta>,\n): FallbackRecoveryOperation<TMeta>[] {\n const operations: FallbackRecoveryOperation<TMeta>[] = [];\n for (const membership of current.memberships)\n if (\n !desired.memberships.some(\n (entry) =>\n entry.collectionId === membership.collectionId &&\n entry.itemId === membership.itemId &&\n isSameKeepScope(entry.scope, membership.scope),\n )\n )\n operations.push({\n type: \"removeMembership\",\n collectionId: membership.collectionId,\n itemId: membership.itemId,\n scope: membership.scope,\n });\n for (const collection of current.collections)\n if (\n !desired.collections.some((entry) => entry.id === collection.id && isSameKeepScope(entry.scope, collection.scope))\n )\n operations.push({ type: \"removeCollection\", id: collection.id, scope: collection.scope });\n for (const item of current.items)\n if (!desired.items.some((entry) => entry.id === item.id && isSameKeepScope(entry.scope, item.scope)))\n operations.push({ type: \"removeItems\", ids: [item.id], scope: item.scope });\n for (const collection of desired.collections) {\n const existing = current.collections.find(\n (entry) => entry.id === collection.id && isSameKeepScope(entry.scope, collection.scope),\n );\n if (!sameRecoveryRecord(existing, collection)) operations.push({ type: \"setCollection\", collection });\n }\n const isChangedItem = (item: KeepItem<TMeta>) => {\n const existing = current.items.find((entry) => entry.id === item.id && isSameKeepScope(entry.scope, item.scope));\n return !sameRecoveryRecord(existing, item);\n };\n const changedItems = desired.items.filter(isChangedItem);\n if (changedItems.length > 0) operations.push({ type: \"setItems\", items: changedItems });\n for (const membership of desired.memberships) {\n const existing = current.memberships.find(\n (entry) =>\n entry.collectionId === membership.collectionId &&\n entry.itemId === membership.itemId &&\n isSameKeepScope(entry.scope, membership.scope),\n );\n if (!sameRecoveryRecord(existing, membership)) operations.push({ type: \"setMembership\", membership });\n }\n return operations;\n}\n\nfunction sameRecoveryRecord<T>(left: T | undefined, right: T): boolean {\n if (left === undefined) return false;\n return serializeKeepStorage(left, { operation: \"getAll\" }) === serializeKeepStorage(right, { operation: \"getAll\" });\n}\nasync function applyRecoveryOperation<TMeta>(\n adapter: StorageAdapter<TMeta>,\n operation: FallbackRecoveryOperation<TMeta>,\n): Promise<void> {\n switch (operation.type) {\n case \"setItems\":\n return persistKeepItems(adapter, operation.items);\n case \"removeItems\":\n if (adapter.removeMany) return adapter.removeMany(operation.ids, operation.scope);\n for (const id of operation.ids) await adapter.remove(id, operation.scope);\n return;\n case \"clearItems\":\n return adapter.clear();\n case \"setCollection\":\n if (!adapter.setCollection) throw new Error(\"Collection storage is unavailable.\");\n return adapter.setCollection(operation.collection);\n case \"removeCollection\":\n if (!adapter.removeCollection) throw new Error(\"Collection storage is unavailable.\");\n return adapter.removeCollection(operation.id, operation.scope);\n case \"setMembership\":\n if (!adapter.setCollectionMembership) throw new Error(\"Collection membership storage is unavailable.\");\n return adapter.setCollectionMembership(operation.membership);\n case \"removeMembership\":\n if (!adapter.removeCollectionMembership) throw new Error(\"Collection membership storage is unavailable.\");\n return adapter.removeCollectionMembership(operation.collectionId, operation.itemId, operation.scope);\n }\n}\n\nfunction overlayItems<TMeta>(\n items: KeepItem<TMeta>[],\n operations: FallbackRecoveryOperation<TMeta>[],\n): KeepItem<TMeta>[] {\n let next = items;\n for (const operation of operations) {\n if (operation.type === \"clearItems\") next = [];\n if (operation.type === \"setItems\") {\n for (const item of operation.items) {\n next = [...next.filter((entry) => entry.id !== item.id || !isSameKeepScope(entry.scope, item.scope)), item];\n }\n }\n if (operation.type === \"removeItems\") {\n next = next.filter(\n (item) =>\n !operation.ids.includes(item.id) ||\n (operation.scope !== undefined && !isSameKeepScope(item.scope, operation.scope)),\n );\n }\n }\n return next;\n}\n\nfunction overlayCollections<TMeta>(\n collections: KeepCollectionDefinition[],\n operations: FallbackRecoveryOperation<TMeta>[],\n): KeepCollectionDefinition[] {\n let next = collections;\n for (const operation of operations) {\n if (operation.type === \"setCollection\") {\n const collection = operation.collection;\n next = [\n ...next.filter((entry) => entry.id !== collection.id || !isSameKeepScope(entry.scope, collection.scope)),\n collection,\n ];\n }\n if (operation.type === \"removeCollection\") {\n next = next.filter((entry) => entry.id !== operation.id || !isSameKeepScope(entry.scope, operation.scope));\n }\n }\n return next;\n}\n\nfunction overlayMemberships<TMeta>(\n memberships: KeepCollectionMembership[],\n operations: FallbackRecoveryOperation<TMeta>[],\n): KeepCollectionMembership[] {\n let next = memberships;\n for (const operation of operations) {\n if (operation.type === \"clearItems\") next = [];\n if (operation.type === \"setMembership\") {\n const membership = operation.membership;\n next = [\n ...next.filter(\n (entry) =>\n entry.collectionId !== membership.collectionId ||\n entry.itemId !== membership.itemId ||\n !isSameKeepScope(entry.scope, membership.scope),\n ),\n membership,\n ];\n }\n if (operation.type === \"removeMembership\") {\n next = next.filter(\n (entry) =>\n entry.collectionId !== operation.collectionId ||\n entry.itemId !== operation.itemId ||\n !isSameKeepScope(entry.scope, operation.scope),\n );\n }\n if (operation.type === \"removeCollection\") {\n next = next.filter(\n (entry) => entry.collectionId !== operation.id || !isSameKeepScope(entry.scope, operation.scope),\n );\n }\n if (operation.type === \"removeItems\") {\n next = next.filter(\n (entry) =>\n !operation.ids.includes(entry.itemId) ||\n (operation.scope !== undefined && !isSameKeepScope(entry.scope, operation.scope)),\n );\n }\n }\n return next;\n}\n\nfunction parseRecoveryState<TMeta>(value: unknown, storageKey?: string): FallbackRecoveryJournalState<TMeta> {\n if (\n !isRecord(value) ||\n (value.version !== 1 && value.version !== 2) ||\n !Array.isArray(value.operations) ||\n !value.operations.every(isRecoveryOperation<TMeta>)\n ) {\n throw new KeepStorageParseError({ operation: \"getAll\", storageKey });\n }\n if (value.version === 1) return { version: 1, operations: value.operations };\n if (\n (value.snapshot !== undefined && !isRecoverySnapshot<TMeta>(value.snapshot)) ||\n (value.archives !== undefined &&\n (!Array.isArray(value.archives) || !value.archives.every(isRecoverySnapshot<TMeta>))) ||\n (value.backups !== undefined && (!Array.isArray(value.backups) || !value.backups.every(isRecoveryBackup<TMeta>))) ||\n (value.initialized !== undefined && typeof value.initialized !== \"boolean\")\n )\n throw new KeepStorageParseError({ operation: \"getAll\", storageKey });\n return {\n version: 2,\n operations: value.operations,\n ...(isRecoverySnapshot<TMeta>(value.snapshot) ? { snapshot: value.snapshot } : {}),\n ...(Array.isArray(value.archives) && value.archives.every(isRecoverySnapshot<TMeta>)\n ? { archives: value.archives }\n : {}),\n ...(Array.isArray(value.backups) && value.backups.every(isRecoveryBackup<TMeta>) ? { backups: value.backups } : {}),\n ...(typeof value.initialized === \"boolean\" ? { initialized: value.initialized } : {}),\n };\n}\nfunction isRecoveryItem<TMeta>(value: unknown): value is KeepItem<TMeta> {\n return isKeepItem(value);\n}\nfunction isRecoverySnapshot<TMeta>(value: unknown): value is FallbackRecoverySnapshot<TMeta> {\n return (\n isRecord(value) &&\n isKeepItemArray(value.items) &&\n Array.isArray(value.collections) &&\n value.collections.every(isKeepCollectionDefinition) &&\n Array.isArray(value.memberships) &&\n value.memberships.every(isKeepCollectionMembership) &&\n isRecord(value.capabilities) &&\n typeof value.capabilities.collections === \"boolean\" &&\n typeof value.capabilities.memberships === \"boolean\" &&\n typeof value.capturedAt === \"number\" &&\n Number.isFinite(value.capturedAt)\n );\n}\nfunction isRecoveryBackup<TMeta>(value: unknown): value is KeepBackupV2<TMeta> {\n return (\n isRecord(value) &&\n value.format === KEEP_BACKUP_FORMAT &&\n value.version === KEEP_BACKUP_VERSION &&\n typeof value.exportedAt === \"number\" &&\n Number.isFinite(value.exportedAt) &&\n isKeepItemArray(value.items) &&\n Array.isArray(value.collections) &&\n value.collections.every(isKeepCollectionDefinition) &&\n Array.isArray(value.memberships) &&\n value.memberships.every(isKeepCollectionMembership) &&\n (value.scopes === undefined || (Array.isArray(value.scopes) && value.scopes.every(isRecoveryScope)))\n );\n}\nfunction isRecoveryScope(value: unknown): value is KeepScope {\n return (\n isRecord(value) &&\n (value.userId === undefined || typeof value.userId === \"string\") &&\n (value.tenantId === undefined || typeof value.tenantId === \"string\")\n );\n}\n\nfunction isRecoveryOperation<TMeta>(value: unknown): value is FallbackRecoveryOperation<TMeta> {\n if (!isRecord(value)) return false;\n if (\n value.scope !== undefined &&\n (!isRecord(value.scope) ||\n (value.scope.userId !== undefined && typeof value.scope.userId !== \"string\") ||\n (value.scope.tenantId !== undefined && typeof value.scope.tenantId !== \"string\"))\n )\n return false;\n switch (value.type) {\n case \"setItems\":\n return isKeepItemArray(value.items);\n case \"removeItems\":\n return Array.isArray(value.ids) && value.ids.every((id) => typeof id === \"string\");\n case \"clearItems\":\n return true;\n case \"setCollection\":\n return isKeepCollectionDefinition(value.collection);\n case \"removeCollection\":\n return typeof value.id === \"string\";\n case \"setMembership\":\n return isKeepCollectionMembership(value.membership);\n case \"removeMembership\":\n return typeof value.collectionId === \"string\" && typeof value.itemId === \"string\";\n default:\n return false;\n }\n}\n","import type {\n KeepCollectionDefinition,\n KeepCollectionMembership,\n KeepCollectionSyncConflict,\n KeepCollectionSyncOperation,\n KeepCollectionSyncResult,\n KeepConflictResolver,\n KeepItem,\n KeepMembershipSyncOperation,\n KeepSyncConflict,\n KeepSyncQueueOperation,\n KeepSyncRejectedOperation,\n KeepSyncResolution,\n KeepSyncState,\n RemoteSyncDriver,\n RemoteSyncResult,\n StorageAdapter,\n SyncCapableStorageAdapter,\n SyncOperation,\n SyncQueueAdapter,\n SyncScope,\n} from \"../features/items/types\";\nimport { isKeepSyncAuthError } from \"../features/items/types\";\nimport {\n isKeepCollectionDefinition,\n isKeepCollectionMembership,\n isRecord,\n mergeKeepItemLists,\n persistKeepItems,\n} from \"../features/persistence/helpers\";\nimport { isSameKeepScope, ScopedSyncQueueAdapter } from \"../features/persistence/scope\";\nimport { serializeKeepStorage } from \"../features/persistence/serialization\";\nimport { withLocalStorageWriteLock } from \"../features/persistence/write-lock\";\nimport type { KeepStorageRecovery } from \"./recovery-journal\";\n\nexport type LocalStorageSyncQueueOptions = {\n key?: string;\n storage?: Storage;\n};\n\nexport type IndexedDBSyncQueueOptions = {\n databaseName?: string;\n storeName?: string;\n version?: number;\n indexedDB?: IDBFactory;\n};\n\nexport type FallbackSyncQueueAdapterOptions<TMeta = Record<string, unknown>> = {\n primary: SyncQueueAdapter<TMeta>;\n fallback: SyncQueueAdapter<TMeta>;\n shouldFallback?: (error: unknown) => boolean;\n};\n\nexport type SyncStorageAdapterOptions<TMeta = Record<string, unknown>> = {\n local: StorageAdapter<TMeta>;\n remote: RemoteSyncDriver<TMeta>;\n queue?: SyncQueueAdapter<TMeta>;\n queueKey?: string;\n queueDatabaseName?: string;\n clientId?: string;\n now?: () => number;\n resolveConflict?: KeepConflictResolver<TMeta>;\n userId?: string;\n tenantId?: string;\n maxRetries?: number;\n retryDelayMs?: number;\n retryBackoff?: number;\n scope?: SyncScope;\n /**\n * How `remote.pull()` results are applied. `\"merge\"` (default) treats them as a partial list and never deletes\n * local items. `\"snapshot\"` treats them as the complete item list for the active scope and removes local items\n * that the server has acknowledged before (they carry a `revision`) but no longer returns. Items with pending\n * local operations are kept, so an offline edit of a remotely deleted item is pushed again.\n */\n itemPullMode?: \"merge\" | \"snapshot\";\n};\n\nexport const DEFAULT_SYNC_QUEUE_KEY = \"keepkit:sync-queue\";\nexport const DEFAULT_SYNC_QUEUE_DATABASE = \"keepkit-sync\";\nexport const DEFAULT_SYNC_QUEUE_STORE = \"sync-queue\";\n\nexport class LocalStorageSyncQueueAdapter<TMeta = Record<string, unknown>> implements SyncQueueAdapter<TMeta> {\n private readonly key: string;\n private readonly storage: Storage | undefined;\n\n constructor(options: LocalStorageSyncQueueOptions = {}) {\n this.key = options.key ?? DEFAULT_SYNC_QUEUE_KEY;\n this.storage = options.storage ?? getBrowserStorage();\n }\n\n async getAll(): Promise<KeepSyncQueueOperation<TMeta>[]> {\n return this.readAll();\n }\n\n async setMany(operations: KeepSyncQueueOperation<TMeta>[]): Promise<void> {\n if (!this.storage) return;\n await withLocalStorageWriteLock(\n this.key,\n async () => {\n const byId = new Map((await this.readAll()).map((operation) => [operation.operationId, operation]));\n for (const operation of operations) byId.set(operation.operationId, operation);\n this.writeAll([...byId.values()]);\n },\n new Error(\"KeepKit needs the Web Locks API to safely update a sync queue across tabs.\"),\n );\n }\n\n async remove(operationIds: string[]): Promise<void> {\n if (!this.storage || operationIds.length === 0) return;\n await withLocalStorageWriteLock(\n this.key,\n async () => {\n const ids = new Set(operationIds);\n this.writeAll((await this.readAll()).filter((operation) => !ids.has(operation.operationId)));\n },\n new Error(\"KeepKit needs the Web Locks API to safely update a sync queue across tabs.\"),\n );\n }\n\n async clear(): Promise<void> {\n if (!this.storage) return;\n await withLocalStorageWriteLock(\n this.key,\n async () => this.storage?.removeItem(this.key),\n new Error(\"KeepKit needs the Web Locks API to safely update a sync queue across tabs.\"),\n );\n }\n\n private async readAll(): Promise<KeepSyncQueueOperation<TMeta>[]> {\n if (!this.storage) return [];\n const raw = this.storage.getItem(this.key);\n if (!raw) return [];\n let value: unknown;\n try {\n value = JSON.parse(raw);\n } catch (cause) {\n throw Object.assign(new Error(\"KeepKit sync queue contains invalid JSON.\"), { cause });\n }\n if (!Array.isArray(value) || !value.every(isSyncQueueOperation)) {\n throw new Error(\"KeepKit sync queue contains invalid operations.\");\n }\n return value as KeepSyncQueueOperation<TMeta>[];\n }\n\n private writeAll(operations: KeepSyncQueueOperation<TMeta>[]): void {\n if (!this.storage) return;\n const serialized = serializeKeepStorage(operations, { operation: \"set\", storageKey: this.key });\n this.storage.setItem(this.key, serialized);\n }\n}\n\nexport class IndexedDBSyncQueueAdapter<TMeta = Record<string, unknown>> implements SyncQueueAdapter<TMeta> {\n private readonly databaseName: string;\n private readonly storeName: string;\n private readonly version: number;\n private readonly indexedDB: IDBFactory | undefined;\n private databasePromise: Promise<IDBDatabase | undefined> | undefined;\n\n constructor(options: IndexedDBSyncQueueOptions = {}) {\n this.databaseName = options.databaseName ?? DEFAULT_SYNC_QUEUE_DATABASE;\n this.storeName = options.storeName ?? DEFAULT_SYNC_QUEUE_STORE;\n this.version = options.version ?? 1;\n this.indexedDB = options.indexedDB ?? getBrowserIndexedDB();\n }\n\n async getAll(): Promise<KeepSyncQueueOperation<TMeta>[]> {\n const database = await this.open();\n if (!database) return [];\n const transaction = database.transaction(this.storeName, \"readonly\");\n const value: unknown = await requestToPromise(transaction.objectStore(this.storeName).getAll());\n if (!Array.isArray(value) || !value.every(isSyncQueueOperation)) {\n throw new Error(\"KeepKit sync queue contains invalid operations.\");\n }\n return value as KeepSyncQueueOperation<TMeta>[];\n }\n\n async setMany(operations: KeepSyncQueueOperation<TMeta>[]): Promise<void> {\n const database = await this.open();\n if (!database) return;\n const transaction = database.transaction(this.storeName, \"readwrite\");\n const store = transaction.objectStore(this.storeName);\n for (const operation of operations) store.put(operation);\n await transactionToPromise(transaction);\n }\n\n async remove(operationIds: string[]): Promise<void> {\n const database = await this.open();\n if (!database) return;\n const transaction = database.transaction(this.storeName, \"readwrite\");\n const store = transaction.objectStore(this.storeName);\n for (const operationId of new Set(operationIds)) store.delete(operationId);\n await transactionToPromise(transaction);\n }\n\n async clear(): Promise<void> {\n const database = await this.open();\n if (!database) return;\n const transaction = database.transaction(this.storeName, \"readwrite\");\n transaction.objectStore(this.storeName).clear();\n await transactionToPromise(transaction);\n }\n\n private open(): Promise<IDBDatabase | undefined> {\n if (!this.indexedDB) return Promise.resolve(undefined);\n if (!this.databasePromise) {\n this.databasePromise = new Promise((resolve, reject) => {\n let request: IDBOpenDBRequest;\n try {\n request = this.indexedDB?.open(this.databaseName, this.version) as IDBOpenDBRequest;\n } catch (cause) {\n reject(cause);\n return;\n }\n request.onupgradeneeded = () => {\n if (!request.result.objectStoreNames.contains(this.storeName)) {\n request.result.createObjectStore(this.storeName, { keyPath: \"operationId\" });\n }\n };\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n request.onblocked = () => reject(request.error ?? new Error(\"IndexedDB open was blocked.\"));\n });\n }\n return this.databasePromise.catch((cause) => {\n this.databasePromise = undefined;\n throw cause;\n });\n }\n}\n\n/** Keeps the durable sync queue available when IndexedDB is blocked or fails. */\nexport class FallbackSyncQueueAdapter<TMeta = Record<string, unknown>> implements SyncQueueAdapter<TMeta> {\n private readonly primary: SyncQueueAdapter<TMeta>;\n private readonly fallback: SyncQueueAdapter<TMeta>;\n private readonly shouldFallback: (error: unknown) => boolean;\n private active: \"primary\" | \"fallback\" = \"primary\";\n\n constructor(options: FallbackSyncQueueAdapterOptions<TMeta>) {\n this.primary = options.primary;\n this.fallback = options.fallback;\n this.shouldFallback = options.shouldFallback ?? (() => true);\n }\n\n get isUsingFallback(): boolean {\n return this.active === \"fallback\";\n }\n\n getAll(): Promise<KeepSyncQueueOperation<TMeta>[]> {\n return this.execute((adapter) => adapter.getAll());\n }\n\n setMany(operations: KeepSyncQueueOperation<TMeta>[]): Promise<void> {\n return this.execute((adapter) => adapter.setMany(operations));\n }\n\n remove(operationIds: string[]): Promise<void> {\n return this.execute((adapter) => adapter.remove(operationIds));\n }\n\n clear(): Promise<void> {\n return this.execute((adapter) => adapter.clear());\n }\n\n private async execute<TResult>(operation: (adapter: SyncQueueAdapter<TMeta>) => Promise<TResult>): Promise<TResult> {\n const adapter = this.active === \"primary\" ? this.primary : this.fallback;\n try {\n return await operation(adapter);\n } catch (error) {\n if (this.active !== \"primary\" || !this.shouldFallback(error)) throw error;\n this.active = \"fallback\";\n return operation(this.fallback);\n }\n }\n}\n\n/** A local-first adapter that persists remote operations until they are acknowledged. */\nexport class SyncStorageAdapter<TMeta = Record<string, unknown>> implements SyncCapableStorageAdapter<TMeta> {\n readonly storageKey?: string;\n readonly recovery?: KeepStorageRecovery<TMeta>;\n readonly getCollections?: () => Promise<KeepCollectionDefinition[]>;\n readonly setCollection?: (collection: KeepCollectionDefinition) => Promise<void>;\n readonly removeCollection?: (id: string, scope?: SyncScope) => Promise<void>;\n readonly getCollectionMemberships?: () => Promise<KeepCollectionMembership[]>;\n readonly setCollectionMembership?: (membership: KeepCollectionMembership) => Promise<void>;\n readonly removeCollectionMembership?: (collectionId: string, itemId: string, scope?: SyncScope) => Promise<void>;\n private readonly local: StorageAdapter<TMeta>;\n private readonly remote: RemoteSyncDriver<TMeta>;\n private readonly queue: SyncQueueAdapter<TMeta>;\n private readonly clientId: string;\n private readonly now: () => number;\n private readonly resolveConflict?: KeepConflictResolver<TMeta>;\n readonly scope?: SyncScope;\n private readonly maxRetries: number;\n private readonly retryDelayMs: number;\n private readonly retryBackoff: number;\n private readonly itemPullMode: \"merge\" | \"snapshot\";\n private readonly listeners = new Set<() => void>();\n private readonly dataListeners = new Set<() => void>();\n private queueItems: KeepSyncQueueOperation<TMeta>[] = [];\n private queueLoaded = false;\n private queueLoadPromise: Promise<void> | undefined;\n private flushPromise: Promise<void> | undefined;\n private state: KeepSyncState<TMeta> = { status: \"idle\", pendingCount: 0, conflictIds: [], conflicts: [] };\n private readonly conflicts = new Map<string, KeepSyncConflict<TMeta>>();\n private readonly rejectedOperations = new Map<string, KeepSyncRejectedOperation<TMeta>>();\n private onlineHandler?: () => void;\n private disposed = false;\n\n constructor(options: SyncStorageAdapterOptions<TMeta>) {\n this.local = options.local;\n this.remote = options.remote;\n this.scope = getSyncScope(options);\n const queue = options.queue ?? createDefaultQueue<TMeta>(options);\n this.queue = this.scope ? new ScopedSyncQueueAdapter(queue, this.scope) : queue;\n this.clientId = options.clientId ?? createId();\n this.now = options.now ?? Date.now;\n this.resolveConflict = options.resolveConflict;\n this.maxRetries = Math.max(0, options.maxRetries ?? 3);\n this.retryDelayMs = Math.max(0, options.retryDelayMs ?? 0);\n this.retryBackoff = Math.max(1, options.retryBackoff ?? 2);\n this.itemPullMode = options.itemPullMode ?? \"merge\";\n this.storageKey = this.local.storageKey;\n const localRecovery = this.local.recovery;\n if (localRecovery && isSameKeepScope(this.local.scope, this.scope ?? this.local.scope)) {\n this.recovery = {\n getState: () => ({ ...localRecovery.getState(), repairSupported: false }),\n subscribe: (listener) => localRecovery.subscribe(listener),\n };\n }\n if (this.local.getCollections && this.local.setCollection && this.local.removeCollection) {\n const getCollections = this.local.getCollections.bind(this.local);\n const setCollection = this.local.setCollection.bind(this.local);\n const removeCollection = this.local.removeCollection.bind(this.local);\n this.getCollections = async () => {\n const collections = await getCollections();\n const scope = this.scope;\n return scope ? collections.filter((collection) => sameScope(collection.scope, scope)) : collections;\n };\n this.setCollection = async (collection) => {\n const scopedCollection = { ...collection, ...(this.scope ? { scope: this.scope } : {}) };\n if (this.remote.pushCollection) {\n const current = (await this.getCollections?.())?.find((entry) => entry.id === scopedCollection.id);\n const operation = this.createCollectionOperation(\n \"upsert\",\n scopedCollection.id,\n scopedCollection,\n current?.revision,\n );\n await this.enqueueBeforeLocalWrite(operation);\n try {\n await setCollection(scopedCollection);\n } catch (cause) {\n await this.removeQueued(operation.operationId);\n throw cause;\n }\n this.notifyDataListeners();\n this.setPendingState();\n return;\n }\n await setCollection(scopedCollection);\n this.notifyDataListeners();\n };\n this.removeCollection = async (id) => {\n const memberships = (await this.getCollectionMemberships?.()) ?? [];\n const membershipOperations = this.remote.pushMembership\n ? memberships\n .filter((membership) => membership.collectionId === id)\n .map((membership) => this.createMembershipOperation(\"remove\", membership.collectionId, membership.itemId))\n : [];\n if (this.remote.pushCollection) {\n const current = (await this.getCollections?.())?.find((collection) => collection.id === id);\n const operation = this.createCollectionOperation(\"remove\", id, undefined, current?.revision);\n await this.enqueueManyBeforeLocalWrite([...membershipOperations, operation]);\n try {\n await removeCollection(id, this.scope);\n } catch (cause) {\n await this.removeQueued([operation.operationId, ...membershipOperations.map((entry) => entry.operationId)]);\n throw cause;\n }\n this.notifyDataListeners();\n this.setPendingState();\n return;\n }\n await removeCollection(id, this.scope);\n this.notifyDataListeners();\n };\n }\n if (\n this.local.getCollectionMemberships &&\n this.local.setCollectionMembership &&\n this.local.removeCollectionMembership\n ) {\n const getMemberships = this.local.getCollectionMemberships.bind(this.local);\n const setMembership = this.local.setCollectionMembership.bind(this.local);\n const removeMembership = this.local.removeCollectionMembership.bind(this.local);\n this.getCollectionMemberships = async () => {\n const memberships = await getMemberships();\n const scope = this.scope;\n return scope ? memberships.filter((membership) => sameScope(membership.scope, scope)) : memberships;\n };\n this.setCollectionMembership = async (membership) => {\n const scoped = { ...membership, ...(this.scope ? { scope: this.scope } : {}) };\n if (this.remote.pushMembership) {\n const operation = this.createMembershipOperation(\"upsert\", scoped.collectionId, scoped.itemId, scoped);\n await this.enqueueBeforeLocalWrite(operation);\n try {\n await setMembership(scoped);\n } catch (cause) {\n await this.removeQueued(operation.operationId);\n throw cause;\n }\n this.setPendingState();\n } else {\n await setMembership(scoped);\n }\n this.notifyDataListeners();\n };\n this.removeCollectionMembership = async (collectionId, itemId) => {\n if (this.remote.pushMembership) {\n const operation = this.createMembershipOperation(\"remove\", collectionId, itemId);\n await this.enqueueBeforeLocalWrite(operation);\n try {\n await removeMembership(collectionId, itemId, this.scope);\n } catch (cause) {\n await this.removeQueued(operation.operationId);\n throw cause;\n }\n this.setPendingState();\n } else {\n await removeMembership(collectionId, itemId, this.scope);\n }\n this.notifyDataListeners();\n };\n }\n if (typeof window !== \"undefined\") {\n this.onlineHandler = () => void this.flushSync();\n window.addEventListener(\"online\", this.onlineHandler);\n }\n void this.resumeQueue();\n }\n\n getSyncState = (): KeepSyncState<TMeta> => this.state;\n\n subscribeSync = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n\n subscribe = (listener: () => void): (() => void) => {\n this.dataListeners.add(listener);\n const unsubscribeLocal = this.local.subscribe?.(listener) ?? (() => undefined);\n return () => {\n this.dataListeners.delete(listener);\n unsubscribeLocal();\n };\n };\n\n async getAll(): Promise<KeepItem<TMeta>[]> {\n const items = await this.local.getAll();\n const scope = this.scope;\n if (!scope) return items;\n return items.filter((item) => sameScope(item.scope, scope));\n }\n\n async set(item: KeepItem<TMeta>): Promise<void> {\n const scopedItem = this.applyScope(item);\n const operation = this.createOperation(\"upsert\", scopedItem.id, scopedItem);\n await this.enqueueBeforeLocalWrite(operation);\n try {\n await this.local.set(scopedItem);\n } catch (cause) {\n await this.removeQueued(operation.operationId);\n throw cause;\n }\n this.notifyDataListeners();\n this.setPendingState();\n }\n\n async setMany(items: KeepItem<TMeta>[]): Promise<void> {\n const scopedItems = items.map((item) => this.applyScope(item));\n const operations = scopedItems.map((item) => this.createOperation(\"upsert\", item.id, item));\n await this.enqueueManyBeforeLocalWrite(operations);\n try {\n await persistKeepItems(this.local, scopedItems);\n } catch (cause) {\n await this.removeQueued(operations.map((operation) => operation.operationId));\n throw cause;\n }\n this.notifyDataListeners();\n this.setPendingState();\n }\n\n async remove(id: string): Promise<void> {\n const operation = this.createOperation(\"remove\", id);\n const memberships = (await this.getCollectionMemberships?.()) ?? [];\n const membershipOperations = this.remote.pushMembership\n ? memberships\n .filter((membership) => membership.itemId === id)\n .map((membership) => this.createMembershipOperation(\"remove\", membership.collectionId, membership.itemId))\n : [];\n await this.enqueueManyBeforeLocalWrite([...membershipOperations, operation]);\n try {\n await this.local.remove(id, this.scope);\n } catch (cause) {\n await this.removeQueued([operation.operationId, ...membershipOperations.map((entry) => entry.operationId)]);\n throw cause;\n }\n this.notifyDataListeners();\n this.setPendingState();\n }\n\n async removeMany(ids: string[]): Promise<void> {\n const operations = [...new Set(ids)].map((id) => this.createOperation(\"remove\", id));\n const idSet = new Set(ids);\n const memberships = (await this.getCollectionMemberships?.()) ?? [];\n const membershipOperations = this.remote.pushMembership\n ? memberships\n .filter((membership) => idSet.has(membership.itemId))\n .map((membership) => this.createMembershipOperation(\"remove\", membership.collectionId, membership.itemId))\n : [];\n await this.enqueueManyBeforeLocalWrite([...membershipOperations, ...operations]);\n try {\n if (this.local.removeMany) await this.local.removeMany(ids, this.scope);\n else await Promise.all(ids.map((id) => this.local.remove(id, this.scope)));\n } catch (cause) {\n await this.removeQueued([...operations, ...membershipOperations].map((operation) => operation.operationId));\n throw cause;\n }\n this.notifyDataListeners();\n this.setPendingState();\n }\n\n async clear(): Promise<void> {\n const items = await this.getAll();\n await this.removeMany(items.map((item) => item.id));\n if (!this.scope) await this.local.clear();\n }\n\n async merge(localItems: KeepItem<TMeta>[]): Promise<KeepItem<TMeta>[]> {\n if (this.scope) {\n const merged = mergeKeepItemLists(\n await this.getAll(),\n localItems.map((item) => this.applyScope(item)),\n );\n await this.setMany(localItems);\n return merged;\n }\n const merged = this.local.merge\n ? await this.local.merge(localItems)\n : mergeKeepItemLists(await this.local.getAll(), localItems);\n if (!this.local.merge) await persistKeepItems(this.local, merged);\n await this.setMany(localItems);\n return merged;\n }\n\n async flushSync(): Promise<void> {\n if (this.flushPromise) return this.flushPromise;\n this.flushPromise = this.runFlush().finally(() => {\n this.flushPromise = undefined;\n });\n return this.flushPromise;\n }\n\n retrySync(): Promise<void> {\n return this.flushSync();\n }\n\n async resolveSyncConflict(id: string, resolution: KeepSyncResolution, item?: KeepItem<TMeta>): Promise<void> {\n await this.loadQueue();\n const conflict = this.conflicts.get(id);\n if (!conflict) return;\n if (resolution === \"manual\" && !item) {\n throw new Error(`KeepKit manual conflict resolution requires an item for \"${id}\".`);\n }\n\n if (resolution === \"remote\") {\n await this.local.set(this.applyScope(conflict.remote));\n await this.removeQueued(conflict.operation.operationId);\n } else {\n const retry = item\n ? this.createOperation(\"upsert\", item.id, {\n ...item,\n revision: conflict.revision ?? item.revision,\n })\n : {\n ...conflict.operation,\n operationId: `${this.clientId}:${this.now()}:${createId()}`,\n createdAt: this.now(),\n baseRevision: conflict.revision,\n attempts: 0,\n };\n if (retry.item) await this.local.set(this.applyScope(retry.item));\n await this.replaceQueued(conflict.operation, retry);\n }\n\n this.conflicts.delete(id);\n this.updateState({\n status: this.queueItems.length > 0 ? \"pending\" : \"synced\",\n pendingCount: this.queueItems.length,\n conflictIds: [...this.conflicts.keys()],\n conflicts: [...this.conflicts.values()],\n });\n if (resolution !== \"remote\" && this.queueItems.length > 0) await this.flushSync();\n }\n\n async resolveRejectedSyncOperation(operationId: string, resolution: \"retry\" | \"discard\"): Promise<void> {\n await this.loadQueue();\n if (!this.rejectedOperations.has(operationId)) return;\n if (resolution === \"discard\") {\n await this.removeQueued(operationId);\n if (this.queueItems.length > 0) await this.flushSync();\n return;\n }\n\n this.rejectedOperations.delete(operationId);\n this.updateState({ status: \"pending\", error: undefined });\n await this.flushSync();\n }\n\n async resolveCollectionSyncConflict(\n id: string,\n resolution: \"local\" | \"remote\",\n collection?: KeepCollectionDefinition,\n ): Promise<void> {\n await this.loadQueue();\n const conflict = (this.state.collectionConflicts ?? []).find((entry) => entry.operation.id === id);\n if (!conflict) return;\n if (!this.local.getCollections || !this.local.setCollection || !this.local.removeCollection) {\n throw new Error(\"KeepKit collection storage is unavailable.\");\n }\n if (resolution === \"remote\") {\n if (conflict.deleted) await this.local.removeCollection(id, this.scope);\n else {\n if (!conflict.collection) throw new Error(\"Remote collection conflict is missing its selected definition.\");\n await this.local.setCollection({\n ...conflict.collection,\n ...(conflict.revision ? { revision: conflict.revision } : {}),\n ...(this.scope ? { scope: this.scope } : {}),\n });\n }\n await this.removeQueued(conflict.operation.operationId);\n this.updateState({\n collectionConflicts: (this.state.collectionConflicts ?? []).filter((entry) => entry.operation.id !== id),\n });\n return;\n }\n\n if (collection && collection.id !== id) {\n throw new TypeError(\"KeepKit collection conflict resolution must use the requested collection ID.\");\n }\n const chosen = collection ?? (await this.getCollections?.())?.find((entry) => entry.id === id);\n const retry: KeepCollectionSyncOperation = {\n ...conflict.operation,\n operationId: `${this.clientId}:${this.now()}:${createId()}`,\n ...(conflict.operation.type === \"upsert\" && chosen\n ? { collection: { ...chosen, ...(this.scope ? { scope: this.scope } : {}) } }\n : {}),\n createdAt: this.now(),\n baseRevision: conflict.revision,\n attempts: 0,\n };\n await this.replaceQueued(conflict.operation, retry);\n this.updateState({\n collectionConflicts: (this.state.collectionConflicts ?? []).filter((entry) => entry.operation.id !== id),\n });\n await this.flushSync();\n }\n\n dispose(): void {\n this.disposed = true;\n if (this.onlineHandler) window.removeEventListener(\"online\", this.onlineHandler);\n this.listeners.clear();\n this.dataListeners.clear();\n }\n\n private async runFlush(): Promise<void> {\n await this.loadQueue();\n if (this.disposed) return;\n if (!(await this.pullRemote())) return;\n if (this.queueItems.length === 0) {\n this.updateState({ status: \"synced\", pendingCount: 0, error: undefined });\n return;\n }\n this.updateState({ status: \"syncing\", error: undefined });\n for (const operation of [...this.queueItems]) {\n if (this.disposed) return;\n const isBlocked = [...this.rejectedOperations.values()].some(\n ({ operation: rejected }) =>\n rejected.operationId !== operation.operationId && dependsOnRejectedOperation(operation, rejected),\n );\n if (isBlocked) continue;\n try {\n if (isCollectionSyncOperation(operation)) {\n if (!this.remote.pushCollection) throw new Error(\"Remote sync driver does not support collection sync.\");\n const result = await this.pushCollectionWithRetry(operation);\n if (result?.type === \"conflict\" && result.resolution === \"manual\") {\n const conflict = createCollectionSyncConflict(operation, result);\n this.updateState({\n status: \"conflict\",\n collectionConflicts: [\n ...(this.state.collectionConflicts ?? []).filter((entry) => entry.operation.id !== operation.id),\n conflict,\n ],\n });\n continue;\n }\n await this.applyCollectionPushResult(operation, result);\n await this.removeQueued(operation.operationId);\n this.updateState({\n status: this.queueItems.length > 0 ? \"syncing\" : \"synced\",\n lastSyncedAt: this.now(),\n });\n continue;\n }\n if (isMembershipSyncOperation(operation)) {\n if (!this.remote.pushMembership) throw new Error(\"Remote sync driver does not support membership sync.\");\n await this.pushMembershipWithRetry(operation);\n await this.removeQueued(operation.operationId);\n this.updateState({\n status: this.queueItems.length > 0 ? \"syncing\" : \"synced\",\n lastSyncedAt: this.now(),\n });\n continue;\n }\n const result = await this.pushWithRetry(operation);\n if (result.type === \"conflict\") {\n const local = operation.item;\n const resolved = this.resolveConflict\n ? await this.resolveConflict(local, result.remote, {\n operation,\n remoteRevision: result.revision,\n })\n : undefined;\n if (!resolved) {\n const conflict: KeepSyncConflict<TMeta> = {\n id: operation.id,\n operation,\n remote: result.remote,\n ...(result.revision ? { revision: result.revision } : {}),\n };\n this.conflicts.set(operation.id, conflict);\n this.updateState({\n status: \"conflict\",\n conflictIds: [...this.conflicts.keys()],\n conflicts: [...this.conflicts.values()],\n });\n continue;\n }\n const retry = this.createOperation(\"upsert\", resolved.id, {\n ...resolved,\n revision: result.revision ?? resolved.revision,\n });\n await this.local.set(this.applyScope(retry.item as KeepItem<TMeta>));\n await this.replaceQueued(operation, retry);\n continue;\n }\n if (result.item) {\n await this.local.set(\n this.applyScope({\n ...result.item,\n ...(result.revision ? { revision: result.revision } : {}),\n }),\n );\n this.notifyDataListeners();\n }\n await this.removeQueued(operation.operationId);\n this.updateState({\n status: this.queueItems.length > 0 ? \"syncing\" : \"synced\",\n lastSyncedAt: this.now(),\n conflictIds: [...this.conflicts.keys()].filter((id) => id !== operation.id),\n conflicts: [...this.conflicts.values()].filter((conflict) => conflict.id !== operation.id),\n });\n } catch (error) {\n if (isPermanentSyncError(error)) {\n this.rejectedOperations.set(operation.operationId, { operation, error });\n this.updateState({ status: \"syncing\" });\n continue;\n }\n this.updateState({ status: \"error\", error });\n return;\n }\n }\n if (this.rejectedOperations.size > 0) {\n const rejected = [...this.rejectedOperations.values()];\n this.updateState({\n status: \"error\",\n error: rejected[rejected.length - 1]?.error,\n rejectedOperations: rejected,\n });\n } else if (this.queueItems.length === 0) {\n this.updateState({ status: \"synced\", pendingCount: 0 });\n }\n }\n\n private createOperation(\n type: SyncOperation<TMeta>[\"type\"],\n id: string,\n item?: KeepItem<TMeta>,\n ): SyncOperation<TMeta> {\n return {\n operationId: `${this.clientId}:${this.now()}:${createId()}`,\n type,\n id,\n ...(item ? { item } : {}),\n createdAt: this.now(),\n ...(item?.revision ? { baseRevision: item.revision } : {}),\n ...(this.scope ? { scope: this.scope } : {}),\n };\n }\n\n private createCollectionOperation(\n type: KeepCollectionSyncOperation[\"type\"],\n id: string,\n collection?: KeepCollectionDefinition,\n baseRevision?: string,\n ): KeepCollectionSyncOperation {\n return {\n operationId: `${this.clientId}:${this.now()}:${createId()}`,\n type,\n entity: \"collection\",\n id,\n ...(collection ? { collection } : {}),\n createdAt: this.now(),\n ...(baseRevision ? { baseRevision } : {}),\n ...(this.scope ? { scope: this.scope } : {}),\n };\n }\n\n private createMembershipOperation(\n type: KeepMembershipSyncOperation[\"type\"],\n collectionId: string,\n itemId: string,\n membership?: KeepCollectionMembership,\n ): KeepMembershipSyncOperation {\n return {\n operationId: `${this.clientId}:${this.now()}:${createId()}`,\n type,\n entity: \"membership\",\n id: getMembershipId(collectionId, itemId),\n collectionId,\n itemId,\n ...(membership ? { membership } : {}),\n createdAt: this.now(),\n ...(this.scope ? { scope: this.scope } : {}),\n };\n }\n\n private applyScope(item: KeepItem<TMeta>): KeepItem<TMeta> {\n return this.scope ? { ...item, scope: this.scope } : item;\n }\n\n private async removeLocalItems(ids: string[]): Promise<void> {\n // An explicit empty scope limits built-in adapters to unscoped records instead of every record with the same ID.\n const scope = this.scope ?? this.local.scope ?? {};\n if (this.local.removeMany) {\n await this.local.removeMany(ids, scope);\n return;\n }\n for (const id of ids) await this.local.remove(id, scope);\n }\n\n private async pushWithRetry(operation: SyncOperation<TMeta>): Promise<RemoteSyncResult<TMeta>> {\n let attempt = 0;\n while (true) {\n try {\n return await this.remote.push({ ...operation, attempts: attempt });\n } catch (error) {\n if (isKeepSyncAuthError(error) || isPermanentSyncError(error) || attempt >= this.maxRetries) throw error;\n attempt += 1;\n const delay = this.retryDelayMs * this.retryBackoff ** (attempt - 1);\n if (delay > 0) await wait(delay);\n }\n }\n }\n\n private async pushCollectionWithRetry(\n operation: KeepCollectionSyncOperation,\n // biome-ignore lint/suspicious/noConfusingVoidType: Preserve drivers whose collection push returns void.\n ): Promise<void | KeepCollectionSyncResult> {\n let attempt = 0;\n while (true) {\n try {\n return await this.remote.pushCollection?.({ ...operation, attempts: attempt });\n } catch (error) {\n if (isKeepSyncAuthError(error) || isPermanentSyncError(error) || attempt >= this.maxRetries) throw error;\n attempt += 1;\n const delay = this.retryDelayMs * this.retryBackoff ** (attempt - 1);\n if (delay > 0) await wait(delay);\n }\n }\n }\n\n private async applyCollectionPushResult(\n operation: KeepCollectionSyncOperation,\n // biome-ignore lint/suspicious/noConfusingVoidType: A legacy driver signals success by returning void.\n result: void | KeepCollectionSyncResult,\n ): Promise<void> {\n if (!this.local.getCollections || !this.local.setCollection || !this.local.removeCollection) return;\n if (!result) return;\n const outcome = result.type === \"conflict\" ? result.resolution : \"remote\";\n if (outcome === \"manual\") return;\n const deleted =\n outcome === \"local\"\n ? operation.type === \"remove\"\n : (result.deleted ?? (operation.type === \"remove\" && outcome === \"remote\"));\n if (deleted) {\n await this.local.removeCollection(operation.id, this.scope);\n } else if (result.type === \"synced\" || outcome === \"remote\" || outcome === \"local\") {\n const current =\n (outcome === \"local\" ? operation.collection : result.collection) ??\n (await this.getCollections?.())?.find((entry) => entry.id === operation.id);\n if (!current) return;\n await this.local.setCollection({\n ...current,\n ...(result.revision ? { revision: result.revision } : current.revision ? { revision: current.revision } : {}),\n ...(this.scope ? { scope: this.scope } : {}),\n });\n }\n if (result.type === \"conflict\") {\n const conflict = createCollectionSyncConflict(operation, result);\n this.updateState({\n status: \"conflict\",\n collectionConflicts: [\n ...(this.state.collectionConflicts ?? []).filter((entry) => entry.operation.id !== operation.id),\n conflict,\n ],\n });\n }\n }\n\n private async pushMembershipWithRetry(operation: KeepMembershipSyncOperation): Promise<void> {\n let attempt = 0;\n while (true) {\n try {\n await this.remote.pushMembership?.({ ...operation, attempts: attempt });\n return;\n } catch (error) {\n if (isKeepSyncAuthError(error) || isPermanentSyncError(error) || attempt >= this.maxRetries) throw error;\n attempt += 1;\n const delay = this.retryDelayMs * this.retryBackoff ** (attempt - 1);\n if (delay > 0) await wait(delay);\n }\n }\n }\n\n private async enqueueBeforeLocalWrite(operation: KeepSyncQueueOperation<TMeta>): Promise<void> {\n await this.enqueueManyBeforeLocalWrite([operation]);\n }\n\n private async enqueueManyBeforeLocalWrite(operations: KeepSyncQueueOperation<TMeta>[]): Promise<void> {\n await this.loadQueue();\n const next = [...this.queueItems];\n for (const operation of operations) {\n for (let index = next.length - 1; index >= 0; index -= 1) {\n const queued = next[index];\n if (!queued || getQueueIdentity(queued) !== getQueueIdentity(operation)) continue;\n next.splice(index, 1);\n }\n next.push(operation);\n }\n await this.persistQueue(next);\n this.updateState({ status: \"pending\", pendingCount: this.queueItems.length });\n }\n\n private async loadQueue(): Promise<void> {\n if (this.queueLoaded) return;\n if (!this.queueLoadPromise) {\n this.queueLoadPromise = this.queue\n .getAll()\n .then((items) => {\n this.queueItems = items;\n this.queueLoaded = true;\n })\n .catch((error) => {\n this.queueLoadPromise = undefined;\n throw error;\n });\n }\n await this.queueLoadPromise;\n }\n\n private async resumeQueue(): Promise<void> {\n try {\n await this.loadQueue();\n if (this.disposed) return;\n if (this.queueItems.length === 0) return;\n this.updateState({ status: \"pending\", pendingCount: this.queueItems.length });\n if (isBrowserOnline()) await this.flushSync();\n } catch (error) {\n this.updateState({ status: \"error\", error });\n }\n }\n\n private async persistQueue(next: KeepSyncQueueOperation<TMeta>[]): Promise<void> {\n const previousById = new Map(this.queueItems.map((operation) => [operation.operationId, operation]));\n const nextById = new Map(next.map((operation) => [operation.operationId, operation]));\n const removed = [...previousById.keys()].filter((id) => !nextById.has(id));\n if (removed.length > 0) await this.queue.remove(removed);\n const changed = next.filter((operation) => previousById.get(operation.operationId) !== operation);\n if (changed.length > 0) await this.queue.setMany(changed);\n this.queueItems = next;\n }\n\n private async removeQueued(operationIds: string | string[]): Promise<void> {\n await this.loadQueue();\n const ids = new Set(typeof operationIds === \"string\" ? [operationIds] : operationIds);\n await this.queue.remove([...ids]);\n this.queueItems = this.queueItems.filter((operation) => !ids.has(operation.operationId));\n for (const id of ids) this.rejectedOperations.delete(id);\n this.setPendingState();\n }\n\n private async replaceQueued(previous: SyncOperation<TMeta>, next: SyncOperation<TMeta>): Promise<void> {\n await this.persistQueue(\n this.queueItems.map((operation) => (operation.operationId === previous.operationId ? next : operation)),\n );\n this.setPendingState();\n }\n\n private setPendingState(): void {\n const rejected = [...this.rejectedOperations.values()];\n this.updateState({\n status: rejected.length > 0 ? \"error\" : this.queueItems.length > 0 ? \"pending\" : \"synced\",\n pendingCount: this.queueItems.length,\n ...(rejected.length > 0 ? { error: rejected[rejected.length - 1]?.error } : { error: undefined }),\n rejectedOperations: rejected,\n });\n }\n\n private async pullRemote(): Promise<boolean> {\n if (!this.remote.pull && !this.remote.pullCollections && !this.remote.pullMemberships) return true;\n try {\n if (this.remote.pull) {\n const remoteItems = await this.remote.pull();\n const pendingIds = new Set(\n this.queueItems.filter((operation) => operation.entity !== \"collection\").map((operation) => operation.id),\n );\n const localItems = await this.getAll();\n const localById = new Map(localItems.map((item) => [item.id, item]));\n const remoteIds = new Set<string>();\n const remoteById = new Map<string, KeepItem<TMeta>>();\n for (const item of remoteItems) {\n if (this.scope && item.scope && !sameScope(item.scope, this.scope)) continue;\n remoteIds.add(item.id);\n if (pendingIds.has(item.id)) continue;\n const previous = remoteById.get(item.id);\n remoteById.set(item.id, previous ? (mergeKeepItemLists([item], [previous])[0] ?? item) : item);\n }\n const incoming = [...remoteById.values()].flatMap((item) => {\n const merged = mergePulledItem(item, localById.get(item.id));\n return merged ? [this.applyScope(merged)] : [];\n });\n const removedIds =\n this.itemPullMode === \"snapshot\"\n ? getSnapshotRemovals(localItems, remoteIds, pendingIds, this.scope ?? this.local.scope)\n : [];\n if (incoming.length > 0) await persistKeepItems(this.local, incoming);\n if (removedIds.length > 0) await this.removeLocalItems(removedIds);\n if (incoming.length > 0 || removedIds.length > 0) this.notifyDataListeners();\n }\n if (\n this.remote.pullCollections &&\n this.local.getCollections &&\n this.local.setCollection &&\n this.local.removeCollection\n ) {\n const remoteCollections = await this.remote.pullCollections();\n const localCollections = await this.local.getCollections();\n const pendingIds = new Set(this.queueItems.filter(isCollectionSyncOperation).map((operation) => operation.id));\n const remoteById = new Map(\n remoteCollections\n .filter((collection) => !this.scope || !collection.scope || sameScope(collection.scope, this.scope))\n .map((collection) => [collection.id, collection]),\n );\n for (const collection of remoteById.values()) {\n if (pendingIds.has(collection.id)) continue;\n await this.local.setCollection({ ...collection, ...(this.scope ? { scope: this.scope } : {}) });\n }\n for (const collection of localCollections) {\n if (pendingIds.has(collection.id) || remoteById.has(collection.id)) continue;\n if (this.scope && !sameScope(collection.scope, this.scope)) continue;\n await this.local.removeCollection(collection.id, this.scope);\n }\n this.notifyDataListeners();\n }\n if (\n this.remote.pullMemberships &&\n this.getCollections &&\n this.local.getCollectionMemberships &&\n this.local.setCollectionMembership &&\n this.local.removeCollectionMembership\n ) {\n const remoteMemberships = await this.remote.pullMemberships();\n const localMemberships = await this.local.getCollectionMemberships();\n const pendingIds = new Set(this.queueItems.filter(isMembershipSyncOperation).map((operation) => operation.id));\n const itemIds = new Set((await this.getAll()).map((item) => item.id));\n const collectionIds = new Set((await this.getCollections()).map((collection) => collection.id));\n const remoteById = new Map(\n remoteMemberships\n .filter((membership) => {\n if (this.scope && membership.scope && !sameScope(membership.scope, this.scope)) return false;\n if (!itemIds.has(membership.itemId)) return false;\n return collectionIds.has(membership.collectionId);\n })\n .map((membership) => [getMembershipId(membership.collectionId, membership.itemId), membership]),\n );\n for (const membership of remoteById.values()) {\n const id = getMembershipId(membership.collectionId, membership.itemId);\n if (pendingIds.has(id)) continue;\n await this.local.setCollectionMembership({ ...membership, ...(this.scope ? { scope: this.scope } : {}) });\n }\n for (const membership of localMemberships) {\n const id = getMembershipId(membership.collectionId, membership.itemId);\n if (pendingIds.has(id) || remoteById.has(id)) continue;\n if (this.scope && !sameScope(membership.scope, this.scope)) continue;\n await this.local.removeCollectionMembership(membership.collectionId, membership.itemId, this.scope);\n }\n this.notifyDataListeners();\n }\n return true;\n } catch (error) {\n this.updateState({ status: \"error\", error });\n return false;\n }\n }\n\n private notifyDataListeners(): void {\n for (const listener of this.dataListeners) listener();\n }\n\n private updateState(next: Partial<KeepSyncState<TMeta>>): void {\n const state: KeepSyncState<TMeta> = {\n ...this.state,\n ...next,\n pendingCount: next.pendingCount ?? this.queueItems.length,\n };\n const rejected = [...this.rejectedOperations.values()];\n if (rejected.length > 0) state.rejectedOperations = rejected;\n else delete state.rejectedOperations;\n this.state = state;\n for (const listener of this.listeners) listener();\n }\n}\n\nfunction isSyncOperation(value: unknown): value is SyncOperation {\n if (!isRecord(value)) return false;\n return (\n typeof value.operationId === \"string\" &&\n (value.type === \"upsert\" || value.type === \"remove\") &&\n typeof value.id === \"string\" &&\n typeof value.createdAt === \"number\" &&\n (value.entity === undefined || value.entity === \"item\" || value.entity === \"collection\") &&\n (value.collection === undefined || isKeepCollectionDefinition(value.collection)) &&\n (value.entity !== \"collection\" || value.type !== \"upsert\" || isKeepCollectionDefinition(value.collection))\n );\n}\n\nfunction isCollectionSyncOperation(value: unknown): value is KeepCollectionSyncOperation {\n if (!isRecord(value)) return false;\n return (\n typeof value.operationId === \"string\" &&\n value.entity === \"collection\" &&\n (value.type === \"upsert\" || value.type === \"remove\") &&\n typeof value.id === \"string\" &&\n typeof value.createdAt === \"number\" &&\n (value.collection === undefined || isKeepCollectionDefinition(value.collection))\n );\n}\n\nfunction isMembershipSyncOperation(value: unknown): value is KeepMembershipSyncOperation {\n if (!isRecord(value)) return false;\n return (\n typeof value.operationId === \"string\" &&\n value.entity === \"membership\" &&\n (value.type === \"upsert\" || value.type === \"remove\") &&\n typeof value.id === \"string\" &&\n typeof value.collectionId === \"string\" &&\n typeof value.itemId === \"string\" &&\n typeof value.createdAt === \"number\" &&\n (value.membership === undefined || isKeepCollectionMembership(value.membership)) &&\n (value.type !== \"upsert\" || isKeepCollectionMembership(value.membership))\n );\n}\n\nfunction isSyncQueueOperation(value: unknown): value is KeepSyncQueueOperation {\n return isSyncOperation(value) || isCollectionSyncOperation(value) || isMembershipSyncOperation(value);\n}\n\nfunction getQueueIdentity<TMeta>(operation: KeepSyncQueueOperation<TMeta>): string {\n return `${operation.entity ?? \"item\"}:${operation.id}`;\n}\n\nfunction getMembershipId(collectionId: string, itemId: string): string {\n return `${collectionId}\\u0000${itemId}`;\n}\n\nfunction createCollectionSyncConflict(\n operation: KeepCollectionSyncOperation,\n result: Extract<KeepCollectionSyncResult, { type: \"conflict\" }>,\n): KeepCollectionSyncConflict {\n const details = {\n operation,\n resolution: result.resolution,\n ...(result.revision ? { revision: result.revision } : {}),\n };\n if (result.deleted) return { ...details, deleted: true };\n return { ...details, deleted: false, collection: result.collection };\n}\n\nfunction createId(): string {\n if (typeof crypto !== \"undefined\" && \"randomUUID\" in crypto) return crypto.randomUUID();\n return Math.random().toString(36).slice(2);\n}\n\nfunction getBrowserStorage(): Storage | undefined {\n if (typeof window === \"undefined\") return undefined;\n try {\n return window.localStorage;\n } catch {\n return undefined;\n }\n}\n\nfunction getBrowserIndexedDB(): IDBFactory | undefined {\n if (typeof indexedDB === \"undefined\") return undefined;\n return indexedDB;\n}\n\nfunction isBrowserOnline(): boolean {\n return typeof navigator === \"undefined\" || navigator.onLine !== false;\n}\n\nfunction createDefaultQueue<TMeta>(options: SyncStorageAdapterOptions<TMeta>): SyncQueueAdapter<TMeta> {\n const scopeKey = getScopeKey(options);\n const queueKey = `${options.queueKey ?? `${DEFAULT_SYNC_QUEUE_KEY}:${options.local.storageKey ?? \"default\"}`}${scopeKey}`;\n const fallback = new LocalStorageSyncQueueAdapter<TMeta>({ key: queueKey });\n const indexedDB = getBrowserIndexedDB();\n if (!indexedDB) return fallback;\n return new FallbackSyncQueueAdapter<TMeta>({\n primary: new IndexedDBSyncQueueAdapter<TMeta>({\n databaseName: `${options.queueDatabaseName ?? DEFAULT_SYNC_QUEUE_DATABASE}${scopeKey}`,\n indexedDB,\n }),\n fallback,\n });\n}\n\nfunction getSyncScope<TMeta>(options: SyncStorageAdapterOptions<TMeta>): SyncScope | undefined {\n if (options.scope) return options.scope;\n if (!options.userId && !options.tenantId) return undefined;\n return {\n ...(options.userId ? { userId: options.userId } : {}),\n ...(options.tenantId ? { tenantId: options.tenantId } : {}),\n };\n}\n\nfunction getScopeKey<TMeta>(options: SyncStorageAdapterOptions<TMeta>): string {\n const scope = getSyncScope(options);\n if (!scope) return \"\";\n return `:${encodeURIComponent(scope.tenantId ?? \"_\")}:${encodeURIComponent(scope.userId ?? \"_\")}`;\n}\n\nfunction sameScope(left: SyncScope | undefined, right: SyncScope): boolean {\n return left?.userId === right.userId && left?.tenantId === right.tenantId;\n}\n\n/** Returns the item to store after a pull, or undefined when the local copy is newer. */\nfunction mergePulledItem<TMeta>(\n remote: KeepItem<TMeta>,\n current: KeepItem<TMeta> | undefined,\n): KeepItem<TMeta> | undefined {\n if (!current) return remote;\n if (remote.revision !== undefined && current.revision !== undefined && remote.revision !== current.revision) {\n // A different server revision is authoritative even when device clocks make its content look older.\n const lastOpenedAt = Math.max(remote.lastOpenedAt ?? 0, current.lastOpenedAt ?? 0);\n return lastOpenedAt > 0 ? { ...remote, lastOpenedAt } : remote;\n }\n if (remote.updatedAt < current.updatedAt && (remote.lastOpenedAt ?? 0) <= (current.lastOpenedAt ?? 0)) {\n return undefined;\n }\n return mergeKeepItemLists([remote], [current])[0] ?? remote;\n}\n\n/** Only server-acknowledged records without pending writes can be removed by an item snapshot. */\nfunction getSnapshotRemovals<TMeta>(\n localItems: KeepItem<TMeta>[],\n remoteIds: Set<string>,\n pendingIds: Set<string>,\n scope: SyncScope | undefined,\n): string[] {\n const isRemovable = (item: KeepItem<TMeta>) =>\n isSameKeepScope(item.scope, scope) &&\n item.revision !== undefined &&\n !remoteIds.has(item.id) &&\n !pendingIds.has(item.id);\n return localItems.filter(isRemovable).map((item) => item.id);\n}\n\nfunction isPermanentSyncError(error: unknown): boolean {\n const status = getHttpStatus(error);\n return (\n status !== undefined &&\n status >= 400 &&\n status < 500 &&\n status !== 401 &&\n status !== 403 &&\n status !== 408 &&\n status !== 425 &&\n status !== 429\n );\n}\n\nfunction dependsOnRejectedOperation<TMeta>(\n operation: KeepSyncQueueOperation<TMeta>,\n rejected: KeepSyncQueueOperation<TMeta>,\n): boolean {\n if (isMembershipSyncOperation(rejected)) {\n if (isMembershipSyncOperation(operation)) return operation.id === rejected.id;\n if (isCollectionSyncOperation(operation)) return operation.id === rejected.collectionId;\n return operation.id === rejected.itemId;\n }\n if (isMembershipSyncOperation(operation)) {\n return isCollectionSyncOperation(rejected)\n ? operation.collectionId === rejected.id\n : operation.itemId === rejected.id;\n }\n if (isCollectionSyncOperation(operation)) {\n return isCollectionSyncOperation(rejected) && operation.id === rejected.id;\n }\n return !isCollectionSyncOperation(rejected) && operation.id === rejected.id;\n}\n\nfunction getHttpStatus(error: unknown): number | undefined {\n const seen = new Set<object>();\n while (isRecord(error) && !seen.has(error)) {\n seen.add(error);\n if (typeof error.status === \"number\") return error.status;\n if (isRecord(error.response) && typeof error.response.status === \"number\") return error.response.status;\n error = error.cause;\n }\n return undefined;\n}\n\nfunction wait(delay: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, delay));\n}\n\nfunction requestToPromise<T>(request: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n}\n\nfunction transactionToPromise(transaction: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => reject(transaction.error);\n transaction.onabort = () => reject(transaction.error ?? new Error(\"IndexedDB transaction aborted.\"));\n });\n}\n","import {\n type KeepCollectionDefinition,\n type KeepCollectionMembership,\n type KeepItem,\n KeepStorageAccessError,\n KeepStorageError,\n type KeepStorageOperation,\n KeepStorageParseError,\n KeepStorageQuotaError,\n type StorageAdapter,\n} from \"../features/items/types\";\nimport {\n isKeepCollectionDefinition,\n isKeepCollectionMembership,\n isKeepItemArray,\n isRecord,\n mergeKeepItemLists,\n persistKeepItems,\n} from \"../features/persistence/helpers\";\nimport {\n createScopedStorageAdapter,\n getKeepScopeKey,\n isSameKeepScope,\n type KeepScope,\n} from \"../features/persistence/scope\";\nimport { serializeKeepStorage } from \"../features/persistence/serialization\";\nimport {\n type FallbackRecoveryJournal,\n type KeepStorageRecovery,\n LocalStorageRecoveryJournal,\n RecoveryJournalController,\n} from \"./recovery-journal\";\n\nexport type {\n FallbackRecoveryJournal,\n FallbackRecoveryJournalState,\n FallbackRecoveryJournalV2,\n FallbackRecoveryOperation,\n FallbackRecoverySnapshot,\n KeepRecoveryInspection,\n KeepRecoveryResult,\n KeepRecoveryRow,\n KeepRecoveryState,\n KeepStorageRecovery,\n} from \"./recovery-journal\";\nexport { LocalStorageRecoveryJournal } from \"./recovery-journal\";\n\nexport const DEFAULT_STORAGE_KEY = \"keepkit:items\";\n\nexport type LocalStorageAdapterOptions = {\n key?: string;\n storage?: Storage;\n};\n\nexport type IndexedDBAdapterOptions = {\n databaseName?: string;\n dbName?: string;\n /** Alias for databaseName, useful when switching from LocalStorageAdapter. */\n key?: string;\n storeName?: string;\n version?: number;\n indexedDB?: IDBFactory;\n};\n\nexport const DEFAULT_INDEXEDDB_DATABASE = \"keepkit\";\nexport const DEFAULT_INDEXEDDB_STORE = \"items\";\n\nexport type StorageAdapterFactoryOptions<TMeta = Record<string, unknown>> = {\n getAll: () => KeepItem<TMeta>[] | Promise<KeepItem<TMeta>[]>;\n getCollections?: () => KeepCollectionDefinition[] | Promise<KeepCollectionDefinition[]>;\n setCollection?: (collection: KeepCollectionDefinition) => void | Promise<void>;\n removeCollection?: (id: string, scope?: KeepScope) => void | Promise<void>;\n getCollectionMemberships?: () => KeepCollectionMembership[] | Promise<KeepCollectionMembership[]>;\n setCollectionMembership?: (membership: KeepCollectionMembership) => void | Promise<void>;\n removeCollectionMembership?: (collectionId: string, itemId: string, scope?: KeepScope) => void | Promise<void>;\n set: (item: KeepItem<TMeta>) => void | Promise<void>;\n setMany?: (items: KeepItem<TMeta>[]) => void | Promise<void>;\n remove: (id: string, scope?: KeepScope) => void | Promise<void>;\n removeMany?: (ids: string[], scope?: KeepScope) => void | Promise<void>;\n clear: () => void | Promise<void>;\n merge?: (localItems: KeepItem<TMeta>[]) => KeepItem<TMeta>[] | Promise<KeepItem<TMeta>[]>;\n subscribe?: (listener: () => void) => undefined | (() => void);\n storageKey?: string;\n};\n\nexport type FallbackStorageAdapterOptions<TMeta = Record<string, unknown>> = {\n primary?: StorageAdapter<TMeta>;\n scope?: KeepScope;\n fallback: StorageAdapter<TMeta>;\n /** Persist fallback-only operations and replay them before returning to the primary. */\n recoveryJournal?: FallbackRecoveryJournal<TMeta>;\n /** Decide which primary adapter failures should activate the fallback. */\n shouldFallback?: (error: unknown) => boolean;\n onFallback?: (error: unknown) => void;\n /** Copy fallback data into an empty primary on the first read. */\n migrateFallbackOnEmpty?: boolean;\n /** Keep the fallback current while the primary is healthy. */\n mirrorWrites?: boolean;\n};\n\n/**\n * A storage adapter that switches to a fallback after an availability failure.\n * Parse errors remain visible so corrupt data is never silently hidden.\n */\nexport class FallbackStorageAdapter<TMeta = Record<string, unknown>> implements StorageAdapter<TMeta> {\n public readonly storageKey: string | undefined;\n public readonly scope: KeepScope | undefined;\n readonly getCollections?: () => Promise<KeepCollectionDefinition[]>;\n readonly setCollection?: (collection: KeepCollectionDefinition) => Promise<void>;\n readonly removeCollection?: (id: string, scope?: KeepScope) => Promise<void>;\n readonly getCollectionMemberships?: () => Promise<KeepCollectionMembership[]>;\n readonly setCollectionMembership?: (membership: KeepCollectionMembership) => Promise<void>;\n readonly removeCollectionMembership?: (collectionId: string, itemId: string, scope?: KeepScope) => Promise<void>;\n private readonly primary: StorageAdapter<TMeta>;\n private readonly fallback: StorageAdapter<TMeta>;\n private readonly shouldFallback: (error: unknown) => boolean;\n private readonly onFallback?: (error: unknown) => void;\n private readonly migrateFallbackOnEmpty: boolean;\n private readonly mirrorWrites: boolean;\n readonly recovery?: KeepStorageRecovery<TMeta>;\n private readonly journalController: RecoveryJournalController<TMeta> | undefined;\n private active: \"primary\" | \"fallback\" = \"primary\";\n private readonly listeners = new Set<() => void>();\n\n constructor(options: FallbackStorageAdapterOptions<TMeta>) {\n const scope = options.scope ?? options.primary?.scope ?? options.fallback.scope;\n const primary = options.primary && scope ? createScopedStorageAdapter(options.primary, scope) : options.primary;\n this.fallback = scope ? createScopedStorageAdapter(options.fallback, scope) : options.fallback;\n this.primary = primary ?? this.fallback;\n this.shouldFallback = options.shouldFallback ?? isRecoverableStorageError;\n this.onFallback = options.onFallback;\n this.migrateFallbackOnEmpty = options.migrateFallbackOnEmpty ?? false;\n this.mirrorWrites = options.mirrorWrites ?? false;\n this.storageKey = options.fallback.storageKey ?? options.primary?.storageKey;\n this.scope = scope;\n if (!options.primary) this.active = \"fallback\";\n if (options.recoveryJournal) {\n this.journalController = new RecoveryJournalController({\n primary,\n fallback: this.fallback,\n scope: this.scope,\n migrateFallbackOnEmpty: this.migrateFallbackOnEmpty,\n journal: options.recoveryJournal,\n shouldFallback: this.shouldFallback,\n mirrorWrites: this.mirrorWrites,\n onSourceChange: (source, error) => {\n this.active = source;\n if (source === \"fallback\" && error !== undefined) this.reportFallbackError(error);\n this.notifyListeners();\n },\n onError: (error) => this.reportFallbackError(error),\n });\n this.recovery = this.journalController;\n }\n if (\n this.primary.getCollections &&\n this.primary.setCollection &&\n this.primary.removeCollection &&\n this.fallback.getCollections &&\n this.fallback.setCollection &&\n this.fallback.removeCollection\n ) {\n const fallbackGetCollections = this.fallback.getCollections.bind(this.fallback);\n this.getCollections = async () => {\n if (this.journalController) return this.journalController.readCollections();\n const collections = await this.execute((adapter) => {\n if (!adapter.getCollections) throw new Error(\"Collection storage is unavailable.\");\n return adapter.getCollections();\n });\n if (this.active === \"primary\" && this.migrateFallbackOnEmpty && collections.length === 0) {\n const fallbackCollections = await fallbackGetCollections();\n for (const collection of fallbackCollections) await this.setCollection?.(collection);\n return fallbackCollections;\n }\n return collections;\n };\n this.setCollection = (collection) => {\n const value = this.scope ? { ...collection, scope: this.scope } : collection;\n return (\n this.journalController?.write({ type: \"setCollection\", collection: value }) ??\n this.executeWrite((adapter) => {\n if (!adapter.setCollection) throw new Error(\"Collection storage is unavailable.\");\n return adapter.setCollection(value);\n })\n );\n };\n this.removeCollection = (id, scope = this.scope) =>\n this.journalController?.write({ type: \"removeCollection\", id, scope }) ??\n this.executeWrite((adapter) => {\n if (!adapter.removeCollection) throw new Error(\"Collection storage is unavailable.\");\n return adapter.removeCollection(id, scope);\n });\n }\n if (\n this.primary.getCollectionMemberships &&\n this.primary.setCollectionMembership &&\n this.primary.removeCollectionMembership &&\n this.fallback.getCollectionMemberships &&\n this.fallback.setCollectionMembership &&\n this.fallback.removeCollectionMembership\n ) {\n const fallbackGetMemberships = this.fallback.getCollectionMemberships.bind(this.fallback);\n this.getCollectionMemberships = async () => {\n if (this.journalController) return this.journalController.readMemberships();\n const memberships = await this.execute(\n (adapter) => adapter.getCollectionMemberships?.() ?? Promise.resolve([]),\n );\n if (this.active !== \"primary\" || !this.migrateFallbackOnEmpty || memberships.length > 0) return memberships;\n const fallbackMemberships = await fallbackGetMemberships();\n for (const membership of fallbackMemberships) await this.setCollectionMembership?.(membership);\n return fallbackMemberships;\n };\n this.setCollectionMembership = (membership) => {\n const value = this.scope ? { ...membership, scope: this.scope } : membership;\n return (\n this.journalController?.write({ type: \"setMembership\", membership: value }) ??\n this.executeWrite((adapter) => adapter.setCollectionMembership?.(value) ?? Promise.resolve())\n );\n };\n this.removeCollectionMembership = (collectionId, itemId, scope = this.scope) =>\n this.journalController?.write({ type: \"removeMembership\", collectionId, itemId, scope }) ??\n this.executeWrite(\n (adapter) => adapter.removeCollectionMembership?.(collectionId, itemId, scope) ?? Promise.resolve(),\n );\n }\n }\n\n get isUsingFallback(): boolean {\n return this.active === \"fallback\";\n }\n\n getAll(): Promise<KeepItem<TMeta>[]> {\n return this.readAll();\n }\n\n set(item: KeepItem<TMeta>): Promise<void> {\n if (this.scope) item = { ...item, scope: this.scope };\n if (this.journalController)\n return this.journalController.write({ type: \"setItems\", items: [item] }, (adapter) => adapter.set(item));\n return this.executeWrite((adapter) => adapter.set(item));\n }\n\n setMany(items: KeepItem<TMeta>[]): Promise<void> {\n if (this.scope) items = items.map((item) => ({ ...item, scope: this.scope }));\n if (this.journalController) return this.journalController.write({ type: \"setItems\", items });\n return this.executeWrite((adapter) =>\n adapter.setMany\n ? adapter.setMany(items)\n : Promise.all(items.map((item) => adapter.set(item))).then(() => undefined),\n );\n }\n\n remove(id: string, scope: KeepScope | undefined = this.scope): Promise<void> {\n if (this.journalController)\n return this.journalController.write({ type: \"removeItems\", ids: [id], scope }, (adapter) =>\n adapter.remove(id, scope),\n );\n return this.executeWrite((adapter) => adapter.remove(id, scope));\n }\n\n removeMany(ids: string[], scope: KeepScope | undefined = this.scope): Promise<void> {\n if (this.journalController) return this.journalController.write({ type: \"removeItems\", ids, scope });\n return this.executeWrite((adapter) =>\n adapter.removeMany\n ? adapter.removeMany(ids, scope)\n : Promise.all(ids.map((id) => adapter.remove(id, scope))).then(() => undefined),\n );\n }\n\n clear(): Promise<void> {\n if (this.journalController) return this.journalController.write({ type: \"clearItems\" });\n return this.executeWrite((adapter) => adapter.clear());\n }\n\n merge(localItems: KeepItem<TMeta>[]): Promise<KeepItem<TMeta>[]> {\n if (this.scope) localItems = localItems.map((item) => ({ ...item, scope: this.scope }));\n if (this.journalController) return this.journalController.merge(localItems);\n return this.execute(async (adapter) => {\n const merged = adapter.merge\n ? await adapter.merge(localItems)\n : mergeKeepItemLists(await adapter.getAll(), localItems);\n if (!adapter.merge) await persistKeepItems(adapter, merged);\n if (this.active === \"primary\" && this.mirrorWrites) {\n try {\n await persistKeepItems(this.fallback, merged);\n } catch {\n // The fallback is best-effort while the primary is healthy.\n }\n }\n return merged;\n });\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n const notify = (source: \"primary\" | \"fallback\") => {\n if (source === this.active) listener();\n };\n const unsubscribePrimary = this.primary.subscribe?.(() => notify(\"primary\"));\n const unsubscribeFallback = this.fallback.subscribe?.(() => notify(\"fallback\"));\n const unsubscribeJournal = this.journalController?.subscribeJournalChanges(listener);\n return () => {\n this.listeners.delete(listener);\n unsubscribePrimary?.();\n unsubscribeFallback?.();\n unsubscribeJournal?.();\n };\n }\n\n private async readAll(): Promise<KeepItem<TMeta>[]> {\n if (this.journalController) return this.journalController.readItems();\n if (this.active === \"fallback\") return this.fallback.getAll();\n let items: KeepItem<TMeta>[];\n try {\n items = await this.primary.getAll();\n } catch (error) {\n if (!this.shouldFallback(error)) throw error;\n this.activateFallback(error);\n return this.fallback.getAll();\n }\n if (!this.migrateFallbackOnEmpty || items.length > 0) return items;\n\n const fallbackItems = await this.fallback.getAll();\n if (fallbackItems.length === 0) return items;\n try {\n await persistKeepItems(this.primary, fallbackItems);\n return fallbackItems;\n } catch (error) {\n if (!this.shouldFallback(error)) throw error;\n this.activateFallback(error);\n return fallbackItems;\n }\n }\n\n private activateFallback(error: unknown): void {\n this.active = \"fallback\";\n this.reportFallbackError(error);\n this.notifyListeners();\n }\n\n private reportFallbackError(error: unknown): void {\n try {\n this.onFallback?.(error);\n } catch {\n // Reporting cannot interrupt an accepted storage operation or later observers.\n }\n }\n\n private notifyListeners(): void {\n for (const listener of this.listeners) {\n try {\n listener();\n } catch {\n // Each observer receives the source change even if another observer fails.\n }\n }\n }\n\n private async executeWrite<TResult>(\n operation: (adapter: StorageAdapter<TMeta>) => Promise<TResult>,\n ): Promise<TResult> {\n const result = await this.execute(operation);\n if (this.active === \"primary\" && this.mirrorWrites) {\n try {\n await operation(this.fallback);\n } catch {\n // The fallback is best-effort while the primary is healthy.\n }\n }\n return result;\n }\n\n private async execute<TResult>(operation: (adapter: StorageAdapter<TMeta>) => Promise<TResult>): Promise<TResult> {\n const adapter = this.active === \"primary\" ? this.primary : this.fallback;\n try {\n return await operation(adapter);\n } catch (error) {\n if (this.active !== \"primary\" || !this.shouldFallback(error)) throw error;\n this.activateFallback(error);\n return operation(this.fallback);\n }\n }\n}\n\nexport type RecoveryJournalFactoryContext = {\n storageKey: string;\n lockKey: string;\n scope?: KeepScope;\n};\nexport type BrowserStorageAdapterOptions<TMeta = Record<string, unknown>> = {\n key?: string;\n databaseName?: string;\n storeName?: string;\n version?: number;\n indexedDB?: IDBFactory;\n storage?: Storage;\n scope?: KeepScope;\n createRecoveryJournal?: (context: RecoveryJournalFactoryContext) => FallbackRecoveryJournal<TMeta>;\n};\n\n/** IndexedDB-first browser storage with a scoped durable recovery checkpoint. */\nexport function createBrowserStorageAdapter<TMeta = Record<string, unknown>>(\n options: BrowserStorageAdapterOptions<TMeta> = {},\n): StorageAdapter<TMeta> {\n const browserIndexedDB = options.indexedDB ?? getBrowserIndexedDB();\n const scopeKey = getKeepScopeKey(options.scope);\n const storageKey = `${options.key ?? DEFAULT_STORAGE_KEY}${scopeKey}`;\n const fallback = new LocalStorageAdapter<TMeta>({ key: storageKey, storage: options.storage });\n const databaseName = options.databaseName ? `${options.databaseName}${scopeKey}` : DEFAULT_INDEXEDDB_DATABASE;\n const storeName = options.storeName ?? DEFAULT_INDEXEDDB_STORE;\n const primaryKey = JSON.stringify([databaseName, storeName]);\n const scopeIdentity = JSON.stringify([options.scope?.tenantId ?? null, options.scope?.userId ?? null]);\n const journalKey = `${fallback.storageKey}:recovery:${encodeURIComponent(primaryKey)}:${encodeURIComponent(scopeIdentity)}`;\n const lockKey = `recovery:${primaryKey}`;\n const legacyBackendKey = `${databaseName}:${storeName}`;\n const legacyJournalKey = `${fallback.storageKey}:recovery:${encodeURIComponent(legacyBackendKey)}`;\n const recoveryJournal =\n options.createRecoveryJournal?.({ storageKey: journalKey, lockKey, scope: options.scope }) ??\n createBrowserRecoveryJournal<TMeta>(\n journalKey,\n legacyJournalKey,\n lockKey,\n options.storage ?? getBrowserStorage(),\n options.scope,\n isAmbiguousLegacyBackend(legacyBackendKey, scopeKey),\n );\n const adapter = new FallbackStorageAdapter<TMeta>({\n primary: browserIndexedDB\n ? new IndexedDBAdapter<TMeta>({\n databaseName,\n storeName: options.storeName,\n version: options.version,\n indexedDB: browserIndexedDB,\n })\n : undefined,\n fallback,\n scope: options.scope,\n recoveryJournal,\n migrateFallbackOnEmpty: true,\n mirrorWrites: true,\n });\n return options.scope ? createScopedStorageAdapter(adapter, options.scope) : adapter;\n}\n\nfunction createBrowserRecoveryJournal<TMeta>(\n storageKey: string,\n legacyStorageKey: string,\n lockKey: string,\n storage: Storage | undefined,\n scope: KeepScope | undefined,\n ambiguousBackend: boolean,\n): FallbackRecoveryJournal<TMeta> {\n const journal = new LocalStorageRecoveryJournal<TMeta>(storageKey, storage, lockKey);\n const legacy = new LocalStorageRecoveryJournal<TMeta>(legacyStorageKey, storage, lockKey);\n return {\n read: async () => {\n const current = await journal.read();\n if (current !== undefined) return current;\n const previous = await legacy.read();\n if (previous && ambiguousBackend)\n throw new KeepStorageParseError({ operation: \"getAll\", storageKey: legacyStorageKey });\n // Scoped v1 factories never produced clearItems; the old key cannot identify its scope safely.\n if (scope && previous?.operations.some((operation) => operation.type === \"clearItems\"))\n throw new KeepStorageParseError({ operation: \"getAll\", storageKey: legacyStorageKey });\n return previous;\n },\n write: async (state) => {\n await journal.write(state);\n try {\n storage?.removeItem(legacyStorageKey);\n } catch {\n // The canonical journal is already durable and takes precedence over the retained legacy copy.\n }\n },\n runExclusive: (operation) => journal.runExclusive(operation),\n subscribe: (listener) => {\n if (typeof window === \"undefined\") return () => undefined;\n const onStorage = (event: StorageEvent) => {\n if (event.key === null || event.key === storageKey || event.key === legacyStorageKey) listener();\n };\n window.addEventListener(\"storage\", onStorage);\n return () => window.removeEventListener(\"storage\", onStorage);\n },\n };\n}\n\nfunction isAmbiguousLegacyBackend(backendKey: string, scopeKey: string): boolean {\n let candidates = 0;\n for (let index = 1; index < backendKey.length - 1; index += 1) {\n if (backendKey[index] !== \":\") continue;\n const databaseName = backendKey.slice(0, index);\n if (databaseName === DEFAULT_INDEXEDDB_DATABASE || !scopeKey || databaseName.endsWith(scopeKey)) candidates += 1;\n }\n return candidates !== 1;\n}\n\n/** Adapt sync or async persistence functions to the StorageAdapter contract. */\nexport function createStorageAdapter<TMeta = Record<string, unknown>>(\n options: StorageAdapterFactoryOptions<TMeta>,\n): StorageAdapter<TMeta> {\n const merge = options.merge;\n const subscribe = options.subscribe;\n const setMany = options.setMany;\n const removeMany = options.removeMany;\n const getCollections = options.getCollections;\n const setCollection = options.setCollection;\n const removeCollection = options.removeCollection;\n const getCollectionMemberships = options.getCollectionMemberships;\n const setCollectionMembership = options.setCollectionMembership;\n const removeCollectionMembership = options.removeCollectionMembership;\n return {\n getAll: async () => options.getAll(),\n ...(getCollections && setCollection && removeCollection\n ? {\n getCollections: async () => getCollections(),\n setCollection: async (collection: KeepCollectionDefinition) => setCollection(collection),\n removeCollection: async (id: string, scope?: KeepScope) => removeCollection(id, scope),\n }\n : {}),\n ...(getCollectionMemberships && setCollectionMembership && removeCollectionMembership\n ? {\n getCollectionMemberships: async () => getCollectionMemberships(),\n setCollectionMembership: async (membership: KeepCollectionMembership) => setCollectionMembership(membership),\n removeCollectionMembership: async (collectionId: string, itemId: string, scope?: KeepScope) =>\n removeCollectionMembership(collectionId, itemId, scope),\n }\n : {}),\n set: async (item) => options.set(item),\n ...(setMany ? { setMany: async (items: KeepItem<TMeta>[]) => setMany(items) } : {}),\n remove: async (id, scope) => options.remove(id, scope),\n ...(removeMany ? { removeMany: async (ids: string[], scope?: KeepScope) => removeMany(ids, scope) } : {}),\n clear: async () => options.clear(),\n ...(merge ? { merge: async (items: KeepItem<TMeta>[]) => merge(items) } : {}),\n ...(subscribe\n ? {\n subscribe: (listener: () => void) => subscribe(listener) ?? (() => undefined),\n }\n : {}),\n ...(options.storageKey ? { storageKey: options.storageKey } : {}),\n };\n}\n\nexport type { KeepScope } from \"../features/persistence/scope\";\nexport { createScopedStorageAdapter, ScopedStorageAdapter } from \"../features/persistence/scope\";\n\n/** An async StorageAdapter backed by browser localStorage. */\nexport class LocalStorageAdapter<TMeta = Record<string, unknown>> implements StorageAdapter<TMeta> {\n public readonly storageKey: string;\n private readonly storage: Storage | undefined;\n\n constructor(options: LocalStorageAdapterOptions = {}) {\n this.storageKey = options.key ?? DEFAULT_STORAGE_KEY;\n this.storage = options.storage ?? getBrowserStorage();\n }\n\n async getAll(): Promise<KeepItem<TMeta>[]> {\n if (!this.storage) return [];\n\n let raw: string | null;\n try {\n raw = this.storage.getItem(this.storageKey);\n } catch (cause) {\n throw new KeepStorageAccessError({\n operation: \"getAll\",\n storageKey: this.storageKey,\n cause,\n });\n }\n\n if (!raw) return [];\n\n try {\n const value: unknown = JSON.parse(raw);\n if (!isKeepItemArray(value)) {\n throw new KeepStorageParseError({\n operation: \"getAll\",\n storageKey: this.storageKey,\n });\n }\n return value as KeepItem<TMeta>[];\n } catch (cause) {\n if (cause instanceof KeepStorageParseError) throw cause;\n throw new KeepStorageParseError({\n operation: \"getAll\",\n storageKey: this.storageKey,\n cause,\n });\n }\n }\n\n async getCollections(): Promise<KeepCollectionDefinition[]> {\n if (!this.storage) return [];\n const storageKey = `${this.storageKey}:collections`;\n let raw: string | null;\n try {\n raw = this.storage.getItem(storageKey);\n } catch (cause) {\n throw new KeepStorageAccessError({ operation: \"getAll\", storageKey, cause });\n }\n if (!raw) return [];\n try {\n const value: unknown = JSON.parse(raw);\n if (!Array.isArray(value) || !value.every(isKeepCollectionDefinition)) {\n throw new KeepStorageParseError({ operation: \"getAll\", storageKey });\n }\n return value;\n } catch (cause) {\n if (cause instanceof KeepStorageParseError) throw cause;\n throw new KeepStorageParseError({ operation: \"getAll\", storageKey, cause });\n }\n }\n\n async setCollection(collection: KeepCollectionDefinition): Promise<void> {\n if (!isKeepCollectionDefinition(collection)) throw new Error(\"Collection id and name are required.\");\n const current = await this.getCollections();\n await this.writeCollections(\n [\n ...current.filter((entry) => entry.id !== collection.id || !isSameKeepScope(entry.scope, collection.scope)),\n collection,\n ],\n \"set\",\n );\n }\n\n async removeCollection(id: string, scope?: KeepScope): Promise<void> {\n const current = await this.getCollections();\n await this.writeCollections(\n current.filter((entry) => entry.id !== id || !isSameKeepScope(entry.scope, scope)),\n \"remove\",\n );\n const memberships = await this.getCollectionMemberships();\n await this.writeMemberships(\n memberships.filter((membership) => membership.collectionId !== id || !isSameKeepScope(membership.scope, scope)),\n \"remove\",\n );\n }\n\n async getCollectionMemberships(): Promise<KeepCollectionMembership[]> {\n return this.readMemberships();\n }\n\n private readMemberships(): KeepCollectionMembership[] {\n if (!this.storage) return [];\n const storageKey = `${this.storageKey}:memberships`;\n let raw: string | null;\n try {\n raw = this.storage.getItem(storageKey);\n } catch (cause) {\n throw new KeepStorageAccessError({ operation: \"getAll\", storageKey, cause });\n }\n if (!raw) return [];\n try {\n const value: unknown = JSON.parse(raw);\n if (!Array.isArray(value) || !value.every(isKeepCollectionMembership)) {\n throw new KeepStorageParseError({ operation: \"getAll\", storageKey });\n }\n return value;\n } catch (cause) {\n if (cause instanceof KeepStorageParseError) throw cause;\n throw new KeepStorageParseError({ operation: \"getAll\", storageKey, cause });\n }\n }\n\n async setCollectionMembership(membership: KeepCollectionMembership): Promise<void> {\n if (!isKeepCollectionMembership(membership)) throw new Error(\"Collection membership is invalid.\");\n const current = this.readMemberships();\n const sameMembership = (entry: KeepCollectionMembership) =>\n entry.collectionId === membership.collectionId &&\n entry.itemId === membership.itemId &&\n isSameKeepScope(entry.scope, membership.scope);\n await this.writeMemberships([...current.filter((entry) => !sameMembership(entry)), membership], \"set\");\n }\n\n async removeCollectionMembership(collectionId: string, itemId: string, scope?: KeepScope): Promise<void> {\n const current = this.readMemberships();\n await this.writeMemberships(\n current.filter(\n (entry) =>\n entry.collectionId !== collectionId || entry.itemId !== itemId || !isSameKeepScope(entry.scope, scope),\n ),\n \"remove\",\n );\n }\n\n async set(item: KeepItem<TMeta>): Promise<void> {\n await this.setMany([item]);\n }\n\n async setMany(items: KeepItem<TMeta>[]): Promise<void> {\n const current = await this.getAll();\n const byScopeAndId = new Map(current.map((item) => [getItemStorageKey(item), item]));\n for (const item of items) byScopeAndId.set(getItemStorageKey(item), item);\n this.write([...byScopeAndId.values()], \"set\");\n }\n\n async remove(id: string, scope?: KeepScope): Promise<void> {\n await this.removeMany([id], scope);\n }\n\n async removeMany(ids: string[], scope?: KeepScope): Promise<void> {\n const idSet = new Set(ids);\n const items = await this.getAll();\n this.write(\n items.filter((item) => !idSet.has(item.id) || (scope !== undefined && !isSameKeepScope(item.scope, scope))),\n \"remove\",\n );\n const memberships = await this.getCollectionMemberships();\n const membershipIds = memberships.filter(\n (membership) => idSet.has(membership.itemId) && (scope === undefined || isSameKeepScope(membership.scope, scope)),\n );\n for (const membership of membershipIds) {\n await this.removeCollectionMembership(membership.collectionId, membership.itemId, membership.scope);\n }\n }\n\n async clear(): Promise<void> {\n if (!this.storage) return;\n try {\n const items = await this.getAll();\n if (items.length > 0) await this.removeMany(items.map((item) => item.id));\n const memberships = await this.getCollectionMemberships();\n for (const membership of memberships) {\n await this.removeCollectionMembership(membership.collectionId, membership.itemId, membership.scope);\n }\n this.storage.removeItem(this.storageKey);\n } catch (cause) {\n throw new KeepStorageAccessError({\n operation: \"clear\",\n storageKey: this.storageKey,\n cause,\n });\n }\n }\n\n async merge(localItems: KeepItem<TMeta>[]): Promise<KeepItem<TMeta>[]> {\n const merged = mergeKeepItemLists(await this.getAll(), localItems);\n this.write(merged, \"merge\");\n return merged;\n }\n\n subscribe(listener: () => void): () => void {\n if (typeof window === \"undefined\") return () => undefined;\n\n const handleStorage = (event: StorageEvent) => {\n if (\n event.key !== null &&\n event.key !== this.storageKey &&\n event.key !== `${this.storageKey}:collections` &&\n event.key !== `${this.storageKey}:memberships`\n )\n return;\n listener();\n };\n\n window.addEventListener(\"storage\", handleStorage);\n return () => window.removeEventListener(\"storage\", handleStorage);\n }\n\n private write(items: KeepItem<TMeta>[], operation: KeepStorageOperation): void {\n if (!this.storage) return;\n const serialized = serializeKeepStorage(items, { operation, storageKey: this.storageKey });\n try {\n this.storage.setItem(this.storageKey, serialized);\n } catch (cause) {\n if (isQuotaExceededError(cause)) {\n throw new KeepStorageQuotaError({\n operation,\n storageKey: this.storageKey,\n cause,\n });\n }\n throw new KeepStorageAccessError({\n operation,\n storageKey: this.storageKey,\n cause,\n });\n }\n }\n\n private async writeCollections(\n collections: KeepCollectionDefinition[],\n operation: KeepStorageOperation,\n ): Promise<void> {\n if (!this.storage) return;\n const storageKey = `${this.storageKey}:collections`;\n const serialized = serializeKeepStorage(collections, { operation, storageKey });\n try {\n this.storage.setItem(storageKey, serialized);\n } catch (cause) {\n if (isQuotaExceededError(cause)) throw new KeepStorageQuotaError({ operation, storageKey, cause });\n throw new KeepStorageAccessError({ operation, storageKey, cause });\n }\n }\n\n private async writeMemberships(\n memberships: KeepCollectionMembership[],\n operation: KeepStorageOperation,\n ): Promise<void> {\n if (!this.storage) return;\n const storageKey = `${this.storageKey}:memberships`;\n const serialized = serializeKeepStorage(memberships, { operation, storageKey });\n try {\n this.storage.setItem(storageKey, serialized);\n } catch (cause) {\n if (isQuotaExceededError(cause)) throw new KeepStorageQuotaError({ operation, storageKey, cause });\n throw new KeepStorageAccessError({ operation, storageKey, cause });\n }\n }\n}\n\n/** An async StorageAdapter backed by IndexedDB, with one object store per adapter. */\nexport class IndexedDBAdapter<TMeta = Record<string, unknown>> implements StorageAdapter<TMeta> {\n public readonly storageKey: string;\n private readonly databaseName: string;\n private readonly storeName: string;\n private readonly version: number;\n private readonly indexedDB: IDBFactory | undefined;\n private databasePromise: Promise<IDBDatabase | undefined> | undefined;\n private collectionDatabasePromise: Promise<IDBDatabase | undefined> | undefined;\n\n constructor(options: IndexedDBAdapterOptions = {}) {\n this.databaseName = options.databaseName ?? options.dbName ?? options.key ?? DEFAULT_INDEXEDDB_DATABASE;\n this.storeName = options.storeName ?? DEFAULT_INDEXEDDB_STORE;\n this.version = options.version ?? 1;\n this.indexedDB = options.indexedDB ?? getBrowserIndexedDB();\n this.storageKey = `${this.databaseName}:${this.storeName}`;\n }\n\n async getAll(): Promise<KeepItem<TMeta>[]> {\n const database = await this.open(\"getAll\");\n if (!database) return [];\n try {\n const transaction = database.transaction(this.storeName, \"readonly\");\n const value: unknown = await requestToPromise(transaction.objectStore(this.storeName).getAll());\n if (!isKeepItemArray(value)) {\n throw new KeepStorageParseError({ operation: \"getAll\", storageKey: this.storageKey });\n }\n return (value as KeepItem<TMeta>[]).map(decodeIndexedDBItem);\n } catch (cause) {\n if (cause instanceof KeepStorageParseError) throw cause;\n throw new KeepStorageAccessError({ operation: \"getAll\", storageKey: this.storageKey, cause });\n }\n }\n\n async getCollections(): Promise<KeepCollectionDefinition[]> {\n const database = await this.openCollections(\"getAll\");\n if (!database) return [];\n const storageKey = `${this.storageKey}:collections`;\n try {\n const transaction = database.transaction(\"collections\", \"readonly\");\n const value: unknown = await requestToPromise(transaction.objectStore(\"collections\").getAll());\n if (\n !Array.isArray(value) ||\n !value.every((entry) => isRecord(entry) && typeof entry.key === \"string\" && isKeepCollectionDefinition(entry))\n ) {\n throw new KeepStorageParseError({ operation: \"getAll\", storageKey });\n }\n return value.map(({ key: _key, ...collection }) => collection);\n } catch (cause) {\n if (cause instanceof KeepStorageParseError) throw cause;\n throw new KeepStorageAccessError({ operation: \"getAll\", storageKey, cause });\n }\n }\n\n async setCollection(collection: KeepCollectionDefinition): Promise<void> {\n if (!isKeepCollectionDefinition(collection)) throw new Error(\"Collection id and name are required.\");\n await this.writeCollection(\"set\", (store) =>\n store.put({ ...collection, key: collectionKey(collection.id, collection.scope) }),\n );\n }\n\n async removeCollection(id: string, scope?: KeepScope): Promise<void> {\n await this.writeCollection(\"remove\", (store) => store.delete(collectionKey(id, scope)));\n const memberships = await this.getCollectionMemberships();\n for (const membership of memberships) {\n if (membership.collectionId === id && isSameKeepScope(membership.scope, scope)) {\n await this.removeCollectionMembership(id, membership.itemId, scope);\n }\n }\n }\n\n async getCollectionMemberships(): Promise<KeepCollectionMembership[]> {\n const database = await this.openCollections(\"getAll\");\n if (!database) return [];\n const storageKey = `${this.storageKey}:memberships`;\n try {\n const transaction = database.transaction(\"memberships\", \"readonly\");\n const value: unknown = await requestToPromise(transaction.objectStore(\"memberships\").getAll());\n if (\n !Array.isArray(value) ||\n !value.every((entry) => isRecord(entry) && typeof entry.key === \"string\" && isKeepCollectionMembership(entry))\n ) {\n throw new KeepStorageParseError({ operation: \"getAll\", storageKey });\n }\n return value.map(({ key: _key, ...membership }) => membership);\n } catch (cause) {\n if (cause instanceof KeepStorageParseError) throw cause;\n throw new KeepStorageAccessError({ operation: \"getAll\", storageKey, cause });\n }\n }\n\n async setCollectionMembership(membership: KeepCollectionMembership): Promise<void> {\n if (!isKeepCollectionMembership(membership)) throw new Error(\"Collection membership is invalid.\");\n await this.writeCollectionMembership(\"set\", (store) =>\n store.put({ ...membership, key: membershipKey(membership.collectionId, membership.itemId, membership.scope) }),\n );\n }\n\n async removeCollectionMembership(collectionId: string, itemId: string, scope?: KeepScope): Promise<void> {\n await this.writeCollectionMembership(\"remove\", (store) => store.delete(membershipKey(collectionId, itemId, scope)));\n }\n\n async set(item: KeepItem<TMeta>): Promise<void> {\n return this.setMany([item]);\n }\n\n async setMany(items: KeepItem<TMeta>[]): Promise<void> {\n const database = await this.open(\"set\");\n if (!database) return;\n try {\n const identities = new Set(items.map(getItemIdentity));\n const previous = (await this.getAll()).filter((item) => identities.has(getItemIdentity(item)));\n const transaction = database.transaction(this.storeName, \"readwrite\");\n const objectStore = transaction.objectStore(this.storeName);\n for (const item of previous) objectStore.delete(getStoredIndexedDBItemId(item));\n for (const item of items) objectStore.put(encodeIndexedDBItem(item));\n await transactionToPromise(transaction);\n this.notifySubscribers();\n } catch (cause) {\n if (isQuotaExceededError(cause)) {\n throw new KeepStorageQuotaError({ operation: \"set\", storageKey: this.storageKey, cause });\n }\n throw new KeepStorageAccessError({ operation: \"set\", storageKey: this.storageKey, cause });\n }\n }\n\n async remove(id: string, scope?: KeepScope): Promise<void> {\n return this.removeMany([id], scope);\n }\n\n async removeMany(ids: string[], scope?: KeepScope): Promise<void> {\n const database = await this.open(\"remove\");\n if (!database) return;\n try {\n const idSet = new Set(ids);\n const removableIds = (await this.getAll())\n .filter((item) => idSet.has(item.id) && (scope === undefined || isSameKeepScope(item.scope, scope)))\n .map(getStoredIndexedDBItemId);\n const transaction = database.transaction(this.storeName, \"readwrite\");\n const objectStore = transaction.objectStore(this.storeName);\n for (const id of removableIds) objectStore.delete(id);\n await transactionToPromise(transaction);\n const memberships = await this.getCollectionMemberships();\n for (const membership of memberships) {\n if (idSet.has(membership.itemId) && (scope === undefined || isSameKeepScope(membership.scope, scope))) {\n await this.removeCollectionMembership(membership.collectionId, membership.itemId, membership.scope);\n }\n }\n this.notifySubscribers();\n } catch (cause) {\n throw new KeepStorageAccessError({ operation: \"remove\", storageKey: this.storageKey, cause });\n }\n }\n\n async clear(): Promise<void> {\n const database = await this.open(\"clear\");\n if (!database) return;\n try {\n const items = await this.getAll();\n if (items.length > 0) await this.removeMany(items.map((item) => item.id));\n const memberships = await this.getCollectionMemberships();\n for (const membership of memberships) {\n await this.removeCollectionMembership(membership.collectionId, membership.itemId, membership.scope);\n }\n const transaction = database.transaction(this.storeName, \"readwrite\");\n transaction.objectStore(this.storeName).clear();\n await transactionToPromise(transaction);\n this.notifySubscribers();\n } catch (cause) {\n throw new KeepStorageAccessError({ operation: \"clear\", storageKey: this.storageKey, cause });\n }\n }\n\n async merge(localItems: KeepItem<TMeta>[]): Promise<KeepItem<TMeta>[]> {\n try {\n const merged = mergeKeepItemLists(await this.getAll(), localItems);\n await this.setMany(merged);\n return merged;\n } catch (cause) {\n if (cause instanceof KeepStorageError) throw cause;\n throw new KeepStorageAccessError({ operation: \"merge\", storageKey: this.storageKey, cause });\n }\n }\n\n subscribe(listener: () => void): () => void {\n if (!this.indexedDB || typeof BroadcastChannel === \"undefined\") return () => undefined;\n const channel = new BroadcastChannel(`keepkit:${this.storageKey}`);\n channel.onmessage = () => listener();\n return () => channel.close();\n }\n\n private notifySubscribers(): void {\n if (!this.indexedDB || typeof BroadcastChannel === \"undefined\") return;\n const channel = new BroadcastChannel(`keepkit:${this.storageKey}`);\n channel.postMessage({ type: \"keepkit:changed\" });\n channel.close();\n }\n\n private async writeCollection(\n operation: KeepStorageOperation,\n write: (store: IDBObjectStore) => void,\n ): Promise<void> {\n const database = await this.openCollections(operation);\n if (!database) return;\n const storageKey = `${this.storageKey}:collections`;\n try {\n const transaction = database.transaction(\"collections\", \"readwrite\");\n write(transaction.objectStore(\"collections\"));\n await transactionToPromise(transaction);\n this.notifySubscribers();\n } catch (cause) {\n if (isQuotaExceededError(cause)) throw new KeepStorageQuotaError({ operation, storageKey, cause });\n throw new KeepStorageAccessError({ operation, storageKey, cause });\n }\n }\n\n private async writeCollectionMembership(\n operation: KeepStorageOperation,\n write: (store: IDBObjectStore) => void,\n ): Promise<void> {\n const database = await this.openCollections(operation);\n if (!database) return;\n const storageKey = `${this.storageKey}:memberships`;\n try {\n const transaction = database.transaction(\"memberships\", \"readwrite\");\n write(transaction.objectStore(\"memberships\"));\n await transactionToPromise(transaction);\n this.notifySubscribers();\n } catch (cause) {\n if (isQuotaExceededError(cause)) throw new KeepStorageQuotaError({ operation, storageKey, cause });\n throw new KeepStorageAccessError({ operation, storageKey, cause });\n }\n }\n\n private openCollections(operation: KeepStorageOperation): Promise<IDBDatabase | undefined> {\n if (!this.indexedDB) return Promise.resolve(undefined);\n const storageKey = `${this.storageKey}:collections`;\n if (!this.collectionDatabasePromise) {\n this.collectionDatabasePromise = new Promise((resolve, reject) => {\n let request: IDBOpenDBRequest;\n try {\n request = this.indexedDB?.open(storageKey, 2) as IDBOpenDBRequest;\n } catch (cause) {\n reject(cause);\n return;\n }\n request.onupgradeneeded = () => {\n if (!request.result.objectStoreNames.contains(\"collections\")) {\n request.result.createObjectStore(\"collections\", { keyPath: \"key\" });\n }\n if (!request.result.objectStoreNames.contains(\"memberships\")) {\n request.result.createObjectStore(\"memberships\", { keyPath: \"key\" });\n }\n };\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n request.onblocked = () => reject(request.error ?? new Error(\"IndexedDB collection storage open was blocked.\"));\n });\n }\n return this.collectionDatabasePromise.catch((cause) => {\n this.collectionDatabasePromise = undefined;\n throw new KeepStorageAccessError({ operation, storageKey, cause });\n });\n }\n\n private open(operation: KeepStorageOperation): Promise<IDBDatabase | undefined> {\n if (!this.indexedDB) return Promise.resolve(undefined);\n if (!this.databasePromise) {\n this.databasePromise = new Promise((resolve, reject) => {\n let request: IDBOpenDBRequest;\n try {\n request = this.indexedDB?.open(this.databaseName, this.version) as IDBOpenDBRequest;\n } catch (cause) {\n reject(new KeepStorageAccessError({ operation, storageKey: this.storageKey, cause }));\n return;\n }\n request.onupgradeneeded = () => {\n if (!request.result.objectStoreNames.contains(this.storeName)) {\n request.result.createObjectStore(this.storeName, { keyPath: \"id\" });\n }\n };\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n request.onblocked = () => reject(request.error ?? new Error(\"IndexedDB open was blocked.\"));\n });\n }\n return this.databasePromise.catch((cause) => {\n this.databasePromise = undefined;\n if (cause instanceof KeepStorageError) throw cause;\n throw new KeepStorageAccessError({ operation, storageKey: this.storageKey, cause });\n });\n }\n}\n\nconst indexedDBStoredItemIds = new WeakMap<object, string>();\n\nfunction encodeIndexedDBItem<TMeta>(item: KeepItem<TMeta>): Record<string, unknown> {\n if (!item.scope) return item;\n return {\n ...item,\n id: createScopedIndexedDBItemId(item),\n __keepkitOriginalId: item.id,\n };\n}\n\nfunction decodeIndexedDBItem<TMeta>(item: KeepItem<TMeta>): KeepItem<TMeta> {\n const originalId = (item as KeepItem<TMeta> & { __keepkitOriginalId?: unknown }).__keepkitOriginalId;\n const isEncoded =\n typeof originalId === \"string\" &&\n item.scope !== undefined &&\n item.id === createScopedIndexedDBItemId({ ...item, id: originalId });\n const { __keepkitOriginalId: _encodedOriginalId, ...record } = item as KeepItem<TMeta> & {\n __keepkitOriginalId?: unknown;\n };\n const decoded = isEncoded ? { ...record, id: originalId as string } : item;\n indexedDBStoredItemIds.set(decoded, item.id);\n return decoded;\n}\n\nfunction getStoredIndexedDBItemId<TMeta>(item: KeepItem<TMeta>): string {\n return indexedDBStoredItemIds.get(item) ?? createScopedIndexedDBItemId(item);\n}\n\nfunction createScopedIndexedDBItemId(item: Pick<KeepItem, \"id\" | \"scope\">): string {\n if (!item.scope) return item.id;\n return `\\u0000keepkit-scope:${JSON.stringify([item.scope.tenantId ?? null, item.scope.userId ?? null, item.id])}`;\n}\n\nfunction getItemIdentity(item: Pick<KeepItem, \"id\" | \"scope\">): string {\n return JSON.stringify([item.scope?.tenantId ?? null, item.scope?.userId ?? null, item.id]);\n}\n\nfunction collectionKey(id: string, scope?: KeepScope): string {\n return JSON.stringify([scope?.tenantId ?? null, scope?.userId ?? null, id]);\n}\n\nfunction getItemStorageKey(item: Pick<KeepItem, \"id\" | \"scope\">): string {\n return JSON.stringify([item.scope?.tenantId ?? null, item.scope?.userId ?? null, item.id]);\n}\n\nfunction membershipKey(collectionId: string, itemId: string, scope?: KeepScope): string {\n return JSON.stringify([scope?.tenantId ?? null, scope?.userId ?? null, collectionId, itemId]);\n}\n\nfunction getBrowserStorage(): Storage | undefined {\n if (typeof window === \"undefined\") return undefined;\n try {\n return window.localStorage;\n } catch {\n return undefined;\n }\n}\n\nfunction getBrowserIndexedDB(): IDBFactory | undefined {\n if (typeof indexedDB === \"undefined\") return undefined;\n return indexedDB;\n}\n\nfunction isRecoverableStorageError(error: unknown): boolean {\n return error instanceof KeepStorageAccessError || error instanceof KeepStorageQuotaError;\n}\n\nfunction requestToPromise<T>(request: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n}\n\nfunction transactionToPromise(transaction: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => reject(transaction.error);\n transaction.onabort = () => reject(transaction.error ?? new Error(\"IndexedDB transaction aborted.\"));\n });\n}\n\nfunction isQuotaExceededError(cause: unknown): boolean {\n if (!isRecord(cause)) return false;\n return (\n cause.name === \"QuotaExceededError\" ||\n cause.name === \"NS_ERROR_DOM_QUOTA_REACHED\" ||\n cause.code === 22 ||\n cause.code === 1014\n );\n}\n\nexport { ScopedSyncQueueAdapter } from \"../features/persistence/scope\";\nexport {\n DEFAULT_SYNC_QUEUE_DATABASE,\n DEFAULT_SYNC_QUEUE_KEY,\n DEFAULT_SYNC_QUEUE_STORE,\n FallbackSyncQueueAdapter,\n type FallbackSyncQueueAdapterOptions,\n IndexedDBSyncQueueAdapter,\n type IndexedDBSyncQueueOptions,\n LocalStorageSyncQueueAdapter,\n type LocalStorageSyncQueueOptions,\n SyncStorageAdapter,\n type SyncStorageAdapterOptions,\n} from \"./sync\";\n"],"mappings":";;;;;AAqPO,IAAM,oBAAN,cAAiE,MAAM;AAAA,EAM5E,YACE,QACA,SACA;AACA,UAAM,iDAAiD,MAAM,GAAG;AAChE,SAAK,OAAO;AACZ,SA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EAAE,CAAC;AAC3F;AAEA,SAASC,eAAc,cAAsB,QAAgB,OAA2B;AACtF,SAAO,KAAK,UAAU,CAAC,OAAO,YAAY,MAAM,OAAO,UAAU,MAAM,cAAc,MAAM,CAAC;AAC9F;AAEA,SAASH,qBAAyC;AAChD,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,MAAI;AACF,WAAO,OAAO;AAAA,EAChB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAASD,uBAA8C;AACrD,MAAI,OAAO,cAAc,YAAa,QAAO;AAC7C,SAAO;AACT;AAEA,SAAS,0BAA0B,OAAyB;AAC1D,SAAO,iBAAiB,0BAA0B,iBAAiB;AACrE;AAEA,SAASE,kBAAoB,SAAoC;AAC/D,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,YAAQ,YAAY,MAAM,QAAQ,QAAQ,MAAM;AAChD,YAAQ,UAAU,MAAM,OAAO,QAAQ,KAAK;AAAA,EAC9C,CAAC;AACH;AAEA,SAASG,sBAAqB,aAA4C;AACxE,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,gBAAY,aAAa,MAAM,QAAQ;AACvC,gBAAY,UAAU,MAAM,OAAO,YAAY,KAAK;AACpD,gBAAY,UAAU,MAAM,OAAO,YAAY,SAAS,IAAI,MAAM,gCAAgC,CAAC;AAAA,EACrG,CAAC;AACH;AAEA,SAAS,qBAAqB,OAAyB;AACrD,MAAI,CAAC,SAAS,KAAK,EAAG,QAAO;AAC7B,SACE,MAAM,SAAS,wBACf,MAAM,SAAS,gCACf,MAAM,SAAS,MACf,MAAM,SAAS;AAEnB;","names":["result","_legacyCollectionId","migratedItem","isSyncScope","merged","fallback","sameScope","merged","result","indexedDB","scope","getBrowserIndexedDB","getBrowserStorage","requestToPromise","collectionKey","membershipKey","transactionToPromise"]}
|