{"version":3,"file":"use-paginated-list.mjs","names":["epoch","usePaginatedList","options","pageSize","skip","args","effectiveArgs","identity","getFunctionName","query","convexToJson","stored","setState","useState","initialPagination","state","queries","useMemo","key","interval","paginationOpts","results","useQueries","reconcilePagination","errors","queryErrors","failure","decodeFailure","queryFailure","invalid","view","paginationView","currentEpoch","previous","nextPagination"],"sources":["../../src/react/use-paginated-list.ts"],"sourcesContent":["import { useMemo, useState } from 'react'\nimport { useQueries } from 'convex/react'\nimport {\n\tgetFunctionName,\n\ttype FunctionArgs,\n\ttype FunctionReference,\n\ttype FunctionReturnType,\n\ttype PaginationOptions,\n} from 'convex/server'\nimport { convexToJson, type Value } from 'convex/values'\nimport { queryErrors } from '../modules/contracts/errors'\nimport { decodeFailure, type FailureContract, type FailureOf } from './failures'\nimport {\n\tinitialPagination,\n\treconcilePagination,\n\tnextPagination,\n\tpaginationView,\n\ttype ListPage,\n} from './pagination-state'\n\nexport type ListQueryReference = FunctionReference<\n\t'query',\n\t'public',\n\t{ paginationOpts: PaginationOptions },\n\tListPage\n>\nexport type PaginatedList<\n\tQuery extends ListQueryReference,\n\tContract extends FailureContract = typeof queryErrors,\n> = {\n\trows: FunctionReturnType<Query>['page']\n\tisLoading: boolean\n\thasNextPage: boolean\n\tisFetchingNextPage: boolean\n\tfetchNextPage: () => void\n\tresetKey: string\n\tcompleteness: FunctionReturnType<Query>['completeness'] | undefined\n\tfailure: FailureOf<Contract> | undefined\n\t/** Original subscription error, without decoding or mutation. */\n\terror: Error | undefined\n}\nexport type PaginatedListOptions<Contract extends FailureContract = typeof queryErrors> = {\n\t/** Integer 1..100. Initial target for native search; browse uses fixed adjacent pages. */\n\tpageSize: number\n\tonInvalidCursor?: 'restart' | 'throw'\n\t/** Keep failures in state (default), or throw the original error to a React boundary. */\n\tonFailure?: 'state' | 'throw'\n\t/** Explicit server contract; generated references do not carry error metadata. Defaults to queryErrors. */\n\terrors?: Contract\n\t/** Convex value identifying the current auth/scope/reset generation. Never a credential. */\n\tresetIdentity?: Value\n}\ntype IntervalPagination = {\n\tnumItems: number\n\tcursor: string | null\n\tid: number\n\tendCursor?: string\n}\nlet epoch = 0\n/** Reactive engine-backed list: fixed browse ranges or SDK-journal search windows. Empty pages advance manually. */\nexport function usePaginatedList<\n\tQuery extends ListQueryReference,\n\tContract extends FailureContract = typeof queryErrors,\n>(\n\tquery: Query,\n\targs: Omit<FunctionArgs<Query>, 'paginationOpts'> | 'skip',\n\toptions: PaginatedListOptions<Contract>,\n): PaginatedList<Query, Contract> {\n\tconst { pageSize } = options\n\tif (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 100)\n\t\tthrow new Error('pageSize must be an integer from 1 to 100')\n\tconst skip = args === 'skip'\n\t// Convex's public encoder sorts object keys recursively and preserves array order, IDs, bytes and int64.\n\t// SAFETY: FunctionArgs are Convex values; pagination transport is owned exclusively by this hook.\n\tconst effectiveArgs = skip ? {} : (args as Record<string, Value>)\n\tconst identity = JSON.stringify([\n\t\tgetFunctionName(query),\n\t\tconvexToJson(effectiveArgs),\n\t\tconvexToJson(options.resetIdentity ?? null),\n\t\tpageSize,\n\t\tskip,\n\t])\n\tconst [stored, setState] = useState(() =>\n\t\tinitialPagination<FunctionReturnType<Query>>(identity, ++epoch, skip),\n\t)\n\tlet state = stored\n\tif (state.identity !== identity) state = initialPagination(identity, ++epoch, skip)\n\tconst queries = useMemo(\n\t\t() =>\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.entries(state.intervals).map(([key, interval]) => {\n\t\t\t\t\tconst paginationOpts: IntervalPagination = {\n\t\t\t\t\t\tnumItems: pageSize,\n\t\t\t\t\t\tcursor: interval.cursor,\n\t\t\t\t\t\tid: state.epoch,\n\t\t\t\t\t}\n\t\t\t\t\tif (interval.endCursor !== undefined) paginationOpts.endCursor = interval.endCursor\n\t\t\t\t\treturn [key, { query, args: { ...effectiveArgs, paginationOpts } }]\n\t\t\t\t}),\n\t\t\t),\n\t\t// Equivalent args/references must keep subscriptions stable; identity encodes their effective values.\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[state.intervals, state.epoch, identity],\n\t)\n\t// SAFETY: useQueries returns each complete endpoint result or an Error for the keyed subscription.\n\tconst results = useQueries(queries) as Record<\n\t\tstring,\n\t\tFunctionReturnType<Query> | Error | undefined\n\t>\n\tstate = reconcilePagination(state, results)\n\tconst errors = options.errors ?? queryErrors\n\tlet failure = state.error ? decodeFailure(state.error, errors) : undefined\n\t// Both the explicit decoder and the fixed query contract must validate the actual transported envelope.\n\tconst queryFailure = state.error ? decodeFailure(state.error, queryErrors) : undefined\n\tconst invalid =\n\t\tstate.error &&\n\t\tfailure?._tag === 'DeclaredFailure' &&\n\t\tfailure.code === 'invalid-cursor' &&\n\t\tqueryFailure?._tag === 'DeclaredFailure' &&\n\t\tqueryFailure.code === 'invalid-cursor'\n\tif (invalid && options.onInvalidCursor !== 'throw' && !state.restarted) {\n\t\tstate = initialPagination(identity, ++epoch, skip, true)\n\t\tfailure = undefined\n\t}\n\tif (state !== stored) setState(state)\n\t// Recovery runs first. A boundary unmount releases useQueries subscriptions even\n\t// when the render-phase state update above cannot commit because this render throws.\n\tif (\n\t\tstate.error &&\n\t\t(options.onFailure === 'throw' || (invalid && options.onInvalidCursor === 'throw'))\n\t)\n\t\tthrow state.error\n\tconst view = paginationView(state)\n\tconst currentEpoch = state.epoch\n\treturn {\n\t\t...view,\n\t\t// SAFETY: the controller concatenates unmodified elements from this query's validated page DTOs.\n\t\trows: view.rows as FunctionReturnType<Query>['page'],\n\t\tcompleteness: view.completeness,\n\t\t// SAFETY: omitted errors selects the default Contract parameter; an explicit contract owns its decoder.\n\t\tfailure: failure as FailureOf<Contract> | undefined,\n\t\terror: state.error,\n\t\tresetKey: `${identity}:${state.restarted ? 1 : 0}`,\n\t\tfetchNextPage: () =>\n\t\t\tsetState((previous) =>\n\t\t\t\tprevious.epoch === currentEpoch && previous.identity === identity\n\t\t\t\t\t? nextPagination(previous)\n\t\t\t\t\t: previous,\n\t\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