pbtsdb 2.0.0 → 2.0.1
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 +70 -0
- package/dist/{chunk-4CRCARB3.js → chunk-TTENGDS3.js} +223 -35
- package/dist/chunk-TTENGDS3.js.map +1 -0
- package/dist/core.d.ts +53 -1
- package/dist/core.js +1 -1
- package/dist/index.d.ts +20 -2
- package/dist/index.js +11 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-4CRCARB3.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/expand-paths.ts","../src/logger.ts","../src/records.ts","../src/expand-filing.ts","../src/keyed-where.ts","../src/pocketbase-query-converter.ts","../src/pocketbase-limits.ts","../src/fetch-records.ts","../src/held-targets.ts","../src/ledger.ts","../src/loaded-subsets.ts","../src/membership.ts","../src/filter-refs.ts","../src/realtime-subscription.ts","../src/realtime-where.ts","../src/request.ts","../src/sync-adapter.ts","../src/synced-store.ts","../src/realtime-client.ts","../src/sync-status.ts","../src/transport.ts","../src/views.ts","../src/build-collection.ts","../src/collection.ts","../src/util.ts"],"names":["entryFor","result","hold","entries","membership","createTanStackCollection","whenSyncAccepted"],"mappings":";;;;;;AAIO,SAAS,eAAe,KAAA,EAAmC;AAC9D,EAAA,MAAM,GAAA,uBAAU,GAAA,EAAY;AAC5B,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACtB,IAAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAC1B,IAAA,IAAI,OAAA,EAAS,GAAA,CAAI,GAAA,CAAI,OAAO,CAAA;AAAA,EAChC;AACA,EAAA,OAAO,CAAC,GAAG,GAAG,CAAA,CAAE,IAAA,EAAK;AACzB;AAEO,SAAS,WAAW,GAAA,EAAmC;AAC1D,EAAA,OAAO,MAAM,cAAA,CAAe,GAAA,CAAI,MAAM,GAAG,CAAC,IAAI,EAAC;AACnD;AAEO,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AM,MAAM,CAAC,CAAA;AAAA,EACnE;AACA,EAAA,OAAO,MAAA;AACX","file":"chunk-TTENGDS3.js","sourcesContent":["import type { RelationTarget } from './types'\n\nexport type RelationTargets = Record<string, RelationTarget>\n\nexport function normalizePaths(paths: Iterable<string>): string[] {\n const set = new Set<string>()\n for (const path of paths) {\n const trimmed = path.trim()\n if (trimmed) set.add(trimmed)\n }\n return [...set].sort()\n}\n\nexport function splitPaths(csv: string | undefined): string[] {\n return csv ? normalizePaths(csv.split(',')) : []\n}\n\nexport function joinPaths(paths: Iterable<string>): string | undefined {\n const normalized = normalizePaths(paths)\n return normalized.length > 0 ? normalized.join(',') : undefined\n}\n\nexport const BACK_RELATION_EXPAND_CAP = 1000\n\n/** `<collection>_via_<field>` → `{ field }`, split at the first `_via_`. */\nexport function parseViaKey(key: string): { field: string } | undefined {\n const index = key.indexOf('_via_')\n if (index < 0) return undefined\n const field = key.slice(index + '_via_'.length)\n return field ? { field } : undefined\n}\n\n/**\n * After a parent filed the values expanded under `key`, record on the target\n * that the subset `field = parentId` is complete — unless the key is a forward\n * relation or PocketBase may have capped the expand.\n */\nexport function markFiledSubset(\n target: RelationTarget,\n key: string,\n values: readonly object[],\n parentId: string\n): void {\n const via = parseViaKey(key)\n if (!via || values.length >= BACK_RELATION_EXPAND_CAP) return\n target.markSubsetLoaded(via.field, parentId)\n}\n\nexport function validateExpandPath(\n collectionName: string,\n targets: RelationTargets | undefined,\n path: string\n): void {\n if (!targets) {\n throw new Error(\n `Cannot expand \"${path}\" on collection \"${collectionName}\": no relations declared`\n )\n }\n let current: RelationTargets | undefined = targets\n for (const segment of path.split('.')) {\n const next: RelationTarget | undefined = current?.[segment]\n if (!next) {\n throw new Error(\n `Cannot expand \"${path}\" on collection \"${collectionName}\": segment \"${segment}\" is not a declared relation`\n )\n }\n current = next.relationTargets\n }\n}\n","/**\n * Logger interface for subscription events and internal operations.\n * Users can provide their own implementation to integrate with external logging services.\n */\nexport interface Logger {\n /**\n * Log debug-level messages (typically only shown in development).\n * @param msg - The message to log\n * @param context - Optional context object with additional information\n */\n debug: (msg: string, context?: object) => void\n\n /**\n * Log info-level messages.\n * @param msg - The message to log\n * @param context - Optional context object with additional information\n */\n info: (msg: string, context?: object) => void\n\n /**\n * Log warning-level messages.\n * @param msg - The message to log\n * @param context - Optional context object with additional information\n */\n warn: (msg: string, context?: object) => void\n\n /**\n * Log error-level messages.\n * @param msg - The message to log\n * @param context - Optional context object with additional information\n */\n error: (msg: string, context?: object) => void\n}\n\n/**\n * Default console-based logger implementation.\n * Only logs debug messages in development mode.\n */\nconst defaultLogger: Logger = {\n debug: (msg: string, context?: object) => {\n if (process.env.NODE_ENV === 'development') {\n console.debug(`[pbtsdb] ${msg}`, context || '')\n }\n },\n info: (msg: string, context?: object) => {\n console.info(`[pbtsdb] ${msg}`, context || '')\n },\n warn: (msg: string, context?: object) => {\n console.warn(`[pbtsdb] ${msg}`, context || '')\n },\n error: (msg: string, context?: object) => {\n console.error(`[pbtsdb] ${msg}`, context || '')\n },\n}\n\n/**\n * Current logger instance (can be replaced by users).\n */\nlet currentLogger: Logger = defaultLogger\n\n/**\n * Internal logger instance used by the library.\n */\nexport const logger: Logger = {\n debug: (msg: string, context?: object) => currentLogger.debug(msg, context),\n info: (msg: string, context?: object) => currentLogger.info(msg, context),\n warn: (msg: string, context?: object) => currentLogger.warn(msg, context),\n error: (msg: string, context?: object) => currentLogger.error(msg, context),\n}\n\n/**\n * Set a custom logger implementation.\n * This allows users to integrate with their own logging services (e.g., Sentry, LogRocket, etc.).\n *\n * @param customLogger - The custom logger implementation\n *\n * @example\n * ```ts\n * import { setLogger } from 'pbtsdb';\n *\n * // Integration with a custom logging service\n * setLogger({\n * debug: (msg, context) => myLogger.debug(msg, context),\n * warn: (msg, context) => myLogger.warn(msg, context),\n * error: (msg, context) => {\n * myLogger.error(msg, context);\n * Sentry.captureMessage(msg, { level: 'error', extra: context });\n * },\n * });\n * ```\n *\n * @example\n * ```ts\n * // Disable all logging\n * setLogger({\n * debug: () => {},\n * warn: () => {},\n * error: () => {},\n * });\n * ```\n */\nexport function setLogger(customLogger: Logger): void {\n currentLogger = customLogger\n}\n\n/**\n * Reset the logger to the default implementation.\n */\nexport function resetLogger(): void {\n currentLogger = defaultLogger\n}\n","// Accessors for the untyped records PocketBase hands back: rows, expand\n// entries, and realtime events.\n\nexport function idOf(value: unknown): string | undefined {\n if (!value || typeof value !== 'object' || !('id' in value)) return undefined\n return typeof value.id === 'string' ? value.id : undefined\n}\n\n/** The ids of `rows`, skipping rows without one. */\nexport function idsOf(rows: readonly unknown[]): string[] {\n return rows.map(idOf).filter((id): id is string => id !== undefined)\n}\n\nexport function updatedAtOf(value: unknown): string | undefined {\n if (!value || typeof value !== 'object' || !('updated' in value)) return undefined\n return typeof value.updated === 'string' && value.updated !== '' ? value.updated : undefined\n}\n\nexport function expandOf(value: unknown): Record<string, unknown> | undefined {\n if (!value || typeof value !== 'object' || !('expand' in value)) return undefined\n const { expand } = value\n return expand && typeof expand === 'object' ? (expand as Record<string, unknown>) : undefined\n}\n\nexport function isObject(value: unknown): value is object {\n return typeof value === 'object' && value !== null\n}\n","import { markFiledSubset, parseViaKey, type RelationTargets, splitPaths } from './expand-paths'\nimport type { FilingChange } from './held-targets'\nimport { logger } from './logger'\nimport { expandOf, idOf, idsOf, isObject } from './records'\nimport type { RelationTarget } from './types'\n\nexport type { FilingChange } from './held-targets'\n\n/** A back-relation (`<collection>_via_<field>`) at the head of an active expand path. */\nexport interface BackRelationHead {\n target: RelationTarget\n key: string\n field: string\n}\n\nexport function backRelationHeads(\n expandString: string | undefined,\n targets: RelationTargets | undefined\n): BackRelationHead[] {\n if (!targets) return []\n const heads: BackRelationHead[] = []\n for (const key of splitPaths(expandString).map(path => path.split('.')[0])) {\n const target = targets[key]\n const via = target && parseViaKey(key)\n if (target && via) heads.push({ target, key, field: via.field })\n }\n return heads\n}\n\n/** Every collection along the given expand paths, through nested targets. */\nexport function targetsAlong(\n paths: Iterable<string>,\n targets: RelationTargets | undefined\n): Set<RelationTarget> {\n const found = new Set<RelationTarget>()\n for (const path of paths) {\n let current = targets\n for (const segment of path.split('.')) {\n const target = current?.[segment]\n if (!target) break\n found.add(target)\n current = target.relationTargets\n }\n }\n return found\n}\n\n// A filed copy never carries `expand`: parts with a declared target are filed\n// by the recursive call, and parts without one have nowhere to go.\nexport function withoutExpand(values: object[]): object[] {\n return values.map(value => {\n const { expand: _expand, ...plain } = value as { expand?: unknown }\n return plain\n })\n}\n\n// pbtsdb asked PocketBase for these relations only to file them into their\n// target collections; the copies never reach a row in any cache.\nexport function stripFetchedRelations<T extends object>(\n items: T[],\n expandString: string | undefined\n): T[] {\n const heads = new Set(splitPaths(expandString).map(path => path.split('.')[0]))\n if (heads.size === 0) return items\n return items.map(item => {\n const { expand, ...plain } = item as T & { expand?: Record<string, unknown> }\n if (!expand) return item\n const kept = Object.fromEntries(Object.entries(expand).filter(([key]) => !heads.has(key)))\n return (Object.keys(kept).length > 0 ? { ...plain, expand: kept } : plain) as T\n })\n}\n\ntype ExpandedGroup = { values: object[]; byParent: [string, object[]][] }\n\nfunction groupExpandedByKey(records: readonly object[]): Map<string, ExpandedGroup> {\n const byKey = new Map<string, ExpandedGroup>()\n for (const record of records) {\n const expand = expandOf(record)\n if (!expand) continue\n const parentId = idOf(record)\n for (const [key, value] of Object.entries(expand)) {\n const values = (Array.isArray(value) ? value : [value]).filter(isObject)\n const group = byKey.get(key) ?? { values: [], byParent: [] }\n group.values.push(...values)\n if (parentId) group.byParent.push([parentId, values])\n byKey.set(key, group)\n }\n }\n return byKey\n}\n\n// Many parents can expand the same record; the last copy wins.\nfunction lastById(values: object[]): object[] {\n const byId = new Map<string | undefined, object>()\n for (const value of values) byId.set(idOf(value), value)\n return [...byId.values()]\n}\n\n/**\n * Root row `rootId` now files exactly `rowIds` into `target` under expand\n * path `key`, with realtime filters on `filterValues` (the immediate\n * parent ids for a back-relation). The change is committed once the root\n * row has landed, or undone when it is discarded.\n */\nexport type SetFiled = (\n rootId: string,\n target: RelationTarget,\n key: string,\n rowIds: Iterable<string>,\n filterValues?: Iterable<string>\n) => FilingChange\n\nexport interface ExpandFiler {\n /**\n * File every expanded record into its target, one write per relation\n * key, and record each parent's filings for the expand paths the\n * request asked for: a requested key a record does not carry means the\n * relation is empty or unreadable. Resolves with one change: `commit`\n * it after the parent rows land, so a parent is never visible without\n * its relation; `undo` it when the parent rows are discarded, so a\n * result that is thrown away changes nothing.\n */\n fileExpanded: (\n records: readonly object[],\n targets: RelationTargets | undefined,\n requestedPaths: readonly string[]\n ) => Promise<FilingChange>\n /** `fileExpanded` committed at once, for a parent that has already landed. */\n upsertExpanded: (\n records: readonly object[],\n targets: RelationTargets | undefined,\n requestedPaths: readonly string[]\n ) => Promise<void>\n /**\n * Whether `fileExpanded` has rows to write and every target it would\n * write to is syncing, so the filing lands within the current task and\n * the parent can wait for it. False when there is nothing to file, so\n * the parent lands at once.\n */\n canFileFirst: (records: readonly object[], targets: RelationTargets | undefined) => boolean\n /** PocketBase omits an empty back-relation's key, so absence means zero children. */\n markEmptyBackRelations: (items: readonly object[], heads: readonly BackRelationHead[]) => void\n}\n\n/** The paths under `key`: `a.b.c` requested as `key.a.b.c`. */\nfunction tailsOf(paths: readonly string[], key: string): string[] {\n return paths.filter(path => path.startsWith(`${key}.`)).map(path => path.slice(key.length + 1))\n}\n\nexport interface ExpandFilerDeps {\n collectionName: string\n setFiled: SetFiled\n /** This collection's identity as a parent: the holder its filings carry. */\n holder: object\n /**\n * A parent record whose filings must not be reconciled: a copy older\n * than the stored row, or a row deleted while its fetch was in flight.\n */\n isStale: (record: object) => boolean\n}\n\nexport function createExpandFiler(deps: ExpandFilerDeps): ExpandFiler {\n const { collectionName, setFiled, holder } = deps\n\n type Releases = FilingChange[]\n /** The root rows that reach a row at the current level. */\n type Roots = (id: string) => Iterable<string>\n type PerRoot = Map<string, { rows: Set<string>; parents: Set<string> }>\n\n /**\n * What each root files under `key` at this level: the expanded row ids,\n * and the immediate parent ids a back-relation filters on. A root whose\n * records lack a requested key files nothing under it, which ends what it\n * filed there before.\n */\n function entryFor(perRoot: PerRoot, root: string): { rows: Set<string>; parents: Set<string> } {\n let found = perRoot.get(root)\n if (!found) {\n found = { rows: new Set(), parents: new Set() }\n perRoot.set(root, found)\n }\n return found\n }\n\n function addTo(index: Map<string, Set<string>>, key: string, value: string): void {\n let values = index.get(key)\n if (!values) {\n values = new Set()\n index.set(key, values)\n }\n values.add(value)\n }\n\n /** Every root that reaches this level files under a requested key, with nothing when its records lack it. */\n function rootsReaching(\n records: readonly object[],\n via: boolean,\n rootsOf: Roots,\n perRoot: PerRoot\n ): void {\n for (const record of records) {\n const parentId = idOf(record)\n if (!parentId) continue\n for (const root of rootsOf(parentId)) {\n const found = entryFor(perRoot, root)\n if (via) found.parents.add(parentId)\n }\n }\n }\n\n function collectRoots(\n records: readonly object[],\n group: ExpandedGroup,\n requested: boolean,\n via: boolean,\n rootsOf: Roots\n ): { perRoot: PerRoot; childRoots: Map<string, Set<string>> } {\n const perRoot: PerRoot = new Map()\n const childRoots = new Map<string, Set<string>>()\n if (requested) rootsReaching(records, via, rootsOf, perRoot)\n for (const [parentId, values] of group.byParent) {\n const ids = idsOf(values)\n for (const root of rootsOf(parentId)) {\n const found = entryFor(perRoot, root)\n found.parents.add(parentId)\n for (const id of ids) {\n found.rows.add(id)\n addTo(childRoots, id, root)\n }\n }\n }\n return { perRoot, childRoots }\n }\n\n /** A root with no rows under `prefix` files nothing deeper either. */\n function clearDeeper(\n root: string,\n targets: RelationTargets | undefined,\n paths: readonly string[],\n prefix: string,\n releases: Releases\n ): void {\n if (!targets) return\n for (const head of new Set(paths.map(path => path.split('.')[0]))) {\n const target = targets[head]\n if (!target) continue\n releases.push(setFiled(root, target, `${prefix}${head}`, [], []))\n clearDeeper(\n root,\n target.relationTargets,\n tailsOf(paths, head),\n `${prefix}${head}.`,\n releases\n )\n }\n }\n\n // Children before parents at every level, so a row never lands before\n // the rows it points at. Nested levels are the target's rows, not this\n // parent's, so staleness is checked at the top level only.\n type Level = {\n requestedPaths: readonly string[]\n releases: Releases\n rootsOf: Roots\n prefix: string\n }\n\n async function fileKey(\n records: readonly object[],\n level: Level,\n key: string,\n target: RelationTarget,\n group: ExpandedGroup,\n requested: boolean\n ): Promise<void> {\n const via = parseViaKey(key) !== undefined\n const { perRoot, childRoots } = collectRoots(records, group, requested, via, level.rootsOf)\n const values = lastById(group.values)\n const tails = tailsOf(level.requestedPaths, key)\n const path = `${level.prefix}${key}`\n if (values.length > 0) {\n await fileLevel(values, target.relationTargets, {\n requestedPaths: tails,\n releases: level.releases,\n rootsOf: id => childRoots.get(id) ?? [],\n prefix: `${path}.`,\n })\n if (!(await target.writeFiled(values, holder))) return\n }\n for (const [root, { rows, parents }] of perRoot) {\n level.releases.push(setFiled(root, target, path, rows, via ? parents : rows))\n if (rows.size === 0) {\n clearDeeper(root, target.relationTargets, tails, `${path}.`, level.releases)\n }\n }\n for (const [parentId, parentValues] of group.byParent) {\n markFiledSubset(target, key, parentValues, parentId)\n }\n }\n\n async function fileLevel(\n records: readonly object[],\n targets: RelationTargets | undefined,\n level: Level\n ): Promise<void> {\n if (!targets) return\n const grouped = groupExpandedByKey(records)\n const heads = new Set(level.requestedPaths.map(path => path.split('.')[0]))\n for (const key of new Set([...grouped.keys(), ...heads])) {\n const target = targets[key]\n if (!target) {\n if (grouped.has(key)) {\n logger.debug('No relation target for expanded field', { collectionName, key })\n }\n continue\n }\n const group = grouped.get(key) ?? { values: [], byParent: [] }\n await fileKey(records, level, key, target, group, heads.has(key))\n }\n }\n\n async function fileExpanded(\n records: readonly object[],\n targets: RelationTargets | undefined,\n requestedPaths: readonly string[]\n ): Promise<FilingChange> {\n const releases: Releases = []\n try {\n await fileLevel(\n records.filter(record => !deps.isStale(record)),\n targets,\n { requestedPaths, releases, rootsOf: id => [id], prefix: '' }\n )\n } catch (error) {\n // A partial filing must not outlive the error: what landed is\n // undone, so nothing is held by a filing nobody will commit.\n for (const change of [...releases].reverse()) change.undo()\n throw error\n }\n return {\n commit: () => {\n for (const change of releases) change.commit()\n },\n undo: () => {\n for (const change of [...releases].reverse()) change.undo()\n },\n }\n }\n\n async function upsertExpanded(\n records: readonly object[],\n targets: RelationTargets | undefined,\n requestedPaths: readonly string[]\n ): Promise<void> {\n ;(await fileExpanded(records, targets, requestedPaths)).commit()\n }\n\n function targetsReady(records: readonly object[], targets: RelationTargets): boolean {\n for (const [key, group] of groupExpandedByKey(records)) {\n const target = targets[key]\n if (!target) continue\n if (!target.isReady()) return false\n const nested = target.relationTargets\n if (nested && !targetsReady(lastById(group.values), nested)) return false\n }\n return true\n }\n\n function canFileFirst(\n records: readonly object[],\n targets: RelationTargets | undefined\n ): boolean {\n if (!targets) return false\n const toFile = [...groupExpandedByKey(records).keys()].some(key => targets[key])\n return toFile && targetsReady(records, targets)\n }\n\n return {\n fileExpanded,\n upsertExpanded,\n canFileFirst,\n markEmptyBackRelations(items, heads) {\n if (heads.length === 0) return\n for (const item of items) {\n const id = idOf(item)\n if (!id) continue\n const expand = expandOf(item)\n for (const { target, key, field } of heads) {\n if (expand?.[key] === undefined) target.markSubsetLoaded(field, id)\n }\n }\n },\n }\n}\n","import type { IR } from '@tanstack/db'\n\nexport type WhereSubset = { field: string; values: string[] }\n\ntype Node = { type: string; name?: string; args?: Node[]; path?: string[]; value?: unknown }\n\nfunction fieldRef(node: Node | undefined): string | undefined {\n return node?.type === 'ref' && node.path?.length === 1 ? node.path[0] : undefined\n}\n\nfunction stringValue(node: Node | undefined): string | undefined {\n return node?.type === 'val' && typeof node.value === 'string' ? node.value : undefined\n}\n\nfunction collectEq(a: Node | undefined, b: Node | undefined): WhereSubset | undefined {\n const field = fieldRef(a) ?? fieldRef(b)\n if (field === undefined) return undefined\n const value = stringValue(fieldRef(a) !== undefined ? b : a)\n return value === undefined ? undefined : { field, values: [value] }\n}\n\nfunction collectIn(a: Node | undefined, b: Node | undefined): WhereSubset | undefined {\n const field = fieldRef(a)\n if (field === undefined || b?.type !== 'val' || !Array.isArray(b.value)) return undefined\n return b.value.every(v => typeof v === 'string')\n ? { field, values: b.value as string[] }\n : undefined\n}\n\nfunction collectOr(args: Node[]): WhereSubset | undefined {\n let field: string | undefined\n const values: string[] = []\n for (const arg of args) {\n const sub = collect(arg)\n if (!sub || (field !== undefined && sub.field !== field)) return undefined\n field = sub.field\n values.push(...sub.values)\n }\n return field === undefined ? undefined : { field, values }\n}\n\nfunction collect(node: Node): WhereSubset | undefined {\n if (node.type !== 'func' || !node.args) return undefined\n const [a, b] = node.args\n switch (node.name) {\n case 'eq':\n return collectEq(a, b)\n case 'in':\n return collectIn(a, b)\n case 'or':\n return collectOr(node.args)\n default:\n return undefined\n }\n}\n\n/**\n * The single-field subset a `where` selects when it is nothing but equalities on\n * one top-level field: `eq(field, x)`, `in(field, [...])`, or an `or` of those.\n * Anything else returns `undefined`.\n */\nexport function subsetFromWhere(\n where: IR.BasicExpression<boolean> | undefined | null\n): WhereSubset | undefined {\n if (!where) return undefined\n const subset = collect(where as unknown as Node)\n return subset ? { field: subset.field, values: [...new Set(subset.values)].sort() } : undefined\n}\n\n/** Whether a row's `field` is one of `wanted` (a multiple relation matches by containment). */\nexport function matchesSubset(row: object, field: string, wanted: ReadonlySet<string>): boolean {\n const value = (row as Record<string, unknown>)[field]\n if (typeof value === 'string') return wanted.has(value)\n if (Array.isArray(value))\n return value.some(item => typeof item === 'string' && wanted.has(item))\n return false\n}\n","import {\n type FieldPath,\n IR,\n type ParsedOrderBy,\n parseOrderByExpression,\n parseWhereExpression,\n} from '@tanstack/db'\n\ntype BasicExpression<T = unknown> = IR.BasicExpression<T>\n\nexport function escapeValue(value: unknown): string {\n if (value === null) {\n return 'null'\n }\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false'\n }\n if (typeof value === 'number') {\n return value.toString()\n }\n if (typeof value === 'string') {\n return `\"${value.replace(/\"/g, '\\\\\"')}\"`\n }\n if (value instanceof Date) {\n return `\"${value.toISOString()}\"`\n }\n if (Array.isArray(value)) {\n return `[${value.map(escapeValue).join(',')}]`\n }\n return `\"${String(value)}\"`\n}\n\nfunction fieldPathToString(path: FieldPath): string {\n return path.join('.')\n}\n\n// PocketBase has no boolean literals, so an empty `in` / `notIn` compiles to a constant comparison\nconst NEVER_MATCH = '1 = 2'\nconst ALWAYS_MATCH = '1 = 1'\n\nfunction membership(\n field: FieldPath,\n values: unknown,\n operator: '=' | '!=',\n joiner: '||' | '&&',\n empty: string\n): string {\n const valueArray = Array.isArray(values) ? values : [values]\n const fieldStr = fieldPathToString(field)\n const conditions = [...new Set(valueArray)].map(\n v => `${fieldStr} ${operator} ${escapeValue(v)}`\n )\n if (conditions.length === 0) return empty\n return conditions.length > 1 ? `(${conditions.join(` ${joiner} `)})` : conditions[0]\n}\n\nconst NEGATED_OPERATORS: Record<string, string> = {\n eq: 'neq',\n neq: 'eq',\n gt: 'lte',\n gte: 'lt',\n lt: 'gte',\n lte: 'gt',\n in: 'notIn',\n notIn: 'in',\n like: 'notLike',\n notLike: 'like',\n isNull: 'isNotNull',\n isUndefined: 'isNotNull',\n isNotNull: 'isNull',\n}\n\nfunction negate(expr: BasicExpression<boolean>): BasicExpression<boolean> {\n if (expr.type !== 'func') {\n throw new Error(\n `Unsupported operand '${expr.type}' inside not() for PocketBase filter conversion`\n )\n }\n if (expr.name === 'not') {\n return pushDownNot(expr.args[0])\n }\n if (expr.name === 'and' || expr.name === 'or') {\n return new IR.Func(expr.name === 'and' ? 'or' : 'and', expr.args.map(negate))\n }\n const negated = NEGATED_OPERATORS[expr.name]\n if (!negated) {\n throw new Error(`Unsupported operator 'not(${expr.name})' for PocketBase filter conversion`)\n }\n return new IR.Func(negated, expr.args)\n}\n\n// PocketBase filters have no prefix `!`, so negations are pushed down onto comparison operators\nfunction pushDownNot(expr: BasicExpression<boolean>): BasicExpression<boolean> {\n if (expr.type !== 'func') {\n return expr\n }\n if (expr.name === 'not') {\n return negate(expr.args[0])\n }\n if (expr.name === 'and' || expr.name === 'or') {\n return new IR.Func(expr.name, expr.args.map(pushDownNot))\n }\n return expr\n}\n\nexport function convertToPocketBaseFilter(\n where: BasicExpression<boolean> | undefined | null\n): string | undefined {\n if (!where) {\n return undefined\n }\n\n const result = parseWhereExpression(pushDownNot(where), {\n handlers: {\n eq: (field: FieldPath, value: unknown) => {\n return `${fieldPathToString(field)} = ${escapeValue(value)}`\n },\n gt: (field: FieldPath, value: unknown) => {\n return `${fieldPathToString(field)} > ${escapeValue(value)}`\n },\n gte: (field: FieldPath, value: unknown) => {\n return `${fieldPathToString(field)} >= ${escapeValue(value)}`\n },\n lt: (field: FieldPath, value: unknown) => {\n return `${fieldPathToString(field)} < ${escapeValue(value)}`\n },\n lte: (field: FieldPath, value: unknown) => {\n return `${fieldPathToString(field)} <= ${escapeValue(value)}`\n },\n and: (...conditions: string[]) => {\n if (conditions.length === 0) return ''\n if (conditions.length === 1) return conditions[0]\n return `(${conditions.join(' && ')})`\n },\n or: (...conditions: string[]) => {\n if (conditions.length === 0) return ''\n if (conditions.length === 1) return conditions[0]\n return `(${conditions.join(' || ')})`\n },\n neq: (field: FieldPath, value: unknown) => {\n return `${fieldPathToString(field)} != ${escapeValue(value)}`\n },\n in: (field: FieldPath, values: unknown) =>\n membership(field, values, '=', '||', NEVER_MATCH),\n notIn: (field: FieldPath, values: unknown) =>\n membership(field, values, '!=', '&&', ALWAYS_MATCH),\n notLike: (field: FieldPath, value: unknown) => {\n return `${fieldPathToString(field)} !~ ${escapeValue(value)}`\n },\n like: (field: FieldPath, value: unknown) => {\n return `${fieldPathToString(field)} ~ ${escapeValue(value)}`\n },\n isNull: (field: FieldPath) => {\n return `${fieldPathToString(field)} = null`\n },\n isUndefined: (field: FieldPath) => {\n return `${fieldPathToString(field)} = null`\n },\n isNotNull: (field: FieldPath) => {\n return `${fieldPathToString(field)} != null`\n },\n },\n onUnknownOperator: (operator: string, _args: unknown[]) => {\n throw new Error(\n `Unsupported operator '${operator}' for PocketBase filter conversion. ` +\n `Supported operators: eq, gt, gte, lt, lte, in, like, and, or, not, isNull, isUndefined`\n )\n },\n })\n\n return result || undefined\n}\n\nexport function convertToPocketBaseSort(\n orderBy: IR.OrderBy | undefined | null\n): string | undefined {\n if (!orderBy) {\n return undefined\n }\n\n const sorts = parseOrderByExpression(orderBy)\n\n if (sorts.length === 0) {\n return undefined\n }\n\n return sorts\n .map((sort: ParsedOrderBy) => {\n const field = fieldPathToString(sort.field)\n return sort.direction === 'desc' ? `-${field}` : field\n })\n .join(',')\n}\n","import type { RecordSubscribeOptions } from 'pocketbase'\nimport type { WhereSubset } from './keyed-where'\nimport { escapeValue } from './pocketbase-query-converter'\n\n// PocketBase refuses a filter over MaxFilterLength (3500 bytes) with a generic\n// 400, and a subset's size is the caller's data — a user's memberships, a\n// mailbox's threads. The margin below the server cap absorbs multi-byte values,\n// since `.length` counts UTF-16 units.\nconst MAX_FILTER_LENGTH = 2500\n\n// PocketBase caps a realtime subscription topic at 2500 characters, and the\n// SDK URI-encodes the filter into the topic at roughly 2.1x its length; this\n// leaves room for `expand` and factory headers in the same topic.\nexport const REALTIME_MAX_FILTER_LENGTH = 1000\n\n/** PocketBase rejects a realtime subscription topic longer than this. */\nexport const REALTIME_TOPIC_MAX_LENGTH = 2500\n\n// Option keys the PocketBase SDK keeps out of `query` (normalizeUnknownQueryParams).\nconst SDK_RESERVED_OPTIONS = new Set([\n 'requestKey',\n '$cancelKey',\n '$autoCancel',\n 'fetch',\n 'headers',\n 'body',\n 'query',\n 'params',\n 'cache',\n 'credentials',\n 'integrity',\n 'keepalive',\n 'method',\n 'mode',\n 'redirect',\n 'referrer',\n 'referrerPolicy',\n 'signal',\n 'window',\n])\n\n/**\n * The topic the PocketBase server expects for a wildcard subscription on\n * `collectionName` with `options`, built the way the JS SDK builds it:\n * every key the SDK does not reserve moves into `query`.\n */\nexport function realtimeTopic(\n collectionName: string,\n options: RecordSubscribeOptions | undefined\n): string {\n const topic = `${collectionName}/*`\n if (!options) return topic\n const query: Record<string, unknown> = { ...options.query }\n for (const [key, value] of Object.entries(options)) {\n if (!SDK_RESERVED_OPTIONS.has(key)) query[key] = value\n }\n const encoded = encodeURIComponent(JSON.stringify({ query, headers: options.headers }))\n return `${topic}?options=${encoded}`\n}\n\n/** Length of {@link realtimeTopic}; the server rejects one over `REALTIME_TOPIC_MAX_LENGTH`. */\nexport function realtimeTopicLength(\n collectionName: string,\n options: RecordSubscribeOptions | undefined\n): number {\n return realtimeTopic(collectionName, options).length\n}\n\n/**\n * The PocketBase filters that select `subset`, each short enough for the server\n * to accept: one when every value fits, more when they do not. `maxLength`\n * defaults to the REST fetch budget; pass `REALTIME_MAX_FILTER_LENGTH` when the\n * filters go to a realtime subscription instead.\n */\nexport function subsetFilters(\n { field, values }: WhereSubset,\n maxLength = MAX_FILTER_LENGTH\n): string[] {\n const filters: string[] = []\n let current = ''\n for (const value of values) {\n const clause = `${field} = ${escapeValue(value)}`\n const joined = current ? `${current} || ${clause}` : clause\n if (current && joined.length > maxLength) {\n filters.push(current)\n current = clause\n } else {\n current = joined\n }\n }\n if (current) filters.push(current)\n return filters\n}\n","import type PocketBase from 'pocketbase'\nimport {\n type BackRelationHead,\n backRelationHeads,\n type ExpandFiler,\n type FilingChange,\n stripFetchedRelations,\n} from './expand-filing'\nimport type { RelationTargets } from './expand-paths'\nimport { splitPaths } from './expand-paths'\nimport { matchesSubset, type WhereSubset } from './keyed-where'\nimport type { LoadedSubsets } from './loaded-subsets'\nimport { subsetFilters } from './pocketbase-limits'\nimport type { PbRequest } from './request'\n\nexport interface FetchDeps<T extends object> {\n pb: PocketBase\n collectionName: string\n relationTargets: RelationTargets | undefined\n /** The full expand string a request sends, alwaysFetchRelations included. */\n activeExpand: (request: PbRequest) => string | undefined\n syncedRow: (id: string) => T | undefined\n syncedRows: () => Iterable<T>\n subsets: Pick<LoadedSubsets, 'isLoaded'>\n filer: ExpandFiler\n}\n\nexport interface FetchResult<T> {\n rows: T[]\n /** True when the store answered and no request was sent. */\n fromStore: boolean\n /**\n * The filings this result made. Commit it after the rows land; undo it\n * when the result is discarded, so a discarded result changes nothing.\n */\n filings: FilingChange\n}\n\nexport interface FetchOptions {\n /**\n * Abort sources. An abort cancels every request of this load and\n * rejects with `FetchAbortedError`.\n */\n signals?: readonly AbortSignal[]\n /** Revalidate: send the request even when the store could answer it. */\n refetch?: boolean\n}\n\nexport interface Fetcher<T extends object> {\n /** Rows for `request`: relations filed into their targets, fetched expand stripped. */\n fetchRecords: (request: PbRequest, options?: FetchOptions) => Promise<FetchResult<T>>\n /**\n * The rows the store answers `request` with, or undefined when it cannot.\n * Synchronous: it does not wait for a parent's pending filing.\n */\n serveFromStore: (request: PbRequest) => T[] | undefined\n /**\n * A parent's fetch may file and mark `field` once `settles` resolves; a\n * fetch for a not-yet-loaded subset on that field waits for it first.\n * Returns the unregister function the parent runs once its fetch settles.\n */\n expectFiling: (field: string, settles: Promise<void>) => () => void\n}\n\nconst NO_FILINGS: FilingChange = { commit: () => undefined, undo: () => undefined }\n\n/** Thrown when `signal` aborted before the rows were installed. */\nexport class FetchAbortedError extends Error {\n constructor(collectionName: string) {\n super(`${collectionName}: fetch aborted`)\n this.name = 'AbortError'\n }\n}\n\n/** One load's cancellation: its own signal and the request keys it sent. */\ntype Cancel = { controller: AbortController; keys: string[] }\n\nexport function createFetcher<T extends object>(deps: FetchDeps<T>): Fetcher<T> {\n const { pb, collectionName, relationTargets, filer, subsets } = deps\n const pendingFilings = new Map<string, Promise<void>[]>()\n let requestSeq = 0\n\n function expectFiling(field: string, settles: Promise<void>): () => void {\n let pending = pendingFilings.get(field)\n if (!pending) {\n pending = []\n pendingFilings.set(field, pending)\n }\n pending.push(settles)\n return () => {\n const index = pending.indexOf(settles)\n if (index !== -1) pending.splice(index, 1)\n if (pending.length === 0) pendingFilings.delete(field)\n }\n }\n\n async function awaitPendingFiling(field: string): Promise<void> {\n const pending = pendingFilings.get(field)\n if (pending && pending.length > 0) await Promise.all(pending)\n }\n\n function rowsFromStore(ids: readonly string[]): T[] | undefined {\n const rows: T[] = []\n for (const id of ids) {\n const row = deps.syncedRow(id)\n if (!row) return undefined\n rows.push(row)\n }\n return rows\n }\n\n function fieldSubsetFromStore(subset: WhereSubset): T[] | undefined {\n if (!subsets.isLoaded(subset)) return undefined\n const wanted = new Set(subset.values)\n return [...deps.syncedRows()].filter(row => matchesSubset(row, subset.field, wanted))\n }\n\n // Stored rows were filed with alwaysFetchRelations already; only a view's\n // extra `request.expand` forces a fetch. An empty subset selects nothing\n // and must never become a request. A sorted and limited request must be\n // sliced in that order, which the store's id order cannot provide, and a\n // cursor is a boundary in that order too.\n function servedFromStore(request: PbRequest): T[] | undefined {\n const { subset, sort, limit } = request\n if (!subset) return undefined\n if (subset.values.length === 0) return []\n if (request.expand || request.cursor || (sort && limit)) return undefined\n const rows =\n subset.field === 'id' ? rowsFromStore(subset.values) : fieldSubsetFromStore(subset)\n return rows && limit ? rows.slice(0, limit) : rows\n }\n\n function withCursor(\n filter: string | undefined,\n cursor: string | undefined\n ): string | undefined {\n if (!cursor) return filter\n return filter ? `(${filter}) && (${cursor})` : cursor\n }\n\n // Each load and each chunk carry their own request key, so the SDK's\n // auto-cancellation never aborts a sibling chunk or a concurrent load. A\n // limited request returns each chunk's first rows unsliced: the live\n // query re-applies sort and limit. An offset without a cursor is a count\n // of rows already acquired; PocketBase pages by page number, so an\n // aligned offset becomes a page and any other offset is sliced from a\n // request that starts at row one.\n async function fetchPage(\n request: PbRequest,\n expand: string | undefined,\n chunkFilter: string | undefined,\n requestKey: string,\n offset: number,\n signal: AbortSignal\n ): Promise<T[]> {\n const { sort, limit } = request\n const filter = withCursor(chunkFilter, request.cursor)\n if (limit) {\n if (offset % limit === 0) {\n const result = await pb\n .collection(collectionName)\n .getList(offset / limit + 1, limit, {\n filter,\n sort,\n skipTotal: true,\n expand,\n requestKey,\n signal,\n })\n return result.items as unknown as T[]\n }\n const result = await pb.collection(collectionName).getList(1, offset + limit, {\n filter,\n sort,\n skipTotal: true,\n expand,\n requestKey,\n signal,\n })\n return (result.items as unknown as T[]).slice(offset)\n }\n const items = await pb\n .collection(collectionName)\n .getFullList({ filter, sort, expand, requestKey, signal })\n return (items as unknown as T[]).slice(offset)\n }\n\n function chunkRequest(\n request: PbRequest,\n chunks: number\n ): { request: PbRequest; offset: number } {\n const offset = request.offset ?? 0\n if (chunks === 1 || offset === 0) return { request, offset }\n const limit = request.limit ? offset + request.limit : undefined\n return { request: { ...request, limit }, offset: 0 }\n }\n\n async function fetchItems(\n request: PbRequest,\n heads: readonly BackRelationHead[],\n refetch: boolean,\n cancel: Cancel\n ): Promise<Omit<FetchResult<T>, 'filings'>> {\n const served = refetch ? undefined : servedFromStore(request)\n if (served) return { rows: served, fromStore: true }\n // Give a same-tick parent fetch the chance to file this subset first.\n // Invariant: a fetch that registers pending filings never waits on\n // them, or two mutually back-related collections deadlock.\n if (!refetch && request.subset && request.subset.field !== 'id' && heads.length === 0) {\n await awaitPendingFiling(request.subset.field)\n const servedAfterFiling = servedFromStore(request)\n if (servedAfterFiling) return { rows: servedAfterFiling, fromStore: true }\n }\n const filters = request.subset ? subsetFilters(request.subset) : [request.filter]\n const expand = deps.activeExpand(request)\n const chunk = chunkRequest(request, filters.length)\n const load = ++requestSeq\n const pages = await Promise.all(\n filters.map((chunkFilter, index) => {\n const requestKey = `${collectionName}:${load}:${index}`\n cancel.keys.push(requestKey)\n return fetchPage(\n chunk.request,\n expand,\n chunkFilter,\n requestKey,\n chunk.offset,\n cancel.controller.signal\n )\n })\n )\n const items = pages.flat()\n filer.markEmptyBackRelations(items, heads)\n return { rows: items, fromStore: false }\n }\n\n // The SDK replaces `signal` with its own per-`requestKey` controller\n // while auto-cancellation is on, and sends `signal` as given while it is\n // off. An abort does both, so the request is cancelled either way.\n async function fetchRecords(\n request: PbRequest,\n options: FetchOptions = {}\n ): Promise<FetchResult<T>> {\n const { signals = [] } = options\n const aborted = () => signals.some(signal => signal.aborted)\n const cancel: Cancel = { controller: new AbortController(), keys: [] }\n const onAbort = () => {\n cancel.controller.abort()\n for (const key of cancel.keys) pb.cancelRequest(key)\n }\n for (const signal of signals) signal.addEventListener('abort', onAbort, { once: true })\n let settleFiling: () => void = () => undefined\n const filed = new Promise<void>(resolve => {\n settleFiling = resolve\n })\n const heads = backRelationHeads(deps.activeExpand(request), relationTargets)\n const unregister = heads.map(({ target, field }) => target.expectFiling(field, filed))\n try {\n if (aborted()) throw new FetchAbortedError(collectionName)\n const result = await fetchItems(request, heads, options.refetch === true, cancel).catch(\n error => {\n if (aborted()) throw new FetchAbortedError(collectionName)\n throw error\n }\n )\n if (aborted()) throw new FetchAbortedError(collectionName)\n const filings = result.fromStore\n ? NO_FILINGS\n : await filer.fileExpanded(\n result.rows,\n relationTargets,\n splitPaths(deps.activeExpand(request))\n )\n if (aborted()) {\n filings.undo()\n throw new FetchAbortedError(collectionName)\n }\n return {\n rows: stripFetchedRelations(result.rows, deps.activeExpand(request)),\n fromStore: result.fromStore,\n filings,\n }\n } finally {\n for (const signal of signals) signal.removeEventListener('abort', onAbort)\n settleFiling()\n for (const fn of unregister) fn()\n }\n }\n\n return { fetchRecords, serveFromStore: servedFromStore, expectFiling }\n}\n","import { parseViaKey } from './expand-paths'\nimport { logger } from './logger'\nimport { REALTIME_MAX_FILTER_LENGTH, subsetFilters } from './pocketbase-limits'\nimport type { HeldTarget, RelationTarget } from './types'\n\n/**\n * A filing change that is recorded at once but settled later: `commit`\n * releases the rows the change stopped filing (run after the root row\n * lands); `undo` restores the previous filing and releases what the change\n * filed (run when the root row is discarded). Run one of the two, once.\n */\nexport interface FilingChange {\n commit: () => void\n undo: () => void\n}\n\n/**\n * Relation targets a collection holds live while its own subscription is\n * open, and what each parent row filed into them. A filed row stays in its\n * target while at least one parent row in this collection's store files\n * it; the hold's realtime filters cover exactly the current filings.\n */\nexport interface HeldTargets {\n /**\n * Root row `rootId` of this collection now files exactly `rowIds` into\n * `target` under expand path `key` (`author`, `author.publisher`), with\n * realtime filters on `filterValues`: the row ids for a forward\n * relation (the default), the immediate parent ids for a back-relation.\n * Recorded at once; the returned change is committed once the root row\n * has landed, so a parent is never visible without its relation, or\n * undone when the root row is discarded.\n */\n setFiled: (\n rootId: string,\n target: RelationTarget,\n key: string,\n rowIds: Iterable<string>,\n filterValues?: Iterable<string>\n ) => FilingChange\n /** Root row `rootId` left the store: release everything it filed, at every depth. */\n forgetParentRow: (rootId: string) => void\n /** Hold exactly `desired`; release every other held target. */\n sync: (desired: Set<RelationTarget>) => void\n releaseAll: () => void\n /** Forget every filing without releasing; the store that held them is gone. */\n clearFiled: () => void\n count: () => number\n}\n\ntype Filing = { rows: Set<string>; filters: Set<string> }\ntype Filed = Map<RelationTarget, Map<string, Filing>>\n\nexport function createHeldTargets(collectionName: string, holder: object): HeldTargets {\n const held = new Map<RelationTarget, HeldTarget>()\n const filings = new Map<string, Filed>()\n /** Per target: how many (root, key) filings reference each filed row. */\n const rowRefs = new Map<RelationTarget, Map<string, number>>()\n /** Per target: field → value → how many filings need that realtime filter. */\n const filterRefs = new Map<RelationTarget, Map<string, Map<string, number>>>()\n\n function filtersFor(target: RelationTarget): string[] {\n const byField = filterRefs.get(target)\n if (!byField) return []\n const filters: string[] = []\n for (const [field, values] of byField) {\n if (values.size === 0) continue\n filters.push(\n ...subsetFilters({ field, values: [...values.keys()] }, REALTIME_MAX_FILTER_LENGTH)\n )\n }\n return filters\n }\n\n function bump<K>(counts: Map<K, number>, key: K, delta: 1 | -1): boolean {\n const next = (counts.get(key) ?? 0) + delta\n if (next <= 0) {\n counts.delete(key)\n return delta < 0\n }\n counts.set(key, next)\n return delta > 0 && next === 1\n }\n\n function filterRef(\n target: RelationTarget,\n field: string,\n value: string,\n delta: 1 | -1\n ): boolean {\n let byField = filterRefs.get(target)\n if (!byField) {\n byField = new Map()\n filterRefs.set(target, byField)\n }\n let values = byField.get(field)\n if (!values) {\n values = new Map()\n byField.set(field, values)\n }\n return bump(values, value, delta)\n }\n\n function rowRef(target: RelationTarget, id: string, delta: 1 | -1): boolean {\n let counts = rowRefs.get(target)\n if (!counts) {\n counts = new Map()\n rowRefs.set(target, counts)\n }\n return bump(counts, id, delta)\n }\n\n function filedUnder(rootId: string, target: RelationTarget): Map<string, Filing> {\n let byTarget = filings.get(rootId)\n if (!byTarget) {\n byTarget = new Map()\n filings.set(rootId, byTarget)\n }\n let byKey = byTarget.get(target)\n if (!byKey) {\n byKey = new Map()\n byTarget.set(target, byKey)\n }\n return byKey\n }\n\n /** The realtime field a path's last segment filters on: the parent field of a back-relation, else `id`. */\n function fieldFor(key: string): string {\n const last = key.split('.').at(-1) ?? key\n return parseViaKey(last)?.field ?? 'id'\n }\n\n function diff<V>(previous: Set<V>, next: Set<V>): { added: V[]; removed: V[] } {\n return {\n added: [...next].filter(value => !previous.has(value)),\n removed: [...previous].filter(value => !next.has(value)),\n }\n }\n\n /** Move the filter refs from `previous` to `next`; true when the target's filter list changed. */\n function swapFilterRefs(\n target: RelationTarget,\n field: string,\n previous: Set<string>,\n next: Set<string>\n ): boolean {\n const { added, removed } = diff(previous, next)\n let changed = false\n for (const value of added) if (filterRef(target, field, value, 1)) changed = true\n for (const value of removed) if (filterRef(target, field, value, -1)) changed = true\n return changed\n }\n\n /** Move the row refs from `previous` to `next`; returns the rows that reached zero. */\n function swapRowRefs(\n target: RelationTarget,\n previous: Set<string>,\n next: Set<string>\n ): string[] {\n const { added, removed } = diff(previous, next)\n for (const id of added) rowRef(target, id, 1)\n return removed.filter(id => rowRef(target, id, -1))\n }\n\n function dropEntry(rootId: string, target: RelationTarget, key: string): void {\n const byTarget = filings.get(rootId)\n const byKey = byTarget?.get(target)\n byKey?.delete(key)\n if (byKey?.size === 0) byTarget?.delete(target)\n if (byTarget?.size === 0) filings.delete(rootId)\n }\n\n function setFiled(\n rootId: string,\n target: RelationTarget,\n key: string,\n rowIds: Iterable<string>,\n filterValues?: Iterable<string>\n ): FilingChange {\n const rows = new Set(rowIds)\n const next: Filing = { rows, filters: new Set(filterValues ?? rows) }\n const byKey = filedUnder(rootId, target)\n const before = byKey.get(key)\n const previous = before ?? { rows: new Set<string>(), filters: new Set<string>() }\n byKey.set(key, next)\n const released = swapRowRefs(target, previous.rows, next.rows)\n if (swapFilterRefs(target, fieldFor(key), previous.filters, next.filters)) {\n held.get(target)?.setFilters(filtersFor(target))\n }\n return {\n // Another root may file one of these rows again before the\n // commit, so it releases only the rows still at zero then.\n commit: () => {\n const counts = rowRefs.get(target)\n const unreferenced = released.filter(id => !counts?.has(id))\n if (unreferenced.length > 0) target.releaseFiled(unreferenced, holder)\n },\n // Only while this change is still the current filing: a later\n // change owns the state after it.\n undo: () => {\n if (byKey.get(key) !== next) return\n setFiled(rootId, target, key, previous.rows, previous.filters).commit()\n if (!before) dropEntry(rootId, target, key)\n },\n }\n }\n\n function forgetParentRow(rootId: string): void {\n const byTarget = filings.get(rootId)\n if (!byTarget) return\n for (const [target, byKey] of byTarget) {\n for (const key of [...byKey.keys()]) setFiled(rootId, target, key, [], []).commit()\n }\n filings.delete(rootId)\n }\n\n function release(target: RelationTarget): void {\n const hold = held.get(target)\n if (!hold) return\n held.delete(target)\n try {\n hold.release()\n } catch (error) {\n logger.error('Failed to release relation target subscription', {\n collectionName,\n error,\n })\n }\n }\n\n function hold(target: RelationTarget): void {\n if (held.has(target)) return\n try {\n const hold = target.holdLive(holder)\n held.set(target, hold)\n hold.setFilters(filtersFor(target))\n } catch (error) {\n logger.error('Failed to hold relation target subscription', { collectionName, error })\n }\n }\n\n function sync(desired: Set<RelationTarget>): void {\n for (const target of [...held.keys()]) if (!desired.has(target)) release(target)\n for (const target of desired) hold(target)\n }\n\n return {\n setFiled,\n forgetParentRow,\n sync,\n releaseAll: () => sync(new Set()),\n clearFiled: () => {\n filings.clear()\n rowRefs.clear()\n filterRefs.clear()\n },\n count: () => held.size,\n }\n}\n","import { idOf, idsOf, updatedAtOf } from './records'\n\n/** Something that keeps a row in the store: a subset, a topic filter, a hold, or a sentinel. */\nexport type Holder = object | string\n\n/** Rows a retain or replace must write: new to the store, or replaced in it. */\nexport interface LedgerWrites<T> {\n inserted: T[]\n updated: T[]\n}\n\n/** The ledger changes made since `track()`, kept or undone as one unit. */\nexport interface LedgerChange {\n commit: () => void\n rollback: () => void\n}\n\n/**\n * Every synced row with the holders that reference it. A row is in the store\n * while at least one holder references it.\n */\nexport interface Ledger<T extends object> {\n row: (id: string) => T | undefined\n has: (id: string) => boolean\n rows: () => IterableIterator<T>\n size: () => number\n idsOf: (holder: Holder) => string[]\n holderCount: (id: string) => number\n /**\n * Reference `rows` for `holder`. A row that is new or not older is stored\n * as a new object: the stored row merged with the incoming one.\n */\n retain: (holder: Holder, rows: readonly T[]) => LedgerWrites<T>\n /** Replace stored rows with `rows` under the same rule as `retain`, adding no holder; a row not stored is skipped. */\n refresh: (rows: readonly T[]) => LedgerWrites<T>\n /** Drop `holder`'s reference to `ids` (all of them when omitted). Returns ids with no holder left, now removed. */\n release: (holder: Holder, ids?: Iterable<string>) => string[]\n /** Set `holder`'s references to exactly `rows`. */\n replace: (holder: Holder, rows: readonly T[]) => LedgerWrites<T> & { removed: string[] }\n /** Reference the stored rows among `ids` for `holder`, writing nothing. */\n hold: (holder: Holder, ids: Iterable<string>) => void\n /** Remove the row from every holder. False when absent. */\n releaseAll: (id: string) => boolean\n /** Every holder that references at least one row. */\n holders: () => Holder[]\n /** Record every change from now on, so the caller can undo it if its sync write throws. */\n track: () => LedgerChange\n clear: () => void\n}\n\n/** Rows a mutation write-back or `accept()` landed; released once a subset or topic covers them. */\nexport const ACCEPTED: Holder = { holder: 'accepted' }\n/** The whole collection, in eager mode. */\nexport const EAGER: Holder = { holder: 'eager' }\n\ntype Entry<T> = { row: T; holders: Set<Holder> }\n\nexport function createLedger<T extends object>(): Ledger<T> {\n const entries = new Map<string, Entry<T>>()\n const byHolder = new Map<Holder, Set<string>>()\n let journal: (() => void)[] | undefined\n\n function link(id: string, entry: Entry<T>, holder: Holder): void {\n if (entry.holders.has(holder)) return\n entry.holders.add(holder)\n let ids = byHolder.get(holder)\n if (!ids) {\n ids = new Set()\n byHolder.set(holder, ids)\n }\n ids.add(id)\n journal?.push(() => unlink(id, entry, holder))\n }\n\n function unlink(id: string, entry: Entry<T>, holder: Holder): void {\n if (!entry.holders.delete(holder)) return\n const ids = byHolder.get(holder)\n ids?.delete(id)\n if (ids?.size === 0) byHolder.delete(holder)\n journal?.push(() => link(id, entry, holder))\n }\n\n function put(id: string, entry: Entry<T>): void {\n entries.set(id, entry)\n journal?.push(() => {\n entries.delete(id)\n })\n }\n\n function remove(id: string, entry: Entry<T>): void {\n entries.delete(id)\n journal?.push(() => {\n entries.set(id, entry)\n })\n }\n\n function setRow(entry: Entry<T>, row: T): void {\n const previous = entry.row\n entry.row = row\n journal?.push(() => {\n entry.row = previous\n })\n }\n\n function isOlder(incoming: T, current: T): boolean {\n const next = updatedAtOf(incoming)\n const now = updatedAtOf(current)\n return next !== undefined && now !== undefined && next < now\n }\n\n // The collection declares rowUpdateMode 'full', so core stores the\n // written object as is. Merging here keeps a partial realtime payload\n // (a factory `fields` option) from dropping fields, and keeps this row\n // equal to core's.\n function update(entry: Entry<T>, incoming: T, writes: LedgerWrites<T>): void {\n if (entry.row === incoming || isOlder(incoming, entry.row)) return\n setRow(entry, { ...entry.row, ...incoming })\n writes.updated.push(entry.row)\n }\n\n function retain(holder: Holder, rows: readonly T[]): LedgerWrites<T> {\n const writes: LedgerWrites<T> = { inserted: [], updated: [] }\n for (const incoming of rows) {\n const id = idOf(incoming)\n if (id === undefined) continue\n const entry = entries.get(id)\n if (!entry) {\n const created: Entry<T> = { row: { ...incoming }, holders: new Set() }\n put(id, created)\n link(id, created, holder)\n writes.inserted.push(created.row)\n continue\n }\n link(id, entry, holder)\n update(entry, incoming, writes)\n }\n return writes\n }\n\n function refresh(rows: readonly T[]): LedgerWrites<T> {\n const writes: LedgerWrites<T> = { inserted: [], updated: [] }\n for (const incoming of rows) {\n const id = idOf(incoming)\n const entry = id === undefined ? undefined : entries.get(id)\n if (entry) update(entry, incoming, writes)\n }\n return writes\n }\n\n function release(holder: Holder, ids?: Iterable<string>): string[] {\n const held = byHolder.get(holder)\n if (!held) return []\n const removed: string[] = []\n for (const id of ids ? [...ids] : [...held]) {\n const entry = entries.get(id)\n if (!entry || !held.has(id)) continue\n unlink(id, entry, holder)\n if (entry.holders.size === 0) {\n remove(id, entry)\n removed.push(id)\n }\n }\n return removed\n }\n\n return {\n row: id => entries.get(id)?.row,\n has: id => entries.has(id),\n rows: function* rows() {\n for (const entry of entries.values()) yield entry.row\n },\n size: () => entries.size,\n idsOf: holder => [...(byHolder.get(holder) ?? [])],\n holderCount: id => entries.get(id)?.holders.size ?? 0,\n retain,\n refresh,\n release,\n replace(holder, rows) {\n const keep = new Set(idsOf(rows))\n const stale = [...(byHolder.get(holder) ?? [])].filter(id => !keep.has(id))\n const writes = retain(holder, rows)\n return { ...writes, removed: release(holder, stale) }\n },\n hold(holder, ids) {\n for (const id of ids) {\n const entry = entries.get(id)\n if (entry) link(id, entry, holder)\n }\n },\n releaseAll(id) {\n const entry = entries.get(id)\n if (!entry) return false\n for (const holder of [...entry.holders]) unlink(id, entry, holder)\n remove(id, entry)\n return true\n },\n holders: () => [...byHolder.keys()],\n track() {\n const undo: (() => void)[] = []\n journal = undo\n const stop = () => {\n if (journal === undo) journal = undefined\n }\n return {\n commit() {\n stop()\n undo.length = 0\n },\n rollback() {\n stop()\n for (const step of undo.reverse()) step()\n undo.length = 0\n },\n }\n },\n clear() {\n entries.clear()\n byHolder.clear()\n },\n }\n}\n","import type { WhereSubset } from './keyed-where'\n\n/**\n * Field → values whose subset is known complete in the store, so a query on\n * that subset is served without a request (see docs/internals.md,\n * \"Loaded-subset marks\").\n */\nexport interface LoadedSubsets {\n mark: (field: string, value: string) => void\n count: () => number\n isLoaded: (subset: WhereSubset) => boolean\n /** Forget the marks a removed row belonged to. */\n forgetRow: (row: unknown) => void\n clear: () => void\n}\n\nexport function createLoadedSubsets(): LoadedSubsets {\n const marks = new Map<string, Set<string>>()\n\n function forgetValue(marked: Set<string>, value: unknown): void {\n if (typeof value === 'string') marked.delete(value)\n else if (Array.isArray(value)) {\n for (const item of value) if (typeof item === 'string') marked.delete(item)\n }\n }\n\n return {\n mark(field, value) {\n let values = marks.get(field)\n if (!values) {\n values = new Set()\n marks.set(field, values)\n }\n values.add(value)\n },\n count() {\n let count = 0\n for (const values of marks.values()) count += values.size\n return count\n },\n isLoaded({ field, values }) {\n const marked = marks.get(field)\n return marked !== undefined && values.every(value => marked.has(value))\n },\n forgetRow(row) {\n if (!row || typeof row !== 'object') return\n for (const [field, marked] of marks) {\n forgetValue(marked, (row as Record<string, unknown>)[field])\n }\n },\n clear() {\n marks.clear()\n },\n }\n}\n","import { ACCEPTED, type Holder, type Ledger, type LedgerWrites } from './ledger'\nimport { idOf, idsOf } from './records'\nimport type { SyncedStore, SyncWrite } from './synced-store'\n\n/** A commit receipt, or false when no sync session is running. */\nexport type Applied = true | Promise<void> | false\n\nexport interface MembershipDeps<T extends object> {\n collectionName: string\n ledger: Ledger<T>\n store: SyncedStore<T>\n /** Rows that left the store, for mark bookkeeping. */\n onRemoved: (rows: readonly T[]) => void\n}\n\n/**\n * Ledger changes as sync transactions. Every row the store gains or loses\n * goes through here (see docs/internals.md, \"Ledger\").\n */\nexport interface Membership<T extends object> {\n /** Reference `rows` for `holder`; new and newer rows are written. */\n land: (holder: Holder, rows: readonly T[]) => Applied\n /**\n * Land server-confirmed rows. A row nothing holds yet takes the\n * `ACCEPTED` holder; a row already held is refreshed in place and gains\n * no holder, so a write-back never outlives the holders a query or\n * topic gave the row.\n */\n accept: (rows: readonly T[]) => Applied\n /**\n * Make `rows` exactly what `holder` references; rows it no longer holds\n * may leave. `releaseAlso` holders release `rows` in the same\n * transaction; `holder` keeps each of them, so none leaves.\n */\n reconcile: (holder: Holder, rows: readonly T[], releaseAlso?: readonly Holder[]) => Applied\n /** Release `holders` from the `ids` that `keeper` references; `keeper` keeps each row. */\n confirm: (keeper: Holder, holders: readonly Holder[], ids: Iterable<string>) => Applied\n /** Release `ids` (all of theirs when omitted) from `holders`; rows at zero leave. */\n drop: (holders: readonly Holder[], ids?: Iterable<string>) => Applied\n /** Remove `ids` from every holder. */\n dropAll: (ids: Iterable<string>) => Applied\n /** Reference the stored rows among `ids` for each of `holders`; no row changes. */\n hold: (holders: readonly Holder[], ids: Iterable<string>) => Applied\n}\n\ntype Change<T> = { writes: SyncWrite<T>[]; gone: T[] }\n\nconst NO_WRITES = { inserted: [], updated: [] }\n\nexport function createMembership<T extends object>(deps: MembershipDeps<T>): Membership<T> {\n const { ledger, store } = deps\n\n // One write per id, in input order rather than insert/update bucket\n // order: a duplicate id in `rows` must write once, not once per\n // occurrence, and always as the final ledger row, since that is the\n // object core tracks by identity once the transaction lands.\n function writesFor(\n rows: readonly T[],\n changes: LedgerWrites<T>,\n removed: readonly string[]\n ): SyncWrite<T>[] {\n const inserted = new Set(changes.inserted.map(idOf))\n const updated = new Set(changes.updated.map(idOf))\n const seen = new Set<string>()\n const writes: SyncWrite<T>[] = []\n for (const row of rows) {\n const id = idOf(row)\n if (id === undefined || seen.has(id) || !(inserted.has(id) || updated.has(id))) continue\n const stored = ledger.row(id)\n if (stored === undefined) continue\n seen.add(id)\n writes.push({ type: inserted.has(id) ? 'insert' : 'update', value: stored })\n }\n for (const key of removed) writes.push({ type: 'delete', key })\n return writes\n }\n\n function rowsBefore(ids: readonly string[]): Map<string, T> {\n const rows = new Map<string, T>()\n for (const id of ids) {\n const row = ledger.row(id)\n if (row) rows.set(id, row)\n }\n return rows\n }\n\n function pick(rows: Map<string, T>, ids: readonly string[]): T[] {\n return ids.map(id => rows.get(id)).filter((row): row is T => row !== undefined)\n }\n\n // Releases a holder from rows another holder still references, so no row\n // can reach zero; a removal here is a bug and rolls the change back.\n function releaseKept(keeper: Holder, holders: readonly Holder[], ids: Iterable<string>): void {\n const kept = new Set(ledger.idsOf(keeper))\n const covered = [...ids].filter(id => kept.has(id))\n for (const holder of holders) {\n const removed = ledger.release(holder, covered)\n if (removed.length > 0) {\n throw new Error(\n `${deps.collectionName}: releasing a kept row removed ${removed.join(', ')}`\n )\n }\n }\n }\n\n // The ledger change and its sync transaction succeed or fail together:\n // a throwing write rolls the ledger back, so the two never disagree.\n function apply(change: () => Change<T>): Applied {\n if (!store.isAttached()) return false\n const tracked = ledger.track()\n let receipt: Applied\n let gone: T[]\n try {\n const result = change()\n gone = result.gone\n receipt = store.transact(result.writes)\n } catch (error) {\n tracked.rollback()\n throw error\n }\n tracked.commit()\n if (gone.length > 0) deps.onRemoved(gone)\n return receipt\n }\n\n return {\n land: (holder, rows) =>\n apply(() => ({ writes: writesFor(rows, ledger.retain(holder, rows), []), gone: [] })),\n accept: rows =>\n apply(() => {\n const held = new Set(idsOf(rows).filter(id => ledger.has(id)))\n const fresh = rows.filter(row => !held.has(idOf(row) ?? ''))\n const stale = rows.filter(row => held.has(idOf(row) ?? ''))\n const retained = ledger.retain(ACCEPTED, fresh)\n const refreshed = ledger.refresh(stale)\n const changes = {\n inserted: [...retained.inserted, ...refreshed.inserted],\n updated: [...retained.updated, ...refreshed.updated],\n }\n return { writes: writesFor(rows, changes, []), gone: [] }\n }),\n reconcile: (holder, rows, releaseAlso = []) =>\n apply(() => {\n const before = rowsBefore(ledger.idsOf(holder))\n const { removed, ...changes } = ledger.replace(holder, rows)\n releaseKept(holder, releaseAlso, idsOf(rows))\n return { writes: writesFor(rows, changes, removed), gone: pick(before, removed) }\n }),\n confirm: (keeper, holders, ids) =>\n apply(() => {\n releaseKept(keeper, holders, ids)\n return { writes: [], gone: [] }\n }),\n drop: (holders, ids) =>\n apply(() => {\n const listed = ids ? [...ids] : undefined\n const removed: string[] = []\n const gone: T[] = []\n for (const holder of holders) {\n const held = listed ?? ledger.idsOf(holder)\n const before = rowsBefore(held)\n const released = ledger.release(holder, held)\n removed.push(...released)\n gone.push(...pick(before, released))\n }\n return { writes: writesFor([], NO_WRITES, removed), gone }\n }),\n hold: (holders, ids) =>\n apply(() => {\n const listed = [...ids]\n for (const holder of holders) ledger.hold(holder, listed)\n return { writes: [], gone: [] }\n }),\n dropAll: ids =>\n apply(() => {\n const present = [...new Set(ids)].filter(id => ledger.has(id))\n const gone = pick(rowsBefore(present), present)\n for (const id of present) ledger.releaseAll(id)\n return { writes: writesFor([], NO_WRITES, present), gone }\n }),\n }\n}\n","/** Reference counts keyed by filter string. */\nexport class RefCounter {\n private readonly counts = new Map<string, number>()\n\n add(key: string): void {\n this.counts.set(key, (this.counts.get(key) ?? 0) + 1)\n }\n\n /** Drops one reference. Returns true when none remain. */\n drop(key: string): boolean {\n const count = (this.counts.get(key) ?? 0) - 1\n if (count > 0) {\n this.counts.set(key, count)\n return false\n }\n this.counts.delete(key)\n return true\n }\n\n has(key: string): boolean {\n return this.counts.has(key)\n }\n\n keys(): IterableIterator<string> {\n return this.counts.keys()\n }\n\n clear(): void {\n this.counts.clear()\n }\n}\n","import type { RecordSubscribeOptions, RecordSubscription } from 'pocketbase'\nimport { RefCounter } from './filter-refs'\nimport { logger } from './logger'\nimport { REALTIME_TOPIC_MAX_LENGTH, realtimeTopicLength } from './pocketbase-limits'\nimport type { Transport } from './transport'\n\nexport interface RealtimeSubscriptionDeps<T extends object> {\n transport: Transport\n collectionName: string\n /**\n * An event, the topic that delivered it (`'*'` or the filter string)\n * and the expand the delivering entry was opened with.\n */\n handleEvent: (event: RecordSubscription<T>, topic: string, expand: string | undefined) => void\n /** The expand union the next subscribe carries; pure, compared to detect drift. */\n pendingExpand: () => string | undefined\n /** Options for the next subscribe attempt; calls the factory callback. */\n subscribeOptions: () => RecordSubscribeOptions | undefined\n /** An entry opened, so the collections its expand reaches should be held. */\n onEntryOpened: () => void\n /**\n * The topic's entry is closed and the topic is no longer wanted, so the\n * rows it delivered lose that topic's holder. Not called for a restart,\n * which reopens the same topic.\n */\n onEntryClosed: (topic: string) => void\n /** Nothing is open and nothing is wanted. */\n onIdle: () => void\n}\n\n/**\n * The PocketBase realtime entries for one collection. The `'*'` entry covers\n * the whole collection; a filter entry covers one query filter. Filter entries\n * stay closed while `'*'` is open. Every change to what is wanted goes through\n * `reconcile`, which serializes all open and close work on one promise tail.\n */\nexport interface RealtimeSubscription {\n /** Counted subscribers want the whole collection. */\n addCollectionSubscriber: () => void\n dropCollectionSubscriber: () => void\n /** A query's filters, or `undefined` for the whole collection. Refs are zeroed on sync cleanup. */\n retainQueryFilters: (filters: readonly string[] | undefined) => void\n releaseQueryFilters: (filters: readonly string[] | undefined) => void\n resetQueryFilters: () => void\n /** Filters a parent's hold on this collection wants; they outlive the sync session. */\n swapHoldFilters: (previous: readonly string[], next: readonly string[]) => void\n reconcile: () => void\n /** Close every open entry and reopen what is wanted; a no-op when nothing is live. */\n restart: () => void\n isOpen: () => boolean\n /** Resolves once an entry is open; rejects when none opens within `timeout`. */\n wait: (timeout?: number) => Promise<void>\n}\n\nexport function createRealtimeSubscription<T extends object>(\n deps: RealtimeSubscriptionDeps<T>\n): RealtimeSubscription {\n const { collectionName } = deps\n\n let starUnsubscribe: (() => Promise<void>) | null = null\n let starExpand: string | undefined\n const filterEntries = new Map<\n string,\n { unsubscribe: () => Promise<void>; expand: string | undefined }\n >()\n const waiters = new Set<() => void>()\n\n let collectionSubscribers = 0\n let unfilteredQueryRefs = 0\n const queryRefs = new RefCounter()\n const holdRefs = new RefCounter()\n // Wanted filters whose topic is over PocketBase's cap. The realtime\n // client rejects an oversized topic before sending it, so these widen\n // to '*' instead.\n const oversizedFilters = new Set<string>()\n // Topics that opened at least once, so the ledger may hold rows under them.\n const delivered = new Set<string>()\n\n const isStarOpen = () => starUnsubscribe !== null\n const isOpen = () => isStarOpen() || filterEntries.size > 0\n const wantedFilters = () => new Set([...queryRefs.keys(), ...holdRefs.keys()])\n const wantsStar = () =>\n collectionSubscribers > 0 || unfilteredQueryRefs > 0 || oversizedFilters.size > 0\n\n function dropRef(refs: RefCounter, filter: string): void {\n if (refs.drop(filter) && !queryRefs.has(filter) && !holdRefs.has(filter)) {\n oversizedFilters.delete(filter)\n }\n }\n\n function notifyOpened(): void {\n deps.onEntryOpened()\n for (const resolve of waiters) resolve()\n waiters.clear()\n }\n\n // A failed step is logged and never poisons the tail.\n let work: Promise<void> = Promise.resolve()\n function enqueue(fn: () => Promise<void>): void {\n work = work.then(fn, fn).catch(error => {\n logger.error('Subscription work failed', { collectionName, error })\n })\n }\n\n async function openStar(): Promise<void> {\n if (isStarOpen()) return\n const expand = deps.pendingExpand()\n try {\n starUnsubscribe = await deps.transport.subscribe<T>(\n collectionName,\n deps.subscribeOptions(),\n event => deps.handleEvent(event, '*', expand)\n )\n delivered.add('*')\n starExpand = expand\n logger.debug('Subscription started', { collectionName })\n notifyOpened()\n } catch (error) {\n logger.error('Failed to start subscription', { collectionName, error })\n }\n }\n\n async function closeStar(): Promise<void> {\n const unsubscribe = starUnsubscribe\n if (!unsubscribe) return\n // Cleared first: a throwing unsubscribe must not leave the entry open.\n starUnsubscribe = null\n starExpand = undefined\n try {\n await unsubscribe()\n logger.debug('Subscription stopped', { collectionName })\n } catch (error) {\n logger.debug('Unsubscribe failed (expected if connection closed)', {\n collectionName,\n error,\n })\n }\n }\n\n // A factory-supplied filter narrows every entry; the query filter narrows\n // further, so the two are conjoined.\n function filteredOptions(filter: string): RecordSubscribeOptions {\n const base = deps.subscribeOptions()\n const combined = base?.filter ? `(${base.filter}) && (${filter})` : filter\n return { ...base, filter: combined }\n }\n\n async function openFilter(filter: string): Promise<void> {\n if (filterEntries.has(filter)) return\n const options = filteredOptions(filter)\n const expand = deps.pendingExpand()\n try {\n const unsubscribe = await deps.transport.subscribe<T>(collectionName, options, event =>\n deps.handleEvent(event, filter, expand)\n )\n delivered.add(filter)\n filterEntries.set(filter, { unsubscribe, expand })\n logger.debug('Filtered subscription started', { collectionName, filter })\n notifyOpened()\n } catch (error) {\n logger.error('Failed to start filtered subscription', {\n collectionName,\n filter,\n error,\n })\n }\n }\n\n async function closeFilter(filter: string): Promise<void> {\n const entry = filterEntries.get(filter)\n if (!entry) return\n filterEntries.delete(filter)\n try {\n await entry.unsubscribe()\n logger.debug('Filtered subscription stopped', { collectionName, filter })\n } catch (error) {\n logger.debug('Unsubscribe failed (expected if connection closed)', {\n collectionName,\n filter,\n error,\n })\n }\n }\n\n async function closeFilters(keep: (filter: string) => boolean = () => false): Promise<void> {\n await Promise.all([...filterEntries.keys()].filter(f => !keep(f)).map(closeFilter))\n }\n\n // A topic's rows stay held while its entry is open or the topic is still\n // wanted: a restart reopens the same topic, and a filter closed because\n // '*' opened comes back when '*' is no longer wanted. Runs after every\n // close in the pass has settled.\n function releaseClosedTopics(): void {\n const wanted = wantedFilters()\n for (const topic of delivered) {\n const live =\n topic === '*'\n ? isStarOpen() || wantsStar()\n : filterEntries.has(topic) || wanted.has(topic)\n if (live) continue\n delivered.delete(topic)\n deps.onEntryClosed(topic)\n }\n }\n\n // Oversized filters are found first, synchronously, so one pass can\n // decide between '*' and filter entries before any request goes out.\n async function openWantedFilters(): Promise<void> {\n if (wantsStar()) return\n const wanted = [...wantedFilters()]\n for (const filter of wanted) {\n if (filterEntries.has(filter) || oversizedFilters.has(filter)) continue\n const topicLength = realtimeTopicLength(collectionName, filteredOptions(filter))\n if (topicLength > REALTIME_TOPIC_MAX_LENGTH) {\n oversizedFilters.add(filter)\n logger.warn('Realtime filter too long; subscribing to the whole collection', {\n collectionName,\n filterLength: filter.length,\n topicLength,\n })\n }\n }\n if (wantsStar()) return\n await Promise.all(wanted.map(openFilter))\n }\n\n // The expand union can grow while a subscribe call is in flight.\n function expandDrifted(): boolean {\n const pending = deps.pendingExpand()\n if (isStarOpen() && starExpand !== pending) return true\n for (const entry of filterEntries.values()) if (entry.expand !== pending) return true\n return false\n }\n\n // The single place entries are opened or closed. Wanted entries open\n // before unwanted ones close: an overlap duplicates events, a gap loses\n // them. A filter found oversized while opening flips wantsStar in this pass.\n async function doReconcile(): Promise<void> {\n await openWantedFilters()\n if (wantsStar()) {\n await openStar()\n if (isStarOpen()) await closeFilters()\n } else {\n await closeStar()\n const wanted = wantedFilters()\n await closeFilters(filter => wanted.has(filter))\n }\n releaseClosedTopics()\n if (!isOpen() && !wantsStar() && wantedFilters().size === 0) deps.onIdle()\n if (expandDrifted()) restart()\n }\n\n async function doRestart(): Promise<void> {\n if (!isOpen()) return\n await closeStar()\n await closeFilters()\n await doReconcile()\n }\n\n const reconcile = () => enqueue(doReconcile)\n const restart = () => enqueue(doRestart)\n\n return {\n addCollectionSubscriber() {\n collectionSubscribers += 1\n },\n dropCollectionSubscriber() {\n collectionSubscribers -= 1\n },\n retainQueryFilters(filters) {\n if (!filters) unfilteredQueryRefs += 1\n else for (const filter of filters) queryRefs.add(filter)\n reconcile()\n },\n releaseQueryFilters(filters) {\n if (!filters) unfilteredQueryRefs -= 1\n else for (const filter of filters) dropRef(queryRefs, filter)\n reconcile()\n },\n resetQueryFilters() {\n queryRefs.clear()\n unfilteredQueryRefs = 0\n for (const filter of oversizedFilters) {\n if (!holdRefs.has(filter)) oversizedFilters.delete(filter)\n }\n reconcile()\n },\n swapHoldFilters(previous, next) {\n for (const filter of next) if (!previous.includes(filter)) holdRefs.add(filter)\n for (const filter of previous) if (!next.includes(filter)) dropRef(holdRefs, filter)\n reconcile()\n },\n reconcile,\n restart,\n isOpen,\n wait(timeout = 5000) {\n if (isOpen()) return Promise.resolve()\n return new Promise((resolve, reject) => {\n const onOpen = () => {\n clearTimeout(timer)\n resolve()\n }\n const timer = setTimeout(() => {\n waiters.delete(onOpen)\n reject(new Error('Subscription timeout'))\n }, timeout)\n waiters.add(onOpen)\n })\n },\n }\n}\n","import type { LoadSubsetOptions } from '@tanstack/db'\n\n// TanStack composes a boundary tie-check as `and(subscription.where, extra)`\n// and loads it through the same subscription; a cursor page arrives with\n// `where === subscription.where`. The subscription's own where is the\n// query's base filter, which is the one realtime should follow: every chunk\n// of one query then shares one entry. `options` is private in TanStack's\n// types, but `subscribeChanges` always sets its `whereExpression` key (even\n// to undefined). A missing key means the shape changed underneath us, so the\n// caller falls back to the request's where rather than guessing.\nfunction subscriptionWhere(\n opts: LoadSubsetOptions\n): { known: true; where: LoadSubsetOptions['where'] } | { known: false } {\n const sub = opts.subscription as\n | { options?: { whereExpression?: LoadSubsetOptions['where'] } }\n | undefined\n if (!sub?.options || !('whereExpression' in sub.options)) return { known: false }\n return { known: true, where: sub.options.whereExpression }\n}\n\n// What a loadSubset asks for beyond the subscription's own where. TanStack\n// composes every chunk as `and(subscription.where, extra)` with the same where\n// object, or hands the extra alone when the subscription has no where.\nfunction chunkExtra(\n where: LoadSubsetOptions['where'],\n subWhere: LoadSubsetOptions['where']\n): LoadSubsetOptions['where'] | null {\n if (where === subWhere) return undefined\n if (subWhere === undefined) return where\n const node = where as { type?: string; name?: string; args?: unknown[] } | undefined\n if (\n node?.type === 'func' &&\n node.name === 'and' &&\n node.args?.length === 2 &&\n node.args[0] === subWhere\n ) {\n return node.args[1] as LoadSubsetOptions['where']\n }\n return null // unknown shape: do not guess\n}\n\n// A join or include loads its lazy side as `inArray(joinKey, keys)`\n// through that side's subscription. The key is the lazy side's own `id`\n// only when it joins on its id; a foreign-key join batches on that FK, so\n// the field cannot tell a batch from a slice. The operator can: an\n// ordered loader's tie-check is `eq`, `and(gte, lt)` for a Date, or\n// `or(isNull, isUndefined)`, never a top-level `in`. A batch keeps its own\n// filter or realtime never covers it; a tie-check shares the base entry.\nexport function realtimeWhereFor(opts: LoadSubsetOptions): LoadSubsetOptions['where'] {\n if (!opts.subscription) return opts.where\n const sub = subscriptionWhere(opts)\n if (!sub.known) return opts.where // unknown shape: per-chunk behavior\n const extra = chunkExtra(opts.where, sub.where)\n if (extra === null) return opts.where // unknown shape: per-chunk behavior\n if (extra === undefined) return sub.where // the base load or a cursor page\n const node = extra as { type?: string; name?: string } | undefined\n return node?.type === 'func' && node.name === 'in' ? opts.where : sub.where\n}\n","import type { LoadSubsetOptions } from '@tanstack/db'\nimport { joinPaths } from './expand-paths'\nimport { subsetFromWhere, type WhereSubset } from './keyed-where'\nimport { REALTIME_MAX_FILTER_LENGTH, subsetFilters } from './pocketbase-limits'\nimport { convertToPocketBaseFilter, convertToPocketBaseSort } from './pocketbase-query-converter'\n\n/** Load options plus the expand paths a view adds. */\nexport type LoadOptions = LoadSubsetOptions & { expand?: readonly string[] }\n\n/**\n * What a query's load options ask PocketBase for. Also the second element of\n * the query key, so equal requests share one cached query.\n */\nexport interface PbRequest {\n filter?: string\n sort?: string\n limit?: number\n /** Rows to skip before the first returned row; set only when no cursor is given. */\n offset?: number\n expand?: string\n subset?: WhereSubset\n /**\n * TanStack's `cursor.whereFrom` as a PocketBase filter. Conjoined to the\n * fetch filter only: realtime stays on the base `where`, so every chunk of\n * one query shares one subscription.\n */\n cursor?: string\n}\n\nexport function toRequest(opts: LoadSubsetOptions | undefined): PbRequest {\n const request: PbRequest = {}\n const subset = subsetFromWhere(opts?.where)\n const filter = subset ? undefined : convertToPocketBaseFilter(opts?.where)\n const sort = convertToPocketBaseSort(opts?.orderBy)\n const expand = joinPaths((opts as LoadOptions | undefined)?.expand ?? [])\n const cursor = convertToPocketBaseFilter(opts?.cursor?.whereFrom)\n if (subset) request.subset = subset\n if (filter) request.filter = filter\n if (sort) request.sort = sort\n if (opts?.limit) request.limit = opts.limit\n if (expand) request.expand = expand\n // A cursor is exact; an offset is a count of rows already acquired. When\n // both arrive, the cursor wins.\n if (cursor) request.cursor = cursor\n else if (opts?.offset) request.offset = opts.offset\n return request\n}\n\n/**\n * The filters a query's realtime entries send: every chunk of a keyed subset,\n * or the single converted filter. `undefined` means the whole collection.\n */\nexport function realtimeFiltersFor(request: PbRequest): string[] | undefined {\n if (request.subset) return subsetFilters(request.subset, REALTIME_MAX_FILTER_LENGTH)\n return request.filter ? [request.filter] : undefined\n}\n","import {\n compileSingleRowExpression,\n LoadSubsetOperationAbortedError,\n type LoadSubsetOptions,\n type SyncConfig,\n toBooleanPredicate,\n whenSyncAccepted,\n} from '@tanstack/db'\nimport type { Fetcher, FetchResult } from './fetch-records'\nimport { ACCEPTED, EAGER, type Holder, type Ledger } from './ledger'\nimport type { LoadedSubsets } from './loaded-subsets'\nimport { logger } from './logger'\nimport type { Applied, Membership } from './membership'\nimport type { RealtimeSubscription } from './realtime-subscription'\nimport { realtimeWhereFor } from './realtime-where'\nimport { idOf, idsOf } from './records'\nimport { type PbRequest, realtimeFiltersFor, toRequest } from './request'\nimport type { LoadStatus } from './sync-status'\nimport type { SyncChannel, SyncedStore } from './synced-store'\nimport type { RealtimeMode } from './types'\nimport type { ViewRegistry } from './views'\n\nexport interface SyncAdapterDeps<T extends object> {\n collectionName: string\n syncMode: 'eager' | 'on-demand'\n realtimeMode: RealtimeMode\n /** How long an unloaded subset stays held for an equal load to adopt; 0 releases at once. */\n subsetGcTime: number\n /** Waits before each retry of a failed load; the length is the number of retries. */\n loadRetryDelays: readonly number[]\n ledger: Ledger<T>\n store: SyncedStore<T>\n membership: Membership<T>\n fetcher: Fetcher<T>\n subsets: LoadedSubsets\n realtime: Pick<\n RealtimeSubscription,\n 'retainQueryFilters' | 'releaseQueryFilters' | 'resetQueryFilters'\n >\n /** The view registry, created after the collection; read lazily. */\n registry: () => Pick<ViewRegistry<never, object>, 'tagFor' | 'withViewExpand'>\n onCleanup: () => void\n /** After anything `loadStatus()` reports may have changed. */\n onLoadStatusChange: () => void\n}\n\nexport interface SyncAdapter<T extends object> {\n sync: SyncConfig<T, string | number>['sync']\n /**\n * Refetch every live subset from the server (the whole collection in\n * eager mode), then release the topic and accepted holders the results\n * did not confirm. Resolves when the rows are accepted; they become\n * visible with the settlement of any persisting mutation.\n */\n reload: () => Promise<void>\n /** The subset holders whose base realtime filter is `filter`. */\n subsetsFor: (filter: string) => LoadSubsetOptions[]\n /**\n * The server deleted `id`, as seen on `topic`: `'*'` for a real delete,\n * a filter string for a row that left that filter. A fetch in flight for\n * a demand the topic covers must not put the row back.\n */\n noteDeleted: (id: string, topic: string) => void\n /** Whether `id` was deleted while a fetch still in flight was running. */\n isDeleted: (id: string) => boolean\n /** Release every parked subset now, for example because the auth changed. */\n expireParked: () => void\n /** End every retry wait now, so a waiting load tries again at once. */\n wakeRetries: () => void\n /**\n * The holders a server-confirmed row belongs to by its values: `EAGER`\n * in eager mode, else every live, landed demand whose `where` the row\n * matches on the client. For a row the server wrote, so no row the\n * server lacks can enter through here.\n */\n holdersFor: (row: T) => Holder[]\n /** Live demands sleeping in retry or ended in an error that is not retried. */\n loadStatus: () => LoadStatus\n}\n\n/** `visible` for a load core awaits; `accepted` for a path a mutation handler can reach. */\ntype Wait = 'visible' | 'accepted'\n\ntype Demand = {\n request: PbRequest\n filters: string[] | undefined\n /** The effective realtime mode is `'query'`, so `filters` hold a realtime ref. */\n counted: boolean\n /** Incremented by every load of this demand; only the newest load reconciles. */\n seq: number\n /** The newest load; a superseded load resolves with it. */\n loading: Promise<string[]> | undefined\n /** Set once unloaded: the demand waits for an equal load to adopt it, or expires. */\n parked: ReturnType<typeof setTimeout> | undefined\n /** Rows for this demand reached the store at least once; only such a demand may park. */\n landed: boolean\n /** Ends a retry wait early: a newer load, an unload or a cleanup supersedes it. */\n wake: (() => void) | undefined\n /** When the load now sleeping in retry first failed. */\n retryingSince: number | undefined\n /** The newest load ended in an error that is not retried. */\n failed: boolean\n}\n\n/** One run of `sync()`, from its call to its cleanup. */\ntype Run = {\n abort: AbortController\n demands: Map<LoadSubsetOptions, Demand>\n eagerSeq: number\n eagerLoad: Promise<string[]> | undefined\n eagerWake: (() => void) | undefined\n eagerRetryingSince: number | undefined\n eagerFailed: boolean\n}\n\nexport function createSyncAdapter<T extends object>(deps: SyncAdapterDeps<T>): SyncAdapter<T> {\n const { collectionName, syncMode, ledger, store, membership, fetcher, subsets, realtime } = deps\n const { subsetGcTime, loadRetryDelays } = deps\n let current: Run | undefined\n // One entry per fetch in flight: ids the server deleted meanwhile, which\n // the result may still list, and the realtime filters the demand holds\n // (undefined: covered by `'*'` only).\n const tombstones = new Map<Set<string>, readonly string[] | undefined>()\n\n function demandFor(opts: LoadSubsetOptions): Demand {\n const request = toRequest(deps.registry().withViewExpand(opts))\n const mode = deps.registry().tagFor(opts)?.realtime ?? deps.realtimeMode\n const base = {\n request,\n seq: 0,\n loading: undefined,\n parked: undefined,\n landed: false,\n wake: undefined,\n retryingSince: undefined,\n failed: false,\n }\n if (mode !== 'query') return { ...base, filters: undefined, counted: false }\n const filters = realtimeFiltersFor(toRequest({ where: realtimeWhereFor(opts) }))\n return { ...base, filters, counted: true }\n }\n\n // Two demands are equal when they would send the same request and hold\n // the same realtime filters.\n function keyOf(demand: Demand): string {\n return JSON.stringify([demand.request, demand.filters], (_key, value: unknown) =>\n value && typeof value === 'object' && !Array.isArray(value)\n ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)))\n : value\n )\n }\n\n async function settle(applied: Applied, wait: Wait): Promise<void> {\n if (applied === true || applied === false) return\n const receipt = wait === 'accepted' ? whenSyncAccepted(applied) : applied\n if (receipt !== true) await receipt\n }\n\n async function fetchRows(\n run: Run,\n request: PbRequest,\n signal: AbortSignal | undefined,\n refetch: boolean,\n filters: readonly string[] | undefined\n ): Promise<FetchResult<T>> {\n const deleted = new Set<string>()\n tombstones.set(deleted, filters)\n try {\n const { rows, fromStore, filings } = await fetcher.fetchRecords(request, {\n signals: signal ? [run.abort.signal, signal] : [run.abort.signal],\n refetch,\n })\n return {\n rows: rows.filter(row => !deleted.has(idOf(row) ?? '')),\n fromStore,\n filings,\n }\n } finally {\n tombstones.delete(deleted)\n }\n }\n\n // Core ignores an aborted load's outcome, but a direct caller\n // (`beginLoadSubsetOperation`) must see that it did not complete. A\n // reload skips the demand instead.\n function isStopped(run: Run, opts: LoadSubsetOptions): boolean {\n return run.abort.signal.aborted || opts.signal?.aborted === true\n }\n\n function stopped(run: Run, opts: LoadSubsetOptions, wait: Wait): boolean {\n if (!isStopped(run, opts)) return false\n if (wait === 'visible') throw new LoadSubsetOperationAbortedError()\n return true\n }\n\n // `unknown` is the answer for an expression the client cannot compile or\n // evaluate. The release path treats it as no match, so it releases\n // nothing; the hand-off treats it as a match, so it keeps the row.\n function matcherFor(where: LoadSubsetOptions['where'], unknown: boolean): (row: T) => boolean {\n if (where === undefined) return () => true\n let evaluate: ReturnType<typeof compileSingleRowExpression>\n try {\n evaluate = compileSingleRowExpression(where)\n } catch {\n return () => unknown\n }\n return row => {\n try {\n return toBooleanPredicate(evaluate(row as Record<string, unknown>))\n } catch {\n return unknown\n }\n }\n }\n\n // Rows ACCEPTED or this demand's filter topics hold, as they stand\n // before the fetch. Never '*': it holds rows for every query on the\n // collection, and a client-side `where` can disagree with PocketBase's. A row an event or a write-back replaces meanwhile\n // is a new object, so it is not mistaken for one the result omits.\n function uncoveredRows(demand: Demand): { holders: Holder[]; rows: Map<string, T> } {\n const holders = [ACCEPTED, ...(demand.filters ?? [])]\n const rows = new Map<string, T>()\n for (const holder of holders) {\n for (const id of ledger.idsOf(holder)) {\n const stored = ledger.row(id)\n if (stored) rows.set(id, stored)\n }\n }\n return { holders, rows }\n }\n\n // A complete fresh result is the server's answer for `where`: a row\n // ACCEPTED or a filter topic holds, that matches `where` and that the result\n // omits, is gone or changed on the server (rule 6 exception). A page\n // (limit, cursor, offset) omits matching rows by design.\n function releaseOmitted(\n opts: LoadSubsetOptions,\n before: { holders: Holder[]; rows: Map<string, T> },\n ids: readonly string[]\n ): Applied {\n if (opts.limit !== undefined || opts.cursor || opts.offset !== undefined) return true\n const returned = new Set(ids)\n const matches = matcherFor(opts.where, false)\n const omitted = [...before.rows]\n .filter(([id, stored]) => !returned.has(id) && ledger.row(id) === stored)\n .filter(([, stored]) => matches(stored))\n .map(([id]) => id)\n return omitted.length > 0 ? membership.drop(before.holders, omitted) : true\n }\n\n async function install(\n run: Run,\n opts: LoadSubsetOptions,\n wait: Wait,\n before: { holders: Holder[]; rows: Map<string, T> },\n result: FetchResult<T>\n ): Promise<string[]> {\n const applied = membership.reconcile(opts, result.rows)\n if (applied === false) {\n result.filings.undo()\n return []\n }\n result.filings.commit()\n const demand = run.demands.get(opts)\n if (demand) demand.landed = true\n const ids = idsOf(result.rows)\n const released = result.fromStore ? true : releaseOmitted(opts, before, ids)\n await settle(applied, wait)\n await settle(released, wait)\n if (!stopped(run, opts, wait)) membership.confirm(opts, [ACCEPTED], ids)\n return ids\n }\n\n // A transient failure must not error the live query: one flaky request\n // would otherwise leave a list empty until a remount. Retries stop when\n // the demand is gone, superseded or aborted.\n function superseded(run: Run, opts: LoadSubsetOptions, demand: Demand, seq: number): boolean {\n return isStopped(run, opts) || run.demands.get(opts) !== demand || demand.seq !== seq\n }\n\n function statusOf(error: unknown): number | undefined {\n const status = (error as { status?: unknown } | null)?.status\n return typeof status === 'number' ? status : undefined\n }\n\n // A response the server gave on purpose is not retried: the request is\n // wrong or forbidden and would fail again. Everything else (no response,\n // a server error, a timeout, a rate limit) may pass next time. A 401 is\n // retried only once the auth changes.\n function isRetryable(error: unknown): boolean {\n const status = statusOf(error)\n if (status === undefined || status < 400 || status >= 500) return true\n return status === 401 || status === 408 || status === 429\n }\n\n /**\n * The wait before retry number `attempt`: the configured delay with up to\n * a quarter of jitter either way, so retries do not fire in lockstep; the\n * last delay repeats. Undefined with no delays, or with a 401, which\n * waits for a wake alone.\n */\n function retryDelay(attempt: number, error: unknown): number | undefined {\n if (statusOf(error) === 401) return undefined\n const base = loadRetryDelays[Math.min(attempt, loadRetryDelays.length - 1)]\n return base === undefined ? undefined : Math.round(base * (0.75 + Math.random() * 0.5))\n }\n\n /** Sleeps `ms` unless woken through `onWake` first; with no `ms`, until woken. */\n function sleep(ms: number | undefined, onWake: (wake: () => void) => void): Promise<void> {\n return new Promise<void>(resolve => {\n const timer = ms === undefined ? undefined : setTimeout(resolve, ms)\n onWake(() => {\n if (timer !== undefined) clearTimeout(timer)\n resolve()\n })\n })\n }\n\n function wakeRetries(run: Run): void {\n run.eagerWake?.()\n for (const demand of run.demands.values()) demand.wake?.()\n }\n\n const { onLoadStatusChange } = deps\n\n function loadStatus(): LoadStatus {\n const status: LoadStatus = { retrying: 0, failed: 0 }\n const run = current\n if (!run) return status\n const count = (retryingSince: number | undefined, failed: boolean) => {\n if (failed) status.failed += 1\n if (retryingSince === undefined) return\n status.retrying += 1\n if (status.failingSince === undefined || retryingSince < status.failingSince) {\n status.failingSince = retryingSince\n }\n }\n for (const demand of run.demands.values()) {\n if (demand.parked === undefined) count(demand.retryingSince, demand.failed)\n }\n count(run.eagerRetryingSince, run.eagerFailed)\n return status\n }\n\n /**\n * Waits out the next retry delay. False when the load is no longer\n * wanted; throws the error when retries are off or it is not retryable.\n * A demand keeps retrying until it loads, so a live query never enters\n * the error state it cannot leave; a reload or reconnect wakes the wait.\n */\n async function retryAllowed(\n run: Run,\n opts: LoadSubsetOptions,\n demand: Demand,\n seq: number,\n attempt: number,\n error: unknown\n ): Promise<boolean> {\n if (superseded(run, opts, demand, seq)) return false\n if (loadRetryDelays.length === 0 || !isRetryable(error)) {\n demand.failed = true\n onLoadStatusChange()\n throw error\n }\n const delay = retryDelay(attempt, error)\n logger.warn('Subset load failed; retrying', { collectionName, attempt, delay, error })\n demand.retryingSince ??= Date.now()\n onLoadStatusChange()\n await sleep(delay, wake => {\n demand.wake = wake\n })\n demand.wake = undefined\n return !superseded(run, opts, demand, seq)\n }\n\n async function fetchWithRetry(\n run: Run,\n opts: LoadSubsetOptions,\n demand: Demand,\n seq: number,\n refetch: boolean\n ): Promise<FetchResult<T> | undefined> {\n try {\n for (let attempt = 0; ; attempt++) {\n try {\n return await fetchRows(\n run,\n demand.request,\n opts.signal,\n refetch,\n demand.filters\n )\n } catch (error) {\n if (!(await retryAllowed(run, opts, demand, seq, attempt, error))) {\n return undefined\n }\n }\n }\n } finally {\n if (demand.seq === seq) {\n demand.retryingSince = undefined\n onLoadStatusChange()\n }\n }\n }\n\n function load(\n run: Run,\n opts: LoadSubsetOptions,\n demand: Demand,\n wait: Wait,\n refetch: boolean\n ): Promise<string[]> {\n demand.wake?.()\n const seq = ++demand.seq\n demand.failed = false\n demand.retryingSince = undefined\n onLoadStatusChange()\n const before = uncoveredRows(demand)\n const loading = (async (): Promise<string[]> => {\n const result = await fetchWithRetry(run, opts, demand, seq, refetch)\n if (result !== undefined && !superseded(run, opts, demand, seq)) {\n return install(run, opts, wait, before, result)\n }\n // Undo before `stopped` can throw, so an aborted result leaves\n // the filings as they were. A superseded load resolves with the\n // newer one, so the caller never resolves before its rows.\n result?.filings.undo()\n if (demand.seq !== seq) return demand.loading ?? []\n stopped(run, opts, wait)\n return []\n })()\n demand.loading = loading\n return loading\n }\n\n function expire(run: Run, opts: LoadSubsetOptions): void {\n const demand = run.demands.get(opts)\n if (!demand) return\n if (demand.parked !== undefined) clearTimeout(demand.parked)\n demand.wake?.()\n run.demands.delete(opts)\n if (demand.counted) realtime.releaseQueryFilters(demand.filters)\n membership.drop([opts])\n onLoadStatusChange()\n }\n\n // An unloaded subset is parked: its rows stay held and its realtime\n // filters stay open for `subsetGcTime`, so a panel that mounts again\n // adopts them with no request. A reload or cleanup expires every parked\n // demand, because a parked demand is a cache.\n function unloadSubset(run: Run, opts: LoadSubsetOptions): void {\n try {\n const demand = run.demands.get(opts)\n if (!demand) return\n if (subsetGcTime <= 0 || demand.parked !== undefined || !demand.landed) {\n expire(run, opts)\n return\n }\n demand.parked = setTimeout(() => {\n if (current === run) expire(run, opts)\n }, subsetGcTime)\n onLoadStatusChange()\n } catch (error) {\n logger.error('unloadSubset failed', { collectionName, error })\n }\n }\n\n function expireParked(run: Run): void {\n for (const [opts, demand] of [...run.demands]) {\n if (demand.parked !== undefined) expire(run, opts)\n }\n }\n\n /** Take the parked demand equal to `demand`, keeping its filter refs for the caller. */\n function unpark(run: Run, demand: Demand): LoadSubsetOptions | undefined {\n const key = keyOf(demand)\n for (const [opts, parked] of run.demands) {\n if (parked.parked === undefined || keyOf(parked) !== key) continue\n clearTimeout(parked.parked)\n run.demands.delete(opts)\n onLoadStatusChange()\n return opts\n }\n return undefined\n }\n\n function serve(opts: LoadSubsetOptions, demand: Demand): Applied {\n if (opts.refetch) return false\n const served = fetcher.serveFromStore(demand.request)\n if (!served) return false\n demand.seq += 1\n demand.loading = undefined\n demand.landed = true\n return membership.reconcile(opts, served, [ACCEPTED])\n }\n\n // Adopting a parked demand moves its rows to the new holder in one\n // transaction and inherits its realtime filter refs.\n function adopt(opts: LoadSubsetOptions, parkedOpts: LoadSubsetOptions): Applied {\n const rows: T[] = []\n for (const id of ledger.idsOf(parkedOpts)) {\n const row = ledger.row(id)\n if (row) rows.push(row)\n }\n return membership.reconcile(opts, rows, [ACCEPTED, parkedOpts])\n }\n\n // Rows already at hand for a new demand: a parked equal demand's, or\n // the store's. False when a fetch is needed.\n function startFromHeld(\n opts: LoadSubsetOptions,\n demand: Demand,\n parkedOpts: LoadSubsetOptions | undefined\n ): Applied {\n if (parkedOpts === undefined) return serve(opts, demand)\n const adopted = adopt(opts, parkedOpts)\n demand.landed = true\n return opts.refetch === true ? false : adopted\n }\n\n // Rows adopted while a reload is running predate it; fetch them again\n // so the adopter is as fresh as the rest.\n function refetchAdopted(run: Run, opts: LoadSubsetOptions, demand: Demand): void {\n void load(run, opts, demand, 'accepted', true).catch(error =>\n logger.error('Refetch after adopting a parked subset failed', { collectionName, error })\n )\n }\n\n function startHeld(\n run: Run,\n opts: LoadSubsetOptions,\n demand: Demand,\n parkedOpts: LoadSubsetOptions | undefined\n ): Applied {\n try {\n const applied = startFromHeld(opts, demand, parkedOpts)\n if (applied !== false && parkedOpts !== undefined && reloading) {\n refetchAdopted(run, opts, demand)\n }\n return applied\n } catch (error) {\n expire(run, opts)\n throw error\n }\n }\n\n function loadSubsetIn(run: Run) {\n return (opts: LoadSubsetOptions): true | Promise<void> => {\n // Core passes a fresh options object per acquisition; a direct\n // caller that reuses one must not leak the earlier demand's refs.\n if (run.demands.has(opts)) expire(run, opts)\n const demand = demandFor(opts)\n const parkedOpts = unpark(run, demand)\n run.demands.set(opts, demand)\n if (parkedOpts === undefined && demand.counted) {\n realtime.retainQueryFilters(demand.filters)\n }\n const applied = startHeld(run, opts, demand, parkedOpts)\n if (applied !== false) return applied\n // A load that fails keeps retrying and keeps its demand, so the\n // live query stays loading rather than erroring; a reload() or\n // reconnect wakes it. An unload releases it as usual.\n return load(run, opts, demand, 'visible', opts.refetch === true).then(() => undefined)\n }\n }\n\n // A superseded eager load waits for the newer one, so readiness never\n // fires before the rows a later load brings.\n /** Like `retryAllowed` for the eager load; throws when the load is stale, so it never installs. */\n async function eagerRetryAllowed(\n run: Run,\n seq: number,\n attempt: number,\n error: unknown\n ): Promise<void> {\n const stale = () => run.abort.signal.aborted || run.eagerSeq !== seq\n if (stale()) throw error\n if (loadRetryDelays.length === 0 || !isRetryable(error)) {\n run.eagerFailed = true\n onLoadStatusChange()\n throw error\n }\n const delay = retryDelay(attempt, error)\n logger.warn('Eager load failed; retrying', { collectionName, attempt, delay, error })\n run.eagerRetryingSince ??= Date.now()\n onLoadStatusChange()\n await sleep(delay, wake => {\n run.eagerWake = wake\n })\n run.eagerWake = undefined\n if (stale()) throw error\n }\n\n async function fetchEagerWithRetry(run: Run, seq: number): Promise<FetchResult<T>> {\n try {\n for (let attempt = 0; ; attempt++) {\n try {\n return await fetchRows(run, {}, undefined, false, undefined)\n } catch (error) {\n await eagerRetryAllowed(run, seq, attempt, error)\n }\n }\n } finally {\n if (run.eagerSeq === seq) {\n run.eagerRetryingSince = undefined\n onLoadStatusChange()\n }\n }\n }\n\n function loadEagerRows(run: Run): Promise<string[]> {\n run.eagerWake?.()\n const seq = ++run.eagerSeq\n run.eagerFailed = false\n run.eagerRetryingSince = undefined\n onLoadStatusChange()\n const loading = (async (): Promise<string[]> => {\n const { rows, filings } = await fetchEagerWithRetry(run, seq)\n if (run.abort.signal.aborted || run.eagerSeq !== seq) {\n filings.undo()\n return run.eagerSeq !== seq ? (run.eagerLoad ?? []) : []\n }\n const applied = membership.reconcile(EAGER, rows, [ACCEPTED])\n if (applied === false) {\n filings.undo()\n return []\n }\n filings.commit()\n await settle(applied, 'accepted')\n return idsOf(rows)\n })()\n run.eagerLoad = loading\n return loading\n }\n\n async function startEager(\n run: Run,\n markReady: () => void,\n markError: (error: unknown) => void\n ): Promise<void> {\n try {\n await loadEagerRows(run)\n } catch (error) {\n if (run.abort.signal.aborted) return\n logger.error('Initial load failed', { collectionName, error })\n markError(error)\n return\n }\n if (!run.abort.signal.aborted) markReady()\n }\n\n // Holders a reload may release: realtime topics (the only string\n // holders) and ACCEPTED. Taken before the fetch, so a row an echo or a\n // write-back lands while the fetch is in flight keeps its holder.\n function releasable(): [Holder, string[]][] {\n return ledger\n .holders()\n .filter(holder => holder === ACCEPTED || typeof holder === 'string')\n .map((holder): [Holder, string[]] => [holder, ledger.idsOf(holder)])\n }\n\n async function reloadRows(run: Run): Promise<Set<string>> {\n const loaded =\n syncMode === 'eager'\n ? [await loadEagerRows(run)]\n : await Promise.all(\n [...run.demands].map(([opts, demand]) =>\n load(run, opts, demand, 'accepted', true)\n )\n )\n return new Set(loaded.flat())\n }\n\n async function releaseUnconfirmed(\n run: Run,\n before: [Holder, string[]][],\n confirmed: Set<string>\n ): Promise<void> {\n for (const [holder, ids] of before) {\n if (run.abort.signal.aborted) return\n const unconfirmed = ids.filter(id => !confirmed.has(id))\n if (unconfirmed.length > 0) {\n await settle(membership.drop([holder], unconfirmed), 'accepted')\n }\n }\n }\n\n async function reloadNow(): Promise<void> {\n const run = current\n if (!run || !store.isAttached()) return\n expireParked(run)\n const before = releasable()\n let confirmed: Set<string>\n try {\n confirmed = await reloadRows(run)\n } catch (error) {\n if (run.abort.signal.aborted) return\n throw error\n }\n await releaseUnconfirmed(run, before, confirmed)\n }\n\n // Callers during a reload share one follow-up reload, which starts when\n // the current one settles: a change that landed after the current fetch\n // went out still gets a fresh fetch, and no request is sent per caller.\n let reloading: Promise<void> | undefined\n let queued: Promise<void> | undefined\n // Every call wakes the retries at once, also when it only queues behind\n // a reload in flight: the waiting loads try again now, under the current\n // auth, instead of sleeping out their delay.\n function reload(): Promise<void> {\n if (current) wakeRetries(current)\n if (!reloading) {\n reloading = reloadNow().finally(() => {\n reloading = undefined\n })\n return reloading\n }\n queued ??= reloading\n .catch(() => undefined)\n .then(() => {\n queued = undefined\n return reload()\n })\n return queued\n }\n\n return {\n sync: params => {\n const channel: SyncChannel<T> = params\n const run: Run = {\n abort: new AbortController(),\n demands: new Map(),\n eagerSeq: 0,\n eagerLoad: undefined,\n eagerWake: undefined,\n eagerRetryingSince: undefined,\n eagerFailed: false,\n }\n current = run\n store.attach(channel)\n // Core has already fenced this run's writes when it calls\n // cleanup; the abort stops its requests, and every async path\n // checks it before it writes.\n const cleanup = () => {\n run.abort.abort()\n run.eagerWake?.()\n for (const demand of run.demands.values()) {\n if (demand.parked !== undefined) clearTimeout(demand.parked)\n demand.wake?.()\n }\n run.demands.clear()\n if (current === run) current = undefined\n store.detach(channel)\n ledger.clear()\n subsets.clear()\n if (syncMode === 'on-demand') realtime.resetQueryFilters()\n deps.onCleanup()\n onLoadStatusChange()\n }\n if (syncMode === 'eager') {\n void startEager(run, params.markReady, params.markError)\n return { cleanup }\n }\n params.markReady()\n return {\n loadSubset: loadSubsetIn(run),\n unloadSubset: opts => unloadSubset(run, opts),\n cleanup,\n }\n },\n reload,\n subsetsFor: filter =>\n [...(current?.demands ?? [])]\n .filter(([, demand]) => demand.filters?.includes(filter))\n .map(([opts]) => opts),\n noteDeleted: (id, topic) => {\n for (const [deleted, filters] of tombstones) {\n if (topic === '*' || filters?.includes(topic)) deleted.add(id)\n }\n },\n isDeleted: id => [...tombstones.keys()].some(deleted => deleted.has(id)),\n expireParked: () => {\n if (current) expireParked(current)\n },\n wakeRetries: () => {\n if (current) wakeRetries(current)\n },\n holdersFor: row => {\n if (!current) return []\n if (syncMode === 'eager') return [EAGER]\n return [...current.demands]\n .filter(\n ([opts, demand]) =>\n demand.parked === undefined &&\n demand.landed &&\n matcherFor(opts.where, true)(row)\n )\n .map(([opts]) => opts)\n },\n loadStatus,\n }\n}\n","import type { SyncConfig } from '@tanstack/db'\n\ntype SyncParams<T extends object> = Parameters<SyncConfig<T, string | number>['sync']>[0]\n\n/** The part of a running sync session pbtsdb writes through. */\nexport type SyncChannel<T extends object> = Pick<SyncParams<T>, 'begin' | 'write' | 'commit'>\n\nexport type SyncWrite<T> = { type: 'insert' | 'update'; value: T } | { type: 'delete'; key: string }\n\n/** pbtsdb's writes as sync transactions on the running session. */\nexport interface SyncedStore<T extends object> {\n /** Bind the session `sync()` was called with; replaces any earlier one. */\n attach: (channel: SyncChannel<T>) => void\n /** Forget `channel` if it is still the bound session. */\n detach: (channel: SyncChannel<T>) => void\n isAttached: () => boolean\n /**\n * Apply `writes` in one sync transaction. Returns core's commit receipt\n * unchanged (`true` when already visible), or false with no session bound.\n */\n transact: (writes: readonly SyncWrite<T>[]) => true | Promise<void> | false\n}\n\nexport function createSyncedStore<T extends object>(collectionName: string): SyncedStore<T> {\n let session: SyncChannel<T> | undefined\n\n return {\n attach(channel) {\n session = channel\n },\n detach(channel) {\n if (session === channel) session = undefined\n },\n isAttached: () => session !== undefined,\n transact(writes) {\n const channel = session\n if (!channel) return false\n if (writes.length === 0) return true\n channel.begin()\n try {\n for (const write of writes) channel.write(write)\n } catch (error) {\n try {\n const cancel = new AbortController()\n cancel.abort()\n channel.commit(cancel.signal)\n } catch {\n // The original write error is what matters; a failing\n // abort-commit must not replace or hide it.\n }\n throw new Error(`${collectionName}: sync write failed`, { cause: error })\n }\n // Returned unchanged: `whenSyncAccepted` reads the acceptance\n // moment core attaches to this promise, and a `.then()` copy\n // would lose it.\n return channel.commit()\n },\n }\n}\n","import { logger } from './logger'\nimport { REALTIME_TOPIC_MAX_LENGTH } from './pocketbase-limits'\nimport type { RealtimeStatus } from './sync-status'\n\nexport interface RealtimeEvent {\n action: string\n record: unknown\n /** Per-client sequence, sent by a server with resume support. */\n seq?: number\n}\n\nexport type RealtimeListener = (event: RealtimeEvent) => void\n\n/**\n * What the client needs from an EventSource: the global one or a React\n * Native polyfill. Errors are observed through `addEventListener('error')`,\n * which every implementation has; `react-native-sse` has no `onerror`.\n */\nexport type EventSourceLike = {\n addEventListener(type: string, listener: EventListenerOrEventListenerObject | null): void\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null): void\n close(): void\n}\n\nexport interface RealtimeClientDeps {\n /** Absolute URL of `/api/realtime`; read each time a connection opens. */\n readonly url: string\n /** `POST /api/realtime` with the SDK's auth; rejects on a non-2xx response. */\n send: (body: { clientId: string; subscriptions: string[] }) => Promise<unknown>\n eventSource?: (url: string) => EventSourceLike\n /** After a reconnect. `resumed` is true when the server replayed the gap. */\n onReconnect?: (resumed: boolean) => void\n /** After any transition `status()` may report; may fire with no change. */\n onStatusChange?: () => void\n backoff?: readonly number[]\n}\n\nexport class RealtimeTopicTooLongError extends Error {\n constructor(length: number) {\n super(\n `Realtime topic is ${length} characters; the server accepts ${REALTIME_TOPIC_MAX_LENGTH}`\n )\n this.name = 'RealtimeTopicTooLongError'\n }\n}\n\n/** Rejects a `subscribe` whose topic was never confirmed because `disconnect()` was called first. */\nexport class RealtimeDisconnectedError extends Error {\n constructor() {\n super('Realtime client was disconnected before this subscription was confirmed')\n this.name = 'RealtimeDisconnectedError'\n }\n}\n\n/**\n * One SSE connection to PocketBase with its topic list. Topic changes made\n * in one tick go out in one POST; `subscribe` resolves once the server has\n * the topic (see docs/internals.md, \"Realtime client\").\n */\nexport interface RealtimeClient {\n subscribe: (topic: string, listener: RealtimeListener) => Promise<() => Promise<void>>\n topics: () => string[]\n isConnected: () => boolean\n status: () => RealtimeStatus\n clientId: () => string | undefined\n disconnect: () => void\n /**\n * Closes the connection, forgets the server-side session and keeps the\n * client closed: no connect happens until `enable()`. Registrations and\n * listeners are kept, so `enable()` resumes every topic.\n */\n disable: () => void\n /** Lifts `disable()` and connects at once if any topic is registered. */\n enable: () => void\n /** False while `disable()` is in effect. */\n isEnabled: () => boolean\n /**\n * Forgets the server-side session (client id, confirmed topics) and\n * reconnects at once if any topic is registered, posting the full list\n * under whatever auth the caller's `send` carries now. Call this after\n * an auth change (login, logout, user switch) the shared connection\n * cannot otherwise see, so the server does not keep serving the old\n * user's subscriptions. Registrations and listeners are kept; pending\n * `subscribe` calls settle once the new connection's POST completes.\n * While `disable()` is in effect the session is forgotten but no\n * connection opens.\n */\n reset: () => void\n /** @internal Simulates the live connection dropping, the way `onerror` would; tests use it. */\n simulateDisconnect: () => void\n}\n\nexport const REALTIME_BACKOFF_MS: readonly number[] = [200, 300, 500, 1000, 1200, 1500, 2000]\n\ntype Waiter = { resolve: () => void; reject: (error: unknown) => void }\n\nexport function createRealtimeClient(deps: RealtimeClientDeps): RealtimeClient {\n const backoff = deps.backoff ?? REALTIME_BACKOFF_MS\n const openSource = deps.eventSource ?? ((url: string) => new EventSource(url))\n\n const listeners = new Map<string, Set<RealtimeListener>>()\n const dispatchers = new Map<string, EventListener>()\n let source: EventSourceLike | undefined\n let connected = false\n let clientId: string | undefined\n let lastSeq: number | undefined\n /** The topic list the server last confirmed; survives a resumed reconnect's `close()`. */\n let confirmed: string[] = []\n let waiters: Waiter[] = []\n let submitQueued = false\n let submitting = false\n let resubmit = false\n let attempts = 0\n let reconnectTimer: ReturnType<typeof setTimeout> | undefined\n /** When the current reconnect episode began; cleared once a connection's POST succeeds. */\n let lostAt: number | undefined\n let nextRetryAt = 0\n let everConnected = false\n /** Bumped by `reset()` and every full teardown; a POST that outlives its session is stale. */\n let session = 0\n let disabled = false\n\n function topics(): string[] {\n return [...listeners.keys()]\n }\n\n function status(): RealtimeStatus {\n if (disabled || (!source && reconnectTimer === undefined)) return { state: 'disabled' }\n if (connected) return { state: 'connected' }\n if (lostAt !== undefined) {\n return { state: 'reconnecting', attempt: attempts, nextRetryAt, since: lostAt }\n }\n return { state: 'connecting' }\n }\n\n function statusChanged(): void {\n deps.onStatusChange?.()\n }\n\n function dispatcherFor(topic: string): EventListener {\n let dispatch = dispatchers.get(topic)\n if (!dispatch) {\n dispatch = (ev: Event) => {\n const message = ev as MessageEvent\n let event: RealtimeEvent\n try {\n event = JSON.parse(String(message.data)) as RealtimeEvent\n } catch {\n return\n }\n if (typeof event.seq === 'number') lastSeq = event.seq\n for (const listener of listeners.get(topic) ?? []) listener(event)\n }\n dispatchers.set(topic, dispatch)\n }\n return dispatch\n }\n\n function sameList(a: readonly string[], b: readonly string[]): boolean {\n return a.length === b.length && a.every(topic => b.includes(topic))\n }\n\n function settleWaiters(pending: Waiter[], error?: unknown): void {\n for (const waiter of pending) error === undefined ? waiter.resolve() : waiter.reject(error)\n }\n\n async function sendTopics(): Promise<void> {\n const list = topics()\n if (list.length === 0) {\n close(true)\n clientId = undefined\n lastSeq = undefined\n statusChanged()\n return\n }\n if (sameList(list, confirmed)) return\n const id = clientId\n if (!id) return\n await deps.send({ clientId: id, subscriptions: list })\n if (clientId === id) confirmed = list\n }\n\n /**\n * A POST outlived its session (a `reset()` or full teardown ran while it\n * was in flight): its waiters never got the topic under the new session,\n * so they go back to the front of the queue for the next `runSubmit`\n * pass instead of settling now, and the POST's own outcome is moot.\n */\n function requeueStale(pending: Waiter[]): void {\n if (disabled) {\n settleWaiters(pending)\n return\n }\n waiters = [...pending, ...waiters]\n resubmit = true\n }\n\n /** Nothing is wanted while disconnected: settles whatever is queued, since no POST can ever carry it. */\n function settleWhileDisconnected(): void {\n if (listeners.size > 0) return\n const pending = waiters\n waiters = []\n close(true)\n clientId = undefined\n lastSeq = undefined\n statusChanged()\n settleWaiters(pending)\n }\n\n async function postTopics(pending: Waiter[], startedSession: number): Promise<void> {\n try {\n await sendTopics()\n if (session !== startedSession) requeueStale(pending)\n else settleWaiters(pending)\n } catch (error) {\n if (session !== startedSession) {\n requeueStale(pending)\n } else {\n logger.error('Failed to set realtime subscriptions', { error })\n settleWaiters(pending, error)\n }\n }\n }\n\n async function runSubmit(): Promise<void> {\n if (submitting) {\n resubmit = true\n return\n }\n if (!connected || !clientId) {\n settleWhileDisconnected()\n return\n }\n submitting = true\n const pending = waiters\n waiters = []\n try {\n await postTopics(pending, session)\n } finally {\n submitting = false\n if (resubmit) {\n resubmit = false\n void runSubmit()\n }\n }\n }\n\n function submit(): Promise<void> {\n const done = new Promise<void>((resolve, reject) => {\n waiters.push({ resolve, reject })\n })\n if (!submitQueued) {\n submitQueued = true\n queueMicrotask(() => {\n submitQueued = false\n void runSubmit()\n })\n }\n return done\n }\n\n function attachAll(target: EventSourceLike): void {\n for (const topic of listeners.keys()) target.addEventListener(topic, dispatcherFor(topic))\n }\n\n function connectUrl(): string {\n if (!clientId) return deps.url\n const params = new URLSearchParams({ resume: clientId })\n if (lastSeq !== undefined) params.set('after', String(lastSeq))\n return `${deps.url}${deps.url.includes('?') ? '&' : '?'}${params}`\n }\n\n /**\n * Closes the connection. `forget` clears `confirmed` because the server's\n * state for this client is gone too (the last topic was removed, or the\n * caller is disconnecting outright) — not on a transient error, where a\n * resumed reconnect may still find the server holding the old list.\n * `everConnected` resets with it: a session after a full teardown is a\n * first connect again, not a reconnect. `session` bumps too, so a POST\n * still in flight from before this teardown cannot settle against it.\n */\n function close(forget: boolean): void {\n if (reconnectTimer !== undefined) clearTimeout(reconnectTimer)\n reconnectTimer = undefined\n source?.close()\n source = undefined\n connected = false\n if (forget) {\n confirmed = []\n everConnected = false\n lostAt = undefined\n session += 1\n }\n }\n\n // Forgets the server-side session and connects again under the current\n // auth, unless disabled. `everConnected` is kept: the connection after a\n // reset or a re-enable is a reconnect, so every ready collection reloads.\n function forgetSession(): void {\n if (reconnectTimer !== undefined) clearTimeout(reconnectTimer)\n reconnectTimer = undefined\n source?.close()\n source = undefined\n connected = false\n confirmed = []\n clientId = undefined\n lastSeq = undefined\n attempts = 0\n lostAt = undefined\n session += 1\n if (listeners.size > 0) {\n try {\n connect()\n } catch (error) {\n logger.error('Failed to reconnect after reset', { error })\n }\n }\n statusChanged()\n }\n\n function scheduleReconnect(): void {\n const delay = backoff[Math.min(attempts, backoff.length - 1)] ?? 0\n attempts += 1\n lostAt ??= Date.now()\n nextRetryAt = Date.now() + delay\n reconnectTimer = setTimeout(() => {\n reconnectTimer = undefined\n if (listeners.size > 0) connect()\n }, delay)\n }\n\n function handleConnectionLost(target: EventSourceLike): void {\n if (source !== target) return\n logger.debug('Realtime connection lost', { clientId })\n close(false)\n scheduleReconnect()\n statusChanged()\n }\n\n function connect(): void {\n if (source || disabled) return\n const previousId = clientId\n const target = openSource(connectUrl())\n source = target\n statusChanged()\n target.addEventListener('error', () => handleConnectionLost(target))\n target.addEventListener('PB_CONNECT', (ev: Event) => {\n if (source !== target) return\n const message = ev as MessageEvent\n let data: { clientId?: string; resumed?: boolean } = {}\n try {\n data = JSON.parse(String(message.data)) as typeof data\n } catch {\n data = {}\n }\n const id = message.lastEventId || data.clientId\n if (!id) return\n const resumed = data.resumed === true && id === previousId\n clientId = id\n connected = true\n if (!resumed) {\n lastSeq = undefined\n confirmed = []\n }\n attachAll(target)\n // Set on connect, not after the POST: a reset() while the first\n // POST is in flight replaces `source`, and the connection it opens\n // must still count as a reconnect so the gap is reloaded.\n const isReconnect = everConnected\n everConnected = true\n statusChanged()\n submit().then(\n () => {\n if (source !== target) return\n attempts = 0\n lostAt = undefined\n statusChanged()\n if (isReconnect) deps.onReconnect?.(resumed)\n },\n () => {\n if (source !== target || !isReconnect) return\n close(false)\n scheduleReconnect()\n statusChanged()\n }\n )\n })\n }\n\n return {\n subscribe(topic, listener) {\n if (topic.length > REALTIME_TOPIC_MAX_LENGTH) {\n return Promise.reject(new RealtimeTopicTooLongError(topic.length))\n }\n if (!source) {\n try {\n connect()\n } catch (error) {\n return Promise.reject(error)\n }\n }\n let set = listeners.get(topic)\n const isNew = set === undefined\n if (!set) {\n set = new Set()\n listeners.set(topic, set)\n }\n set.add(listener)\n if (isNew && source && connected) source.addEventListener(topic, dispatcherFor(topic))\n // While disabled nothing can confirm a topic; the registration\n // goes out with the first POST after enable(). Resolving now lets\n // the caller open and close entries, so idle cleanup still runs.\n const ready = disabled ? Promise.resolve() : submit()\n const unsubscribe = async () => {\n const current = listeners.get(topic)\n if (!current?.delete(listener)) return\n if (current.size > 0) return\n listeners.delete(topic)\n const dispatch = dispatchers.get(topic)\n if (dispatch) {\n source?.removeEventListener(topic, dispatch)\n dispatchers.delete(topic)\n }\n await submit().catch(() => undefined)\n }\n return ready.then(\n () => unsubscribe,\n (error: unknown) => {\n const current = listeners.get(topic)\n if (current?.delete(listener) && current.size === 0) {\n listeners.delete(topic)\n const dispatch = dispatchers.get(topic)\n if (dispatch) {\n source?.removeEventListener(topic, dispatch)\n dispatchers.delete(topic)\n }\n }\n throw error\n }\n )\n },\n topics,\n isConnected: () => connected,\n status,\n clientId: () => clientId,\n disconnect() {\n close(true)\n clientId = undefined\n lastSeq = undefined\n const pending = waiters\n waiters = []\n listeners.clear()\n dispatchers.clear()\n statusChanged()\n settleWaiters(pending, new RealtimeDisconnectedError())\n },\n simulateDisconnect() {\n if (source) handleConnectionLost(source)\n },\n reset: forgetSession,\n // Pending subscribes settle: their topics are registered and go out\n // with the first POST after enable(), the same as a subscribe made\n // while disabled.\n disable() {\n disabled = true\n forgetSession()\n const pending = waiters\n waiters = []\n settleWaiters(pending)\n },\n enable() {\n if (!disabled) return\n disabled = false\n if (listeners.size > 0) connect()\n statusChanged()\n },\n isEnabled: () => !disabled,\n }\n}\n","/** The state of pbtsdb's realtime connection for one PocketBase client. */\nexport type RealtimeStatus =\n /** `disconnectRealtime(pb)` is in effect, or no collection has subscribed yet. */\n | { state: 'disabled' }\n /** The first connection of a session is opening. */\n | { state: 'connecting' }\n /** The stream is open and `PB_CONNECT` was received. */\n | { state: 'connected' }\n /**\n * The stream dropped, or never came up, and a retry is scheduled.\n * `attempt` is the number of the retry, `nextRetryAt` when it fires and\n * `since` when the connection was lost, both epoch milliseconds.\n */\n | { state: 'reconnecting'; attempt: number; nextRetryAt: number; since: number }\n\n/** Loads that are not progressing, across every collection of one client. */\nexport type LoadStatus = {\n /** Live demands sleeping in their `loadRetryDelays` backoff. */\n retrying: number\n /** When the oldest still-retrying load first failed, epoch milliseconds. */\n failingSince?: number\n /** Live demands whose load ended in an error that is not retried, such as a 403 or 404. */\n failed: number\n}\n\nexport type SyncStatus = {\n realtime: RealtimeStatus\n loads: LoadStatus\n}\n\nexport type SyncStatusListener = (status: SyncStatus) => void\n\nexport interface SyncStatusStore {\n get: () => SyncStatus\n subscribe: (listener: SyncStatusListener) => () => void\n /**\n * Marks the sources changed. Listeners hear about it in a microtask,\n * once for any number of calls, so a change made while React renders\n * a live query never updates another component mid-render.\n */\n refresh: () => void\n}\n\nfunction sameRealtime(a: RealtimeStatus, b: RealtimeStatus): boolean {\n if (a.state !== b.state) return false\n if (a.state !== 'reconnecting' || b.state !== 'reconnecting') return true\n return a.attempt === b.attempt && a.nextRetryAt === b.nextRetryAt && a.since === b.since\n}\n\nfunction sameLoads(a: LoadStatus, b: LoadStatus): boolean {\n return a.retrying === b.retrying && a.failed === b.failed && a.failingSince === b.failingSince\n}\n\nexport function mergeLoads(sources: Iterable<LoadStatus>): LoadStatus {\n const merged: LoadStatus = { retrying: 0, failed: 0 }\n for (const loads of sources) {\n merged.retrying += loads.retrying\n merged.failed += loads.failed\n if (loads.failingSince === undefined) continue\n if (merged.failingSince === undefined || loads.failingSince < merged.failingSince) {\n merged.failingSince = loads.failingSince\n }\n }\n return merged\n}\n\n/**\n * Snapshots are stable: `get()` returns the same object, with the same\n * nested objects, until a value changes, so `useSyncExternalStore` does\n * not re-render on every refresh. `get()` always reads the sources, so it\n * is current before the listeners are told.\n */\nexport function createSyncStatusStore(deps: {\n realtime: () => RealtimeStatus\n loads: () => Iterable<LoadStatus>\n}): SyncStatusStore {\n const listeners = new Set<SyncStatusListener>()\n let snapshot: SyncStatus = { realtime: deps.realtime(), loads: mergeLoads(deps.loads()) }\n\n function next(): SyncStatus | undefined {\n const realtime = deps.realtime()\n const loads = mergeLoads(deps.loads())\n const realtimeChanged = !sameRealtime(snapshot.realtime, realtime)\n const loadsChanged = !sameLoads(snapshot.loads, loads)\n if (!realtimeChanged && !loadsChanged) return undefined\n return {\n realtime: realtimeChanged ? realtime : snapshot.realtime,\n loads: loadsChanged ? loads : snapshot.loads,\n }\n }\n\n let notified = snapshot\n let scheduled = false\n\n function get(): SyncStatus {\n const changed = next()\n if (changed) snapshot = changed\n return snapshot\n }\n\n function notify(): void {\n scheduled = false\n const current = get()\n if (current === notified) return\n notified = current\n for (const listener of listeners) listener(current)\n }\n\n return {\n get,\n subscribe(listener) {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n refresh() {\n if (scheduled) return\n scheduled = true\n queueMicrotask(notify)\n },\n }\n}\n","import type PocketBase from 'pocketbase'\nimport type { RecordSubscribeOptions, RecordSubscription } from 'pocketbase'\nimport { realtimeTopic } from './pocketbase-limits'\nimport { createRealtimeClient, type RealtimeClient } from './realtime-client'\nimport {\n createSyncStatusStore,\n type LoadStatus,\n type SyncStatus,\n type SyncStatusListener,\n type SyncStatusStore,\n} from './sync-status'\n\nexport type Unsubscribe = () => Promise<void>\n\n/** What pbtsdb needs from the server for realtime. REST calls stay on the SDK. */\nexport interface Transport {\n /** Resolves once the server has the topic. */\n subscribe: <T extends object>(\n collectionName: string,\n options: RecordSubscribeOptions | undefined,\n handler: (event: RecordSubscription<T>) => void\n ) => Promise<Unsubscribe>\n /** Called after every reconnect of the shared connection. */\n onReconnect: (listener: (resumed: boolean) => void) => () => void\n /** Called when `pb.authStore` changes to another auth record, before the realtime session resets. */\n onAuthChange: (listener: () => void) => () => void\n /** @internal Number of listeners registered through `onReconnect`; tests assert on it. */\n reconnectListenerCount: () => number\n /** Counts `source` into the client's `SyncStatus.loads` until the returned function is called. */\n addLoadSource: (source: () => LoadStatus) => () => void\n /** Call after anything a load source reports may have changed. */\n loadStatusChanged: () => void\n /** @internal Number of load sources registered; tests assert on it. */\n loadSourceCount: () => number\n}\n\ntype Entry = {\n client: RealtimeClient\n reconnectListeners: Set<(resumed: boolean) => void>\n authListeners: Set<() => void>\n status: SyncStatusStore\n loadSources: Set<() => LoadStatus>\n}\n\nconst entries = new WeakMap<PocketBase, Entry>()\n\n// PocketBase rejects a subscriptions POST whose auth record differs from\n// the connection's with a 403, and an unchanged topic list sends no POST\n// at all, so a login, logout or user switch must forget the session. A\n// token refresh keeps the record and needs nothing.\nfunction watchAuth(pb: PocketBase, entry: Entry): void {\n let authId = pb.authStore.record?.id\n pb.authStore.onChange((_token, record) => {\n if (record?.id === authId) return\n authId = record?.id\n for (const listener of entry.authListeners) listener()\n entry.client.reset()\n })\n}\n\nfunction entryFor(pb: PocketBase): Entry {\n let entry = entries.get(pb)\n if (!entry) {\n const reconnectListeners = new Set<(resumed: boolean) => void>()\n const loadSources = new Set<() => LoadStatus>()\n let status: SyncStatusStore | undefined\n const client = createRealtimeClient({\n get url() {\n return pb.buildURL('/api/realtime')\n },\n send: body => pb.send('/api/realtime', { method: 'POST', body, requestKey: null }),\n onReconnect: resumed => {\n for (const listener of reconnectListeners) listener(resumed)\n },\n onStatusChange: () => status?.refresh(),\n })\n status = createSyncStatusStore({\n realtime: client.status,\n loads: () => [...loadSources].map(source => source()),\n })\n entry = { client, reconnectListeners, authListeners: new Set(), status, loadSources }\n watchAuth(pb, entry)\n entries.set(pb, entry)\n }\n return entry\n}\n\n/** @internal The realtime client behind `transportFor(pb)`; tests spy on its `subscribe`. */\nexport function realtimeClientFor(pb: PocketBase): RealtimeClient {\n return entryFor(pb).client\n}\n\n/**\n * Forgets the shared realtime connection's server-side session and\n * reconnects under `pb`'s current auth, re-sending every subscribed topic.\n * pbtsdb does this itself when `pb.authStore` changes to another auth\n * record; call it for a change the store cannot see, such as a server\n * switch. It also lifts {@link disconnectRealtime}. A no-op if `pb` has no\n * realtime connection yet.\n */\nexport function resetRealtime(pb: PocketBase): void {\n const client = entries.get(pb)?.client\n if (!client) return\n client.reset()\n client.enable()\n}\n\n/**\n * Closes pbtsdb's realtime connection for `pb` and keeps it closed: no\n * connection opens until {@link resetRealtime}. Collections keep working\n * over REST and keep their subscriptions registered, so a later\n * `resetRealtime(pb)` resumes every topic and reloads every ready\n * collection. Use it at logout, or at startup where realtime is not wanted.\n */\nexport function disconnectRealtime(pb: PocketBase): void {\n entryFor(pb).client.disable()\n}\n\n/**\n * The sync state of `pb`'s collections: whether pbtsdb's realtime stream\n * is up, and how many live loads are stuck in retry or ended in an error\n * the server meant. The snapshot is stable until a value changes, so it\n * suits `useSyncExternalStore`; see {@link subscribeSyncStatus}.\n */\nexport function getSyncStatus(pb: PocketBase): SyncStatus {\n return entryFor(pb).status.get()\n}\n\n/**\n * Calls `listener` with each new {@link getSyncStatus} snapshot. Returns\n * the unsubscribe function.\n */\nexport function subscribeSyncStatus(pb: PocketBase, listener: SyncStatusListener): () => void {\n return entryFor(pb).status.subscribe(listener)\n}\n\nexport function transportFor(pb: PocketBase): Transport {\n const entry = entryFor(pb)\n return {\n subscribe: <T extends object>(\n collectionName: string,\n options: RecordSubscribeOptions | undefined,\n handler: (event: RecordSubscription<T>) => void\n ) =>\n entry.client.subscribe(realtimeTopic(collectionName, options), event =>\n handler(event as unknown as RecordSubscription<T>)\n ),\n onReconnect(listener) {\n entry.reconnectListeners.add(listener)\n return () => {\n entry.reconnectListeners.delete(listener)\n }\n },\n onAuthChange(listener) {\n entry.authListeners.add(listener)\n return () => {\n entry.authListeners.delete(listener)\n }\n },\n reconnectListenerCount: () => entry.reconnectListeners.size,\n addLoadSource(source) {\n entry.loadSources.add(source)\n return () => {\n entry.loadSources.delete(source)\n entry.status.refresh()\n }\n },\n loadStatusChanged: entry.status.refresh,\n loadSourceCount: () => entry.loadSources.size,\n }\n}\n","import type { LoadSubsetOptions } from '@tanstack/db'\nimport { normalizePaths, type RelationTargets, validateExpandPath } from './expand-paths'\nimport type { LoadOptions } from './request'\nimport type { RealtimeMode } from './types'\n\n/**\n * What a view adds to every subscription made through it: extra expand paths\n * and, when set, a realtime mode that overrides the collection default.\n */\nexport interface ViewTag {\n paths: string[]\n realtime: RealtimeMode | undefined\n}\n\nexport interface ViewRegistry<Args extends unknown[], Sub extends object> {\n /** The tag for a load, from its subscription or the subscribe call on the stack. */\n tagFor: (opts: LoadSubsetOptions) => ViewTag | undefined\n /** Load options with the tagged view's expand paths. */\n withViewExpand: (opts: LoadSubsetOptions) => LoadOptions\n subscribeTagged: (tag: ViewTag | undefined, args: Args) => Sub\n}\n\n/**\n * Tags subscriptions with their view. A subscription's first loadSubset runs\n * inside subscribeChanges, before the subscription object exists to tag, so\n * while a view's subscribe call is on the stack its tag applies to untagged\n * load options.\n */\nexport function createViewRegistry<Args extends unknown[], Sub extends object>(\n subscribe: (...args: Args) => Sub\n): ViewRegistry<Args, Sub> {\n const tags = new WeakMap<object, ViewTag>()\n let subscribing: ViewTag | undefined\n\n function tagFor(opts: LoadSubsetOptions): ViewTag | undefined {\n return (opts.subscription && tags.get(opts.subscription)) ?? subscribing\n }\n\n return {\n tagFor,\n withViewExpand(opts) {\n const paths = tagFor(opts)?.paths\n return paths ? { ...opts, expand: paths } : opts\n },\n subscribeTagged(tag, args) {\n subscribing = tag\n try {\n const subscription = subscribe(...args)\n if (tag) tags.set(subscription, tag)\n return subscription\n } finally {\n subscribing = undefined\n }\n },\n }\n}\n\nexport interface ViewDeps<V extends object> {\n collectionName: string\n collection: V\n alwaysFetch: readonly string[]\n relationTargets: RelationTargets | undefined\n realtimeMode: RealtimeMode\n assertRealtimeMode: (mode: RealtimeMode) => void\n subscribeChangesFor: (tag: ViewTag) => unknown\n}\n\nexport interface Views<V extends object> {\n fetchRelations: (...paths: string[]) => V\n withRealtime: (mode: RealtimeMode) => V\n}\n\n/**\n * Views share the collection's store and prototype; each is identified by its\n * normalized expand paths plus its realtime override. A mode equal to the\n * collection default is stored as `undefined`, so it never creates a view.\n */\nexport function createViews<V extends object>(deps: ViewDeps<V>): Views<V> {\n const { collectionName, collection, alwaysFetch, relationTargets, realtimeMode } = deps\n const views = new Map<string, V>()\n\n function createView(tag: ViewTag): V {\n const query: string[] = []\n if (tag.paths.length > 0) query.push(`expand=${tag.paths.join(',')}`)\n if (tag.realtime) query.push(`realtime=${tag.realtime}`)\n const view: V = Object.create(collection)\n Object.defineProperties(view, {\n id: { value: `${collectionName}?${query.join('&')}` },\n subscribeChanges: { value: deps.subscribeChangesFor(tag) },\n fetchRelations: {\n value: (...more: string[]) => viewFor([...tag.paths, ...more], tag.realtime),\n },\n withRealtime: {\n value: (mode: RealtimeMode) => {\n deps.assertRealtimeMode(mode)\n const override = mode === realtimeMode ? undefined : mode\n if (tag.realtime !== undefined && tag.realtime !== override) {\n throw new Error(\n `A view of \"${collectionName}\" already uses realtime '${tag.realtime}'`\n )\n }\n return viewFor(tag.paths, mode)\n },\n },\n })\n return view\n }\n\n function viewFor(paths: readonly string[], realtime: RealtimeMode | undefined): V {\n for (const path of paths) validateExpandPath(collectionName, relationTargets, path)\n const all = normalizePaths([...alwaysFetch, ...paths])\n const override = realtime === realtimeMode ? undefined : realtime\n if (override === undefined && all.every(path => alwaysFetch.includes(path))) {\n return collection\n }\n const key = `${all.join(',')}|${override ?? ''}`\n let view = views.get(key)\n if (!view) {\n view = createView({ paths: all, realtime: override })\n views.set(key, view)\n }\n return view\n }\n\n return {\n fetchRelations: (...paths) => viewFor(paths, undefined),\n withRealtime: mode => {\n deps.assertRealtimeMode(mode)\n return viewFor([], mode)\n },\n }\n}\n","import {\n BTreeIndex,\n type Collection,\n createCollection as createTanStackCollection,\n type DeleteMutationFn,\n type InsertMutationFn,\n type UpdateMutationFn,\n type UtilsRecord,\n whenSyncAccepted,\n} from '@tanstack/db'\nimport type PocketBase from 'pocketbase'\nimport type { RecordSubscribeOptions, RecordSubscription } from 'pocketbase'\nimport {\n createExpandFiler,\n stripFetchedRelations,\n targetsAlong,\n withoutExpand,\n} from './expand-filing'\nimport {\n joinPaths,\n normalizePaths,\n type RelationTargets,\n splitPaths,\n validateExpandPath,\n} from './expand-paths'\nimport { createFetcher } from './fetch-records'\nimport { createHeldTargets } from './held-targets'\nimport { ACCEPTED, createLedger } from './ledger'\nimport { createLoadedSubsets } from './loaded-subsets'\nimport { logger } from './logger'\nimport { createMembership } from './membership'\nimport { createRealtimeSubscription } from './realtime-subscription'\nimport { idOf, updatedAtOf } from './records'\nimport type { PbRequest } from './request'\nimport { createSyncAdapter, type SyncAdapterDeps } from './sync-adapter'\nimport { createSyncedStore } from './synced-store'\nimport { transportFor } from './transport'\nimport type {\n CreateCollectionOptions,\n ExtractRecordType,\n HeldTarget,\n RealtimeMode,\n SchemaDeclaration,\n} from './types'\nimport { createViewRegistry, createViews, type ViewTag } from './views'\n\nconst REALTIME_MODES: readonly RealtimeMode[] = ['collection', 'query']\n\n/**\n * Options applied to every collection built by a {@link createCollection} factory.\n */\nexport interface CreateCollectionFactoryOptions {\n /**\n * Extra options passed to every real-time subscription this factory creates,\n * such as `headers`, `filter`, `expand` or `fields`.\n *\n * Invoked on every subscribe attempt rather than read once: each filtered\n * entry of a `realtime: 'query'` collection and each restart (reconnect,\n * wider expand) calls it again, so a value captured at build time would go\n * stale.\n *\n * Returning `undefined` subscribes with no extra options.\n */\n subscribeOptions?: () => RecordSubscribeOptions | undefined\n}\n\n/**\n * pbtsdb's utilities on `collection.utils`. The same functions are also\n * assigned on the collection itself.\n */\nexport interface PbCollectionUtils<T extends object> extends UtilsRecord {\n /**\n * Land rows the server returned as confirmed state, for example a custom\n * endpoint's response. A row older than the stored one is ignored.\n * Resolves when the rows are accepted; they become visible with the\n * settlement of any persisting mutation, so a mutation handler can await it.\n * Throws on an eager collection that is idle: it does not start a full load.\n */\n accept: (rows: readonly T[]) => Promise<void>\n /**\n * Refetch every live query's subset (the whole collection in eager mode)\n * and release the realtime-topic and accepted holders of rows the results\n * do not confirm; rows a subset or a parent holds stay. Resolves when the\n * rows are accepted; they become visible with the settlement of any\n * persisting mutation.\n */\n reload: () => Promise<void>\n /**\n * Remove rows the server deleted, for example after a custom endpoint\n * deleted them. The rows leave every holder, and a fetch in flight does\n * not put them back. Resolves when the removal is accepted, so a custom\n * delete handler can await it. A no-op while the collection is not\n * syncing.\n */\n evict: (ids: readonly string[]) => Promise<void>\n}\n\n/**\n * Helpers added to collection instances.\n * @internal\n */\nexport interface CollectionSubscriptionHelpers<T extends object> {\n /** The PocketBase collection name */\n collectionName: string\n /** Wait for subscription to be established (useful in tests) */\n waitForSubscription: (timeout?: number) => Promise<void>\n /** Check if collection has an active subscription */\n isSubscribed: () => boolean\n /**\n * Relation targets declared through `relations`. Relation plumbing, not public API.\n * @internal\n */\n relationTargets: RelationTargets | undefined\n /**\n * Number of relation targets currently held live. Relation plumbing, not public API.\n * @internal\n */\n heldRelationTargetCount: () => number\n /**\n * Record that every row with `field === value` is now in this collection's store. Relation plumbing, not public API.\n * @internal\n */\n markSubsetLoaded: (field: string, value: string) => void\n /**\n * Number of field/value pairs currently marked loaded. Relation plumbing, not public API.\n * @internal\n */\n loadedSubsetCount: () => number\n /**\n * Hold this collection live as a relation target; see RelationTarget.holdLive. Relation plumbing, not public API.\n * @internal\n */\n holdLive: (holder: object) => HeldTarget\n /**\n * Receive rows a parent expanded into this collection; see RelationTarget.writeFiled. Relation plumbing, not public API.\n * @internal\n */\n writeFiled: (records: object[], holder: object) => Promise<boolean>\n /**\n * Release rows a parent stopped filing here; see RelationTarget.releaseFiled. Relation plumbing, not public API.\n * @internal\n */\n releaseFiled: (ids: readonly string[], holder: object) => void\n /**\n * A parent's fetch may file a subset here; see RelationTarget.expectFiling. Relation plumbing, not public API.\n * @internal\n */\n expectFiling: (field: string, settles: Promise<void>) => () => void\n /** See {@link PbCollectionUtils.accept}. */\n accept: PbCollectionUtils<T>['accept']\n /** See {@link PbCollectionUtils.reload}. */\n reload: PbCollectionUtils<T>['reload']\n /** See {@link PbCollectionUtils.evict}. */\n evict: PbCollectionUtils<T>['evict']\n}\n\n/**\n * Runtime shape of a built collection, before the public factory narrows it.\n * @internal\n */\nexport type BuiltCollection<T extends object> = Collection<\n T,\n string | number,\n PbCollectionUtils<T>,\n never,\n T\n> &\n CollectionSubscriptionHelpers<T> & {\n fetchRelations: (...paths: string[]) => BuiltCollection<T>\n withRealtime: (mode: RealtimeMode) => BuiltCollection<T>\n }\n\n/** @internal */\nexport interface BuildCollectionInput<\n Schema extends SchemaDeclaration,\n C extends keyof Schema & string,\n> {\n pb: PocketBase\n factoryOptions: CreateCollectionFactoryOptions | undefined\n collectionName: C\n options: CreateCollectionOptions<Schema, C> | undefined\n}\n\n/** @internal */\nexport function buildCollection<Schema extends SchemaDeclaration, C extends keyof Schema & string>(\n input: BuildCollectionInput<Schema, C>\n): BuiltCollection<ExtractRecordType<Schema, C>> {\n const { pb, factoryOptions, collectionName, options } = input\n type RecordType = ExtractRecordType<Schema, C>\n\n const relationTargets = options?.relations as RelationTargets | undefined\n for (const [key, target] of Object.entries(relationTargets ?? {})) {\n if (\n typeof target?.writeFiled !== 'function' ||\n typeof target.holdLive !== 'function' ||\n typeof target.expectFiling !== 'function'\n ) {\n throw new Error(\n `Collection '${collectionName}': relation '${key}' is not a pbtsdb collection`\n )\n }\n }\n const alwaysFetch = normalizePaths(options?.alwaysFetchRelations ?? [])\n for (const path of alwaysFetch) validateExpandPath(collectionName, relationTargets, path)\n const syncMode = options?.syncMode ?? 'eager'\n const realtimeMode: RealtimeMode = options?.realtime ?? 'collection'\n const refetchOnMutation = options?.refetchOnMutation ?? false\n const subsetGcTime = options?.subsetGcTime ?? 5000\n const loadRetryDelays = options?.loadRetryDelays ?? [1000, 2000, 4000, 8000, 15000, 30000]\n\n function assertRealtimeMode(mode: RealtimeMode): void {\n if (!REALTIME_MODES.includes(mode)) {\n throw new Error(\n `Collection '${collectionName}': unknown realtime mode '${String(mode)}'`\n )\n }\n if (mode === 'query' && syncMode !== 'on-demand') {\n throw new Error(\n `Collection '${collectionName}': realtime 'query' requires syncMode 'on-demand'`\n )\n }\n }\n assertRealtimeMode(realtimeMode)\n\n // Paths requested by views that have subscribed at least once. Eager fetches\n // read it because they cannot receive per-subset options; the realtime\n // subscription reads it so echoes carry every relation in use.\n const requestedExpand = new Set<string>()\n\n const pendingSubscribeExpand = () => joinPaths([...alwaysFetch, ...requestedExpand])\n\n function activeExpand(request: PbRequest): string | undefined {\n return joinPaths([\n ...alwaysFetch,\n ...splitPaths(request.expand),\n ...(syncMode === 'eager' ? requestedExpand : []),\n ])\n }\n\n // The factory's own subscribeOptions() merged with the expand union.\n function realtimeSubscribeOptions(): RecordSubscribeOptions | undefined {\n const base = factoryOptions?.subscribeOptions?.()\n const expand = joinPaths([\n ...splitPaths(pendingSubscribeExpand()),\n ...splitPaths(base?.expand),\n ])\n return expand ? { ...base, expand } : base\n }\n\n // Every held target, every subset mark and, in on-demand mode, every\n // accepted row exists to serve rows realtime keeps fresh; with nothing\n // live and nothing wanted, release them all.\n function releaseAll(): void {\n held.releaseAll()\n subsets.clear()\n if (syncMode === 'on-demand') membership.drop([ACCEPTED])\n }\n\n // In eager mode the whole collection stays loaded after the last\n // subscriber leaves, until GC, so a topic's rows keep their holder until\n // reload() or cleanup. In on-demand mode they leave with the topic.\n function releaseTopic(topic: string): void {\n if (syncMode === 'eager') return\n if (membership.drop([topic]) === false) {\n logger.debug('Ignoring topic release while sync is not running', {\n collectionName,\n topic,\n })\n }\n }\n\n // This collection's identity as a parent: the holder its filed rows and\n // holds carry in every relation target.\n const parentHolder = { parent: collectionName }\n\n const ledger = createLedger<RecordType>()\n const store = createSyncedStore<RecordType>(collectionName)\n const subsets = createLoadedSubsets()\n const membership = createMembership<RecordType>({\n collectionName,\n ledger,\n store,\n onRemoved: rows => {\n for (const row of rows) {\n subsets.forgetRow(row)\n const id = idOf(row)\n if (id !== undefined) held.forgetParentRow(id)\n }\n },\n })\n const held = createHeldTargets(collectionName, parentHolder)\n // A result row older than the stored row, or deleted while its fetch\n // was in flight, must not re-file its relations over newer state.\n const filer = createExpandFiler({\n collectionName,\n setFiled: held.setFiled,\n holder: parentHolder,\n isStale: record => {\n const id = idOf(record)\n if (id === undefined) return true\n if (adapter.isDeleted(id)) return true\n const incoming = updatedAtOf(record)\n const stored = updatedAtOf(ledger.row(id))\n return incoming !== undefined && stored !== undefined && incoming < stored\n },\n })\n const fetcher = createFetcher<RecordType>({\n pb,\n collectionName,\n relationTargets,\n activeExpand,\n syncedRow: ledger.row,\n syncedRows: ledger.rows,\n subsets,\n filer,\n })\n const transport = transportFor(pb)\n const realtime = createRealtimeSubscription<RecordType>({\n transport,\n collectionName,\n handleEvent: (event, topic, expand) => handleRealtimeEvent(event, topic, expand),\n pendingExpand: pendingSubscribeExpand,\n subscribeOptions: realtimeSubscribeOptions,\n onEntryOpened: () =>\n held.sync(targetsAlong(splitPaths(pendingSubscribeExpand()), relationTargets)),\n onEntryClosed: releaseTopic,\n onIdle: releaseAll,\n })\n const adapter = createSyncAdapter<RecordType>({\n collectionName,\n syncMode,\n realtimeMode,\n subsetGcTime,\n loadRetryDelays,\n ledger,\n store,\n membership,\n fetcher,\n subsets,\n realtime,\n registry: (): ReturnType<SyncAdapterDeps<RecordType>['registry']> => registry,\n onCleanup: () => {\n held.clearFiled()\n for (const timer of acceptedTimers) clearTimeout(timer)\n acceptedTimers.clear()\n },\n onLoadStatusChange: transport.loadStatusChanged,\n })\n\n // `false` disables the mutation; `undefined` selects the built-in handler.\n function resolveHandler<H>(option: H | false | undefined, fallback: H): H | undefined {\n return option === false ? undefined : (option ?? fallback)\n }\n\n // A handler lands the server's rows before it returns: TanStack DB drops\n // the optimistic state when the handler settles, and rows written while\n // it runs publish together with that drop. The receipt is not awaited:\n // core holds this transaction until the handler's own transaction\n // settles, which is after the handler returns.\n function landServerRows(rows: RecordType[]): void {\n const result = membership.accept(rows)\n if (result === false) {\n logger.debug('Dropping write-back while sync is not running', { collectionName })\n return\n }\n expireAccepted(rows)\n }\n\n // ACCEPTED is a bridge until the echo gives the row a topic or a load a\n // subset. When the window ends the row is handed to every live query\n // whose filter matches it, so a missing echo (realtime down, event\n // lost) never removes a row the user still sees; a row no live query\n // matches leaves. A row another holder took meanwhile keeps it.\n const acceptedTimers = new Set<ReturnType<typeof setTimeout>>()\n function settleAccepted(ids: readonly string[]): void {\n for (const id of ids) {\n const row = ledger.row(id)\n if (!row) continue\n const holders = adapter.holdersFor(row)\n if (holders.length > 0) membership.hold(holders, [id])\n }\n membership.drop([ACCEPTED], ids)\n }\n function expireAccepted(rows: readonly RecordType[]): void {\n if (subsetGcTime <= 0) return\n const ids = rows.map(idOf).filter((id): id is string => id !== undefined)\n const timer = setTimeout(() => {\n acceptedTimers.delete(timer)\n settleAccepted(ids)\n }, subsetGcTime)\n acceptedTimers.add(timer)\n }\n\n // reload() resolves on acceptance, so awaiting it here cannot wait for\n // this handler's own transaction.\n async function settleHandler(): Promise<void> {\n if (refetchOnMutation) await adapter.reload()\n }\n\n const defaultInsert: InsertMutationFn<RecordType> = async ({ transaction }) => {\n const created = await Promise.all(\n transaction.mutations.map(async mutation => {\n const {\n created: _created,\n updated: _updated,\n collectionId: _collectionId,\n collectionName: _collectionName,\n ...data\n } = mutation.modified as unknown as Record<string, unknown>\n return pb.collection(collectionName).create<RecordType>(data)\n })\n )\n landServerRows(created)\n await settleHandler()\n }\n\n const defaultUpdate: UpdateMutationFn<RecordType> = async ({ transaction }) => {\n const updated = await Promise.all(\n transaction.mutations.map(mutation =>\n pb\n .collection(collectionName)\n .update<RecordType>(mutation.original.id, mutation.changes)\n )\n )\n landServerRows(updated)\n await settleHandler()\n }\n\n // The server deleted `ids`: no fetch in flight may put them back, and\n // they leave every holder. Acceptance is at commit, so awaiting it from\n // inside a handler cannot wait for that handler's own transaction.\n async function evict(ids: readonly string[]): Promise<void> {\n for (const id of ids) adapter.noteDeleted(id, '*')\n await whenAccepted(membership.dropAll(ids))\n }\n\n const defaultDelete: DeleteMutationFn<RecordType> = async ({ transaction }) => {\n const ids = await Promise.all(\n transaction.mutations.map(async mutation => {\n await pb.collection(collectionName).delete(mutation.original.id)\n return mutation.original.id\n })\n )\n await evict(ids)\n await settleHandler()\n }\n\n // TanStack DB 0.6 turned auto-indexing off by default; without an index an\n // orderBy+limit query loads the whole subset instead of paging lazily and\n // warns on every compile. Restore the earlier default; callers can override\n // both settings through collectionOptions, and `gcTime` reaches core\n // through the same spread. rowUpdateMode 'full' makes core store the\n // object the ledger writes, so the ledger row and the stored row match.\n const collection = createTanStackCollection<\n RecordType,\n string | number,\n PbCollectionUtils<RecordType>\n >({\n autoIndex: 'eager',\n defaultIndexType: BTreeIndex,\n ...options?.collectionOptions,\n id: collectionName,\n syncMode,\n getKey: (item: RecordType) => {\n const id = idOf(item)\n if (id === undefined) {\n throw new Error(\n `Record in collection '${collectionName}' is missing required 'id' field. Received: ${JSON.stringify(item)}`\n )\n }\n return id\n },\n sync: { sync: adapter.sync, rowUpdateMode: 'full' },\n onInsert: resolveHandler(options?.onInsert, defaultInsert),\n onUpdate: resolveHandler(options?.onUpdate, defaultUpdate),\n onDelete: resolveHandler(options?.onDelete, defaultDelete),\n utils: { accept, reload: adapter.reload, evict },\n })\n\n // A reconnect the server did not resume lost every event of the gap.\n // Reload what is live; a resumed connection replayed it already.\n // Registered only while the collection is syncing: it is removed on\n // `cleaned-up` so a long-lived `pb` does not accumulate one listener per\n // `buildCollection` call. A restart after cleanup registers again.\n // Cleanup also clears marks a parent set before sync ever started; the\n // adapter's own cleanup runs only for a started sync.\n // An auth change clears what the previous user left behind at once:\n // parked subsets, accepted rows and their timers. It reloads every\n // live demand under the new auth as well, whether or not realtime is\n // connected, so the order of logout calls does not matter. A reconnect\n // that follows reloads once more, coalesced with this one.\n function reloadFor(reason: string): void {\n void adapter\n .reload()\n .catch(error =>\n logger.error(`Failed to reload after ${reason}`, { collectionName, error })\n )\n }\n // Registered for the life of a sync, like the listeners: a cleaned-up\n // collection reports no loads, and collections recreated for one `pb`\n // must not accumulate in its status.\n let removeTransportListeners: (() => void) | undefined\n collection.on('status:change', event => {\n if (event.status === 'cleaned-up') subsets.clear()\n if (!removeTransportListeners && (event.status === 'loading' || event.status === 'ready')) {\n const removeLoadSource = transport.addLoadSource(adapter.loadStatus)\n const removeReconnect = transport.onReconnect(resumed => {\n if (resumed || !realtime.isOpen()) return\n // A collection still loading has no live demands to reload,\n // but its first load may be waiting out a retry.\n if (!collection.isReady()) {\n adapter.wakeRetries()\n return\n }\n reloadFor('realtime reconnect')\n })\n const removeAuth = transport.onAuthChange(() => {\n adapter.expireParked()\n for (const timer of acceptedTimers) clearTimeout(timer)\n acceptedTimers.clear()\n membership.drop([ACCEPTED])\n if (store.isAttached()) reloadFor('auth change')\n })\n removeTransportListeners = () => {\n removeLoadSource()\n removeReconnect()\n removeAuth()\n }\n } else if (removeTransportListeners && event.status === 'cleaned-up') {\n removeTransportListeners()\n removeTransportListeners = undefined\n }\n })\n\n // Captured before the base collection's own subscribeChanges is replaced\n // below, so views and the base both reach TanStack's original.\n const originalSubscribeChanges = collection.subscribeChanges.bind(collection)\n type ChangesSubscription = ReturnType<typeof originalSubscribeChanges>\n const registry = createViewRegistry(originalSubscribeChanges)\n\n // Subscribe while counting toward the '*' entry; the count drops once,\n // on the first unsubscribe.\n function subscribeCounted(subscribe: () => ChangesSubscription): ChangesSubscription {\n realtime.addCollectionSubscriber()\n let subscription: ChangesSubscription\n try {\n subscription = subscribe()\n } catch (error) {\n realtime.dropCollectionSubscriber()\n throw error\n }\n const unsubscribe = subscription.unsubscribe.bind(subscription)\n let released = false\n subscription.unsubscribe = () => {\n if (!released) {\n released = true\n realtime.dropCollectionSubscriber()\n realtime.reconcile()\n }\n unsubscribe()\n }\n return subscription\n }\n\n function subscribeChangesFor(tag: ViewTag | undefined) {\n return (...args: Parameters<typeof originalSubscribeChanges>) => {\n if (tag) noteViewSubscribed(tag.paths)\n const subscription =\n (tag?.realtime ?? realtimeMode) === 'collection'\n ? subscribeCounted(() => registry.subscribeTagged(tag, args))\n : registry.subscribeTagged(tag, args)\n realtime.reconcile()\n return subscription\n }\n }\n\n Object.defineProperty(collection, 'subscribeChanges', {\n value: subscribeChangesFor(undefined),\n })\n\n const views = createViews({\n collectionName,\n collection,\n alwaysFetch,\n relationTargets,\n realtimeMode,\n assertRealtimeMode,\n subscribeChangesFor,\n })\n\n // PocketBase can redeliver or reorder echoes; the ledger drops a strictly\n // older create/update. A delete on a filter topic releases that topic,\n // its subsets, the parents whose hold covers it and the accepted\n // holder; a delete on '*' removes the row. A delete is also recorded\n // against every fetch in flight, whose result may predate it.\n function handleRealtimeEvent(\n event: RecordSubscription<RecordType>,\n topic: string,\n expand: string | undefined\n ): void {\n const id = idOf(event.record)\n if (!id) return\n if (event.action === 'delete') {\n adapter.noteDeleted(id, topic)\n const applied =\n topic === '*'\n ? membership.dropAll([id])\n : membership.drop(\n [\n topic,\n ...adapter.subsetsFor(topic),\n ...(holdersByFilter.get(topic) ?? []),\n ACCEPTED,\n ],\n [id]\n )\n if (applied === false) {\n logger.debug('Ignoring delete echo while sync is not running', {\n collectionName,\n id,\n })\n }\n return\n }\n const [stored] = stripFetchedRelations([event.record], pendingSubscribeExpand())\n const land = () => {\n const applied = membership.land(topic, [stored])\n if (applied !== false) membership.drop([ACCEPTED], [id])\n return applied !== false\n }\n const paths = splitPaths(expand)\n // The same order as a fetch: relations first, then the parent, then\n // the release of relations the parent stopped referencing, so a\n // reader never sees the parent without its relation. With nothing\n // to file the parent lands at once; a target that is not syncing\n // yet would hold the parent back for a load, so the parent lands\n // first in that case too.\n if (filer.canFileFirst([event.record], relationTargets)) {\n filer\n .fileExpanded([event.record], relationTargets, paths)\n .then(change => {\n if (land()) {\n change.commit()\n return\n }\n change.undo()\n logger.debug('Ignoring realtime echo while sync is not running', {\n collectionName,\n id,\n })\n })\n .catch(error =>\n logger.error('Failed to file expanded records from realtime echo', {\n collectionName,\n error,\n })\n )\n return\n }\n if (!land()) {\n logger.debug('Ignoring realtime echo while sync is not running', { collectionName, id })\n return\n }\n filer.upsertExpanded([event.record], relationTargets, paths).catch(error =>\n logger.error('Failed to upsert expanded records from realtime echo', {\n collectionName,\n error,\n })\n )\n }\n\n // preload() on an on-demand collection logs a warning; startSyncImmediate()\n // does not. On-demand marks ready synchronously, so the wait ends at once.\n async function ensureSyncing(): Promise<boolean> {\n if (collection.isReady()) return true\n if (collection.status === 'error') return false\n const idle = collection.status === 'idle' || collection.status === 'cleaned-up'\n if (syncMode === 'eager') {\n // Filing must not start a full eager load; a load already\n // running (a hold started it) is worth waiting for.\n if (idle) return false\n await collection.preload()\n return true\n }\n if (idle) collection.startSyncImmediate()\n if (!collection.isReady()) {\n await new Promise<void>(resolve => {\n collection.onFirstReady(resolve)\n })\n }\n return true\n }\n\n // Receives rows a parent expanded through a relation to this collection.\n // Returns whether the write happened: a caller marks a subset complete\n // only after a real filing.\n async function writeFiled(records: object[], holder: object): Promise<boolean> {\n if (!(await ensureSyncing())) {\n logger.warn(\n `not syncing filed rows into ${collectionName} because store is not yet ready`\n )\n return false\n }\n return membership.land(holder, withoutExpand(records) as RecordType[]) !== false\n }\n\n // Awaits acceptance, not visibility: a custom mutation handler that calls\n // accept() or evict() would otherwise wait for its own transaction.\n async function whenAccepted(applied: ReturnType<typeof membership.land>): Promise<void> {\n if (applied === true || applied === false) return\n const accepted = whenSyncAccepted(applied)\n if (accepted !== true) await accepted\n }\n\n async function accept(rows: readonly RecordType[]): Promise<void> {\n if (!(await ensureSyncing())) {\n throw new Error(`Collection '${collectionName}' is not syncing; accept() has no store`)\n }\n const applied = membership.accept(rows)\n if (applied !== false) expireAccepted(rows)\n await whenAccepted(applied)\n }\n\n // Parents whose hold covers each realtime filter, so a delete on that\n // topic releases their filings of the row.\n const holdersByFilter = new Map<string, Set<object>>()\n\n function swapHolderFilters(holder: object, previous: string[], next: string[]): void {\n for (const filter of previous) {\n const holders = holdersByFilter.get(filter)\n holders?.delete(holder)\n if (holders?.size === 0) holdersByFilter.delete(filter)\n }\n for (const filter of next) {\n let holders = holdersByFilter.get(filter)\n if (!holders) {\n holders = new Set()\n holdersByFilter.set(filter, holders)\n }\n holders.add(holder)\n }\n realtime.swapHoldFilters(previous, next)\n }\n\n // A parent's hold on this collection as a relation target. Keeps sync\n // alive and GC blocked like any subscriber. In collection mode the hold\n // counts toward '*'; in query mode it is uncounted and the parent\n // supplies the filters covering the rows it filed here. Releasing it\n // releases every row the parent filed under `holder`.\n function holdLive(holder: object): HeldTarget {\n const subscribe = () => originalSubscribeChanges(() => {}, { includeInitialState: false })\n const subscription =\n realtimeMode === 'collection' ? subscribeCounted(subscribe) : subscribe()\n let current: string[] = []\n let released = false\n realtime.reconcile()\n return {\n setFilters: filters => {\n if (released) return\n const next = [...new Set(filters)]\n swapHolderFilters(holder, current, next)\n current = next\n },\n release: () => {\n if (released) return\n released = true\n swapHolderFilters(holder, current, [])\n current = []\n membership.drop([holder])\n subscription.unsubscribe()\n },\n }\n }\n\n // A parent row stopped filing these rows here (its expand no longer\n // returns them, or it left the parent's store).\n function releaseFiled(ids: readonly string[], holder: object): void {\n if (membership.drop([holder], ids) === false) {\n logger.debug('Ignoring filed-row release while sync is not running', {\n collectionName,\n })\n }\n }\n\n // Record which expand paths a view has subscribed with at least once.\n // Eager collections cannot request per-subset options, so a wider union\n // needs a reload; a live realtime subscription needs a restart.\n function noteViewSubscribed(paths: string[]): void {\n let grew = false\n for (const path of paths) {\n if (requestedExpand.has(path)) continue\n requestedExpand.add(path)\n grew = true\n }\n if (!grew) return\n if (\n syncMode === 'eager' &&\n collection.status !== 'idle' &&\n collection.status !== 'cleaned-up'\n ) {\n void adapter.reload().catch(error =>\n logger.error('Failed to reload after widening expand', {\n collectionName,\n error,\n })\n )\n }\n realtime.restart()\n }\n\n Object.assign(collection, {\n collectionName,\n relationTargets,\n waitForSubscription: realtime.wait,\n isSubscribed: realtime.isOpen,\n heldRelationTargetCount: held.count,\n markSubsetLoaded: subsets.mark,\n loadedSubsetCount: subsets.count,\n holdLive,\n writeFiled,\n releaseFiled,\n expectFiling: fetcher.expectFiling,\n accept,\n reload: adapter.reload,\n evict,\n fetchRelations: views.fetchRelations,\n withRealtime: views.withRealtime,\n })\n\n return collection as unknown as BuiltCollection<RecordType>\n}\n","import type { Collection } from '@tanstack/db'\nimport type PocketBase from 'pocketbase'\nimport {\n buildCollection,\n type CollectionSubscriptionHelpers,\n type CreateCollectionFactoryOptions,\n type PbCollectionUtils,\n} from './build-collection'\nimport type {\n CreateCollectionOptions,\n ExpandPath,\n ExtractRecordType,\n InsertInputOf,\n PbMeta,\n RealtimeMode,\n RelationsOf,\n SchemaDeclaration,\n} from './types'\n\nexport type { CreateCollectionFactoryOptions } from './build-collection'\nexport type { BaseRecord, CreateCollectionOptions, SchemaDeclaration } from './types'\n\n/**\n * A pbtsdb collection or view: a TanStack DB collection over\n * `ExtractRecordType<Schema, C>` rows, plus pbtsdb's subscription helpers.\n * Views are created by {@link PbCollectionView.fetchRelations} and\n * {@link PbCollectionView.withRealtime}, and compose in either order.\n */\nexport type PbCollectionView<\n Schema extends SchemaDeclaration,\n C extends keyof Schema & string,\n Opts,\n> = Collection<\n ExtractRecordType<Schema, C>,\n string | number,\n PbCollectionUtils<ExtractRecordType<Schema, C>>,\n never,\n InsertInputOf<Schema, C, Opts>\n> &\n CollectionSubscriptionHelpers<ExtractRecordType<Schema, C>> & {\n /** The PocketBase collection name */\n readonly collectionName: C\n /** @internal phantom; never present at runtime */\n readonly __pbtsdb: PbMeta<Schema, C, RelationsOf<Opts>>\n /**\n * A view of this collection whose queries also fetch `paths` and file the\n * expanded records into their target collections. Rows are unchanged; read\n * related records through `materialize()`, a join, or the target's `get()`.\n */\n fetchRelations<const P extends readonly ExpandPath<RelationsOf<Opts>>[]>(\n ...paths: P\n ): PbCollectionView<Schema, C, Opts>\n /**\n * A view of this collection whose live queries subscribe to realtime in\n * `mode`, overriding the collection's `realtime` option for those queries.\n * `'query'` requires `syncMode: 'on-demand'`. Returns the collection itself\n * when `mode` equals the collection default.\n */\n withRealtime(mode: RealtimeMode): PbCollectionView<Schema, C, Opts>\n }\n\n/**\n * The collection returned by {@link createCollection}. Identical to\n * {@link PbCollectionView}; kept as the name for the root collection.\n */\nexport type PbCollection<\n Schema extends SchemaDeclaration,\n C extends keyof Schema & string,\n Opts,\n> = PbCollectionView<Schema, C, Opts>\n\ntype AlwaysFetchRelationsCheck<Opts> = {\n alwaysFetchRelations?: readonly ExpandPath<RelationsOf<Opts>>[]\n}\n\n/**\n * Creates a type-safe TanStack DB collection backed by PocketBase.\n * Use this when you need fine-grained control or need to create collections with dependencies.\n *\n * @param pb - PocketBase client instance\n * @param factoryOptions - Options applied to every collection this factory creates\n * @returns A curried function that takes collection name and options\n *\n * @example\n * Basic usage:\n * ```ts\n * const booksCollection = createCollection<Schema>(pb)('books', {});\n *\n * // Use directly\n * const books = await booksCollection.getFullList();\n * ```\n *\n * @example\n * With relations fetched on every request:\n * ```ts\n * const authorsCollection = createCollection<Schema>(pb)('authors', {});\n * const booksCollection = createCollection<Schema>(pb)('books', {\n * relations: { author: authorsCollection },\n * alwaysFetchRelations: ['author'],\n * });\n *\n * const { data } = useLiveQuery((q) => q.from({ books: booksCollection }));\n * // The expanded author is filed into authorsCollection, not kept on the row.\n * authorsCollection.get(data[0].author)?.name\n * ```\n *\n * @example\n * With a per-query fetchRelations view:\n * ```ts\n * const booksCollection = createCollection<Schema>(pb)('books', {\n * relations: { author: authorsCollection },\n * });\n *\n * const view = booksCollection.fetchRelations('author');\n * const { data } = useLiveQuery((q) => q.from({ books: view }));\n * // Same target collection as above; the view only affects what gets fetched.\n * authorsCollection.get(data[0].author)?.name\n * ```\n */\nexport function createCollection<Schema extends SchemaDeclaration>(\n pb: PocketBase,\n factoryOptions?: CreateCollectionFactoryOptions\n) {\n return <C extends keyof Schema & string, const Opts extends CreateCollectionOptions<Schema, C>>(\n collectionName: C,\n options?: Opts & AlwaysFetchRelationsCheck<Opts>\n ): PbCollection<Schema, C, Opts> => {\n return buildCollection<Schema, C>({\n pb,\n factoryOptions,\n collectionName,\n options,\n }) as unknown as PbCollection<Schema, C, Opts>\n }\n}\n","/**\n * Generates a new PocketBase-compatible record ID.\n * Returns a 15-character alphanumeric string (lowercase letters and numbers).\n *\n * PocketBase uses 15-character IDs for records, formatted as lowercase alphanumeric.\n *\n * @returns A 15-character alphanumeric string suitable for use as a PocketBase record ID\n *\n * @example\n * ```ts\n * const id = newRecordId(); // \"a1b2c3d4e5f6g7h\"\n * ```\n */\nexport function newRecordId(): string {\n const chars = 'abcdefghijklmnopqrstuvwxyz0123456789'\n let result = ''\n for (let i = 0; i < 15; i++) {\n result += chars.charAt(Math.floor(Math.random() * chars.length))\n }\n return result\n}\n"]}
|