{"version":3,"file":"optimistic.mjs","names":["defineOptimisticList","apply","groups","store","reference","value","_pagination","rest","args","key","convexToJson","descriptor","group","id","change","matches","compareValues","row","source","entry","candidate","placed","fields","next","field","accessible","evaluateFilter","predicate","order","uncertainDestination","destinations","localCandidate","projected","interval","membership","compareKeys","complete","page","index","seen","rows","i","compared","left","right"],"sources":["../../src/react/optimistic.ts"],"sourcesContent":["import type { OptimisticLocalStore } from 'convex/browser'\nimport type {\n\tFunctionArgs,\n\tFunctionReference,\n\tFunctionReturnType,\n\tPaginationOptions,\n} from 'convex/server'\nimport { compareValues, convexToJson, type Value } from 'convex/values'\nimport { evaluateFilter } from '../querying/shared/evaluate'\nimport type { FilterAst } from '../querying/shared/ast'\n\ntype OptimisticQuery = FunctionReference<\n\t'query',\n\t'public',\n\t{ paginationOpts: PaginationOptions },\n\t{ page: Record<string, Value | undefined>[] }\n>\ntype RowOf<Query extends OptimisticQuery> = FunctionReturnType<Query>['page'][number]\ntype FieldOf<Query extends OptimisticQuery> = keyof RowOf<Query> & string\nexport type OptimisticInterval = {\n\t/** Bounds in declared sort order: lower exclusive, upper inclusive. Null attests an unbounded side. */\n\tlower: readonly Value[] | null\n\tupper: readonly Value[] | null\n}\nexport type OptimisticOrder<Field extends string> = readonly {\n\tfield: Field\n\tdirection: 'asc' | 'desc'\n}[]\n/** Shared server-owned semantics, never inferred from client filters or protected cursors. */\nexport type OptimisticListDescriptor<\n\tQuery extends OptimisticQuery,\n\tWritable extends FieldOf<Query>,\n\tId extends FieldOf<Query> = FieldOf<Query>,\n> = {\n\tid: Id\n\twritable: readonly Writable[]\n\t/** Fields permitted by this args/session's output projection, including the ID. */\n\tfields: (args: FunctionArgs<Query>) => readonly FieldOf<Query>[]\n\tsession: (args: FunctionArgs<Query>) => Value\n\t/** Known predicates may prove false even when other server logic remains undeclared. */\n\tmembership: (args: FunctionArgs<Query>) => { predicate: FilterAst; complete: boolean }\n\t/** Complete, total server ordering, including tie breakers. Missing values remain unknown. */\n\torder?: (args: FunctionArgs<Query>) => OptimisticOrder<FieldOf<Query>>\n\t/** An attested loaded interval, not a decoded cursor or a guessed first-page range. */\n\tinterval?: (\n\t\targs: FunctionArgs<Query>,\n\t\tpage: FunctionReturnType<Query>,\n\t) => OptimisticInterval | undefined\n}\nexport type OptimisticList<\n\tQuery extends OptimisticQuery,\n\tWritable extends FieldOf<Query>,\n\tId extends FieldOf<Query> = FieldOf<Query>,\n> = {\n\tpatch: (\n\t\tstore: OptimisticLocalStore,\n\t\tid: RowOf<Query>[Id],\n\t\tpatch: Partial<Pick<RowOf<Query>, Writable>>,\n\t) => void\n\tinsert: (store: OptimisticLocalStore, row: RowOf<Query>) => void\n\tdelete: (store: OptimisticLocalStore, id: RowOf<Query>[Id]) => void\n}\n\n/** Call synchronously inside withOptimisticUpdate/useCommand. Convex owns replay and rollback. */\nexport function defineOptimisticList<\n\tQuery extends OptimisticQuery,\n\tWritable extends FieldOf<Query>,\n\tId extends FieldOf<Query>,\n>(\n\treference: Query,\n\tdescriptor: OptimisticListDescriptor<Query, Writable, Id>,\n): OptimisticList<Query, Writable, Id> {\n\ttype Row = RowOf<Query>\n\ttype Change =\n\t\t| { kind: 'patch'; id: Row[Id]; patch: Partial<Pick<Row, Writable>> }\n\t\t| { kind: 'insert'; row: Row }\n\t\t| { kind: 'delete'; id: Row[Id] }\n\tfunction apply(store: OptimisticLocalStore, change: Change): void {\n\t\tconst groups = new Map<\n\t\t\tstring,\n\t\t\t{ args: FunctionArgs<Query>; value: FunctionReturnType<Query>; rows: Row[] }[]\n\t\t>()\n\t\tfor (const { args, value } of store.getAllQueries(reference)) {\n\t\t\tif (value === undefined) continue\n\t\t\tconst { paginationOpts: _pagination, ...rest } = args\n\t\t\t// SAFETY: Convex query arguments contain only Convex values; only pagination transport was omitted.\n\t\t\tconst key = JSON.stringify(\n\t\t\t\tconvexToJson([rest as Record<string, Value>, descriptor.session(args)]),\n\t\t\t)\n\t\t\tconst group = groups.get(key) ?? []\n\t\t\tgroup.push({ args, value, rows: value.page })\n\t\t\tgroups.set(key, group)\n\t\t}\n\t\tconst id = change.kind === 'insert' ? change.row[descriptor.id] : change.id\n\t\tconst matches = (row: Row) => compareValues(row[descriptor.id], id) === 0\n\t\tfor (const group of groups.values()) {\n\t\t\tconst source = group.flatMap((entry) =>\n\t\t\t\tentry.rows.filter(matches).map((row) => ({ entry, row })),\n\t\t\t)[0]\n\t\t\tlet candidate: Row | undefined\n\t\t\tlet placed = false\n\t\t\tif (change.kind === 'insert') {\n\t\t\t\tif (!source) candidate = change.row\n\t\t\t} else if (change.kind === 'patch') {\n\t\t\t\tfor (const entry of group) {\n\t\t\t\t\tconst fields = new Set(descriptor.fields(entry.args))\n\t\t\t\t\tentry.rows = entry.rows.flatMap((row) => {\n\t\t\t\t\t\tif (!matches(row)) return [row]\n\t\t\t\t\t\tconst next = { ...row }\n\t\t\t\t\t\tfor (const field of descriptor.writable) {\n\t\t\t\t\t\t\t// A patch cannot turn a hidden/absent output field into knowledge or expose an ID change.\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!Object.is(field, descriptor.id) &&\n\t\t\t\t\t\t\t\tfields.has(field) &&\n\t\t\t\t\t\t\t\tObject.hasOwn(row, field) &&\n\t\t\t\t\t\t\t\tObject.hasOwn(change.patch, field)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tnext[field] = change.patch[field]!\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst { predicate } = descriptor.membership(entry.args)\n\t\t\t\t\t\tconst accessible = new Set(Object.keys(row).filter((field) => fields.has(field)))\n\t\t\t\t\t\tif (evaluateFilter(predicate, next, accessible) === false) return []\n\t\t\t\t\t\treturn [next]\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (source) {\n\t\t\t\t\tconst order = descriptor.order?.(source.entry.args)\n\t\t\t\t\tconst next = source.entry.rows.find(matches)\n\t\t\t\t\t// Never infer rank from a field that was absent before the patch.\n\t\t\t\t\tif (\n\t\t\t\t\t\tnext &&\n\t\t\t\t\t\torder?.length &&\n\t\t\t\t\t\torder.every(\n\t\t\t\t\t\t\t({ field }) =>\n\t\t\t\t\t\t\t\tObject.hasOwn(source.row, field) &&\n\t\t\t\t\t\t\t\tsource.row[field] !== undefined &&\n\t\t\t\t\t\t\t\tdescriptor.fields(source.entry.args).includes(field),\n\t\t\t\t\t\t) &&\n\t\t\t\t\t\torder.some(({ field }) => compareValues(source.row[field], next[field]) !== 0)\n\t\t\t\t\t)\n\t\t\t\t\t\tcandidate = next\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (const entry of group) entry.rows = entry.rows.filter((row) => !matches(row))\n\t\t\t}\n\t\t\tif (candidate) {\n\t\t\t\tlet uncertainDestination = false\n\t\t\t\tconst destinations = group.flatMap((entry) => {\n\t\t\t\t\tconst fields = new Set(descriptor.fields(entry.args))\n\t\t\t\t\tconst existing = entry.value.page.find(matches)\n\t\t\t\t\t// An existing copy owns its field knowledge, including fields absent through redaction.\n\t\t\t\t\tconst localCandidate = existing ? entry.rows.find(matches) : candidate\n\t\t\t\t\tif (!localCandidate) return []\n\t\t\t\t\t// SAFETY: selecting only permitted DTO fields preserves their original values and never merges projections.\n\t\t\t\t\tconst projected = Object.fromEntries(\n\t\t\t\t\t\tObject.entries(localCandidate).filter(([field]) => fields.has(field)),\n\t\t\t\t\t) as Row\n\t\t\t\t\tconst { predicate, complete } = descriptor.membership(entry.args)\n\t\t\t\t\tconst order = descriptor.order?.(entry.args)\n\t\t\t\t\tconst interval = descriptor.interval?.(entry.args, entry.value)\n\t\t\t\t\tconst accessible = new Set(Object.keys(projected))\n\t\t\t\t\tconst membership = evaluateFilter(predicate, projected, accessible)\n\t\t\t\t\tif (membership === false) return []\n\t\t\t\t\tif (\n\t\t\t\t\t\t!accessible.has(descriptor.id) ||\n\t\t\t\t\t\tprojected[descriptor.id] === undefined ||\n\t\t\t\t\t\t!order?.length ||\n\t\t\t\t\t\t!interval ||\n\t\t\t\t\t\t!order.every(({ field }) => accessible.has(field) && projected[field] !== undefined)\n\t\t\t\t\t) {\n\t\t\t\t\t\tuncertainDestination = true\n\t\t\t\t\t\treturn []\n\t\t\t\t\t}\n\t\t\t\t\tconst key = order.map(({ field }) => projected[field]!)\n\t\t\t\t\tif (\n\t\t\t\t\t\t(interval.lower &&\n\t\t\t\t\t\t\t(interval.lower.length !== order.length ||\n\t\t\t\t\t\t\t\tcompareKeys(key, interval.lower, order) <= 0)) ||\n\t\t\t\t\t\t(interval.upper &&\n\t\t\t\t\t\t\t(interval.upper.length !== order.length ||\n\t\t\t\t\t\t\t\tcompareKeys(key, interval.upper, order) > 0))\n\t\t\t\t\t)\n\t\t\t\t\t\treturn []\n\t\t\t\t\tif (\n\t\t\t\t\t\t!complete ||\n\t\t\t\t\t\tmembership !== true ||\n\t\t\t\t\t\t!entry.rows.every((row) =>\n\t\t\t\t\t\t\torder.every(\n\t\t\t\t\t\t\t\t({ field }) =>\n\t\t\t\t\t\t\t\t\tfields.has(field) && Object.hasOwn(row, field) && row[field] !== undefined,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t) {\n\t\t\t\t\t\tuncertainDestination = true\n\t\t\t\t\t\treturn []\n\t\t\t\t\t}\n\t\t\t\t\treturn [{ entry, projected, order }]\n\t\t\t\t})\n\t\t\t\t// Overlapping parent/split subscriptions are not evidence of a unique destination.\n\t\t\t\tif (!uncertainDestination && destinations.length === 1) {\n\t\t\t\t\tplaced = true\n\t\t\t\t\tconst { entry, projected, order } = destinations[0]\n\t\t\t\t\tfor (const page of group) page.rows = page.rows.filter((row) => !matches(row))\n\t\t\t\t\tconst index = entry.rows.findIndex(\n\t\t\t\t\t\t(row) =>\n\t\t\t\t\t\t\tcompareKeys(\n\t\t\t\t\t\t\t\torder.map(({ field }) => projected[field]!),\n\t\t\t\t\t\t\t\torder.map(({ field }) => row[field]!),\n\t\t\t\t\t\t\t\torder,\n\t\t\t\t\t\t\t) < 0,\n\t\t\t\t\t)\n\t\t\t\t\tentry.rows = [\n\t\t\t\t\t\t...entry.rows.slice(0, index < 0 ? entry.rows.length : index),\n\t\t\t\t\t\tprojected,\n\t\t\t\t\t\t...(index < 0 ? [] : entry.rows.slice(index)),\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const entry of group) {\n\t\t\t\tconst seen = new Set<string>()\n\t\t\t\tconst rows = entry.rows.filter((row) => {\n\t\t\t\t\tif (!placed && (change.kind === 'insert' || !matches(row))) return true\n\t\t\t\t\tconst key = JSON.stringify(convexToJson(row[descriptor.id] ?? null))\n\t\t\t\t\tif (seen.has(key)) return false\n\t\t\t\t\tseen.add(key)\n\t\t\t\t\treturn true\n\t\t\t\t})\n\t\t\t\tif (\n\t\t\t\t\trows.length === entry.value.page.length &&\n\t\t\t\t\trows.every((row, i) => row === entry.value.page[i])\n\t\t\t\t)\n\t\t\t\t\tcontinue\n\t\t\t\tstore.setQuery(reference, entry.args, { ...entry.value, page: rows })\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\tpatch: (store, id, patch) => apply(store, { kind: 'patch', id, patch }),\n\t\tinsert: (store, row) => apply(store, { kind: 'insert', row }),\n\t\tdelete: (store, id) => apply(store, { kind: 'delete', id }),\n\t}\n}\nfunction compareKeys(\n\tleft: readonly Value[],\n\tright: readonly Value[],\n\torder: OptimisticOrder<string>,\n): number {\n\tfor (let index = 0; index < order.length; index++) {\n\t\tconst compared = compareValues(left[index], right[index])\n\t\tif (compared) return order[index].direction === 'asc' ? compared : -compared\n\t}\n\treturn 0\n}\n"],"mappings":"iIAgEA,SAAgBA,EAKf,EACA,EACsC,CAMtC,SAASC,EAAM,EAA6B,EAAsB,CACjE,IAAMC,kBAAS,IAAI,IAInB,IAAK,GAAM,CAAE,OAAM,WAAWC,EAAM,cAAcC,CAAS,EAAG,CAC7D,GAAIC,IAAU,IAAA,GAAW,SACzB,GAAM,CAAE,eAAgBC,EAAa,GAAGC,GAASC,EAE3CC,EAAM,KAAK,UA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