@confect/react 10.0.0-next.20 → 10.0.0-next.22
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/CHANGELOG.md +121 -39
- package/dist/PaginatedQueryResult.d.ts +4 -4
- package/dist/PaginatedQueryResult.js.map +1 -1
- package/dist/QueryResult.d.ts.map +1 -1
- package/dist/QueryResult.js.map +1 -1
- package/dist/StreamPagination.d.ts +127 -0
- package/dist/StreamPagination.d.ts.map +1 -0
- package/dist/StreamPagination.js +170 -0
- package/dist/StreamPagination.js.map +1 -0
- package/dist/index.d.ts +31 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +155 -13
- package/dist/index.js.map +1 -1
- package/package.json +17 -17
- package/src/PaginatedQueryResult.ts +5 -5
- package/src/QueryResult.ts +0 -1
- package/src/StreamPagination.ts +369 -0
- package/src/index.ts +294 -17
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["useConvexQuery","QueryResult.load","QueryResult.succeed","QueryResult.fail","convexVersion","PaginatedQueryResult.failure","PaginatedQueryResult.loadingFirstPage","PaginatedQueryResult.loadingMore","PaginatedQueryResult.canLoadMore","PaginatedQueryResult.exhausted","OptimisticLocalStore.make","useConvexMutation","useConvexAction"],"sources":["../src/index.ts"],"sourcesContent":["import { Ref } from \"@confect/core\";\nimport { version as convexVersion } from \"convex\";\nimport type { OptimisticUpdate as ConvexOptimisticUpdate } from \"convex/browser\";\nimport * as ConvexReact from \"convex/react\";\nimport type { usePaginatedQuery as useConvexPaginatedQuery } from \"convex/react\";\nimport {\n useAction as useConvexAction,\n useMutation as useConvexMutation,\n useQuery as useConvexQuery,\n type ReactMutation as ConvexReactMutation,\n} from \"convex/react\";\nimport type { FunctionReference } from \"convex/server\";\nimport type { Value } from \"convex/values\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Result from \"effect/Result\";\nimport * as Exit from \"effect/Exit\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport { useCallback, useMemo } from \"react\";\n\nimport * as OptimisticLocalStore from \"./OptimisticLocalStore\";\nimport * as PaginatedQueryResult from \"./PaginatedQueryResult\";\nimport * as QueryResult from \"./QueryResult\";\n\nexport { OptimisticLocalStore, PaginatedQueryResult, QueryResult };\n\nexport type InvokeReturn<Ref_ extends Ref.Any> = [Ref.Error<Ref_>] extends [\n never,\n]\n ? Promise<Ref.Returns<Ref_>>\n : Promise<Result.Result<Ref.Returns<Ref_>, Ref.Error<Ref_>>>;\n\ntype UseQueryArgs<Query extends Ref.AnyPublicQuery> =\n keyof Ref.Args<Query> extends never\n ? [args?: Ref.Args<Query> | \"skip\"]\n : [args: Ref.Args<Query> | \"skip\"];\n\nexport const useQuery = <Query extends Ref.AnyPublicQuery>(\n ref: Query,\n ...rest: UseQueryArgs<Query>\n): QueryResult.QueryResult<Ref.Returns<Query>, Ref.Error<Query>> => {\n const functionReference = Ref.getFunctionReference(ref);\n const args = rest[0];\n const skipped = args === \"skip\";\n const encodedArgs = skipped\n ? \"skip\"\n : Ref.encodeArgsSync(ref, (args ?? {}) as Ref.Args<Query>);\n\n // `useConvexQuery` returns a referentially stable value while the underlying\n // Convex result is unchanged, and throws a stable error when the query\n // fails. We capture either outcome as a `Result` and decode/wrap it inside\n // `useMemo` so that the returned `QueryResult` keeps a stable identity across\n // renders when nothing has actually changed. Decoding on every render would\n // hand consumers a fresh object each time, breaking effects and memoization\n // that depend on the result's identity.\n const encodedReturnsOrError: Result.Result<unknown, unknown> = Result.try(\n () => useConvexQuery(functionReference, encodedArgs),\n );\n\n return useMemo(\n () =>\n Result.match(encodedReturnsOrError, {\n onSuccess: (encodedReturnsOrUndefined) =>\n encodedReturnsOrUndefined === undefined\n ? QueryResult.load(skipped)\n : QueryResult.succeed(\n Ref.decodeReturnsSync(ref, encodedReturnsOrUndefined),\n ),\n onFailure: (error) => {\n if (Ref.isConvexError(error)) {\n const decoded = Ref.decodeErrorOption(ref, error.data);\n if (Option.isSome(decoded)) {\n return QueryResult.fail(decoded.value);\n }\n }\n throw error;\n },\n }),\n // `Result.try` allocates a fresh wrapper each render, so we key the memo on\n // the stable value it carries (the Convex result or thrown error) rather\n // than the wrapper itself; the decoded result is a function of that value,\n // `ref`, and `skipped`.\n [ref, skipped, Result.merge(encodedReturnsOrError)],\n );\n};\n\n/**\n * Like `Omit`, but implemented with key remapping so that optional modifiers\n * are preserved and index signatures don't reintroduce the omitted key's\n * literal type. Mirrors `BetterOmit` from `convex/server`.\n */\ntype OmitKey<T, K extends PropertyKey> = {\n [P in keyof T as P extends K ? never : P]: T[P];\n};\n\n/**\n * The args accepted by {@link usePaginatedQuery}: the ref's args without\n * `paginationOpts`, which the underlying Convex hook manages itself. When no\n * args remain, resolves to `Record<string, never>` (only the empty object is\n * accepted) rather than `{}`, which would accept any non-nullish value.\n */\nexport type PaginatedQueryArgs<Query extends Ref.AnyPublicPaginatedQuery> =\n OmitKey<Ref.Args<Query>, \"paginationOpts\"> extends infer Args_\n ? keyof Args_ extends never\n ? Record<string, never>\n : Args_\n : never;\n\n/**\n * The item type for a paginated query: the element type of the `page` field\n * of the ref's returns.\n */\nexport type PaginatedQueryItem<Query extends Ref.AnyPublicPaginatedQuery> =\n Ref.Returns<Query>[\"page\"][number];\n\n/**\n * The args parameter of {@link usePaginatedQuery}: the ref's args without\n * `paginationOpts`, or `\"skip\"` to skip the query.\n */\nexport type UsePaginatedQueryArgs<Query extends Ref.AnyPublicPaginatedQuery> =\n | PaginatedQueryArgs<Query>\n | \"skip\";\n\nexport type PaginatedQueryOptions = Parameters<\n typeof useConvexPaginatedQuery\n>[2];\n\n/**\n * The `user`-facing result of `usePaginatedQueryInternal` from `convex/react`,\n * including the `\"Error\"` status its non-throwing mode can return.\n */\ninterface ConvexPaginatedQueryInternalUser {\n readonly results: ReadonlyArray<unknown>;\n readonly status:\n | \"LoadingFirstPage\"\n | \"LoadingMore\"\n | \"CanLoadMore\"\n | \"Exhausted\"\n | \"Error\";\n readonly isLoading: boolean;\n readonly loadMore: (numItems: number) => void;\n readonly error?: unknown;\n}\n\ntype UseConvexPaginatedQueryInternal = (\n query: FunctionReference<\"query\">,\n args: Record<string, Value> | \"skip\",\n options: PaginatedQueryOptions,\n throwOnError: boolean,\n) => { user: ConvexPaginatedQueryInternalUser };\n\n// `usePaginatedQueryInternal` is runtime-exported by convex/react but absent\n// from its public type declarations. It is the only way to observe query\n// errors as values: the public positional `usePaginatedQuery` hard-codes\n// throwOnError and throws mid-hook-sequence, which cannot be caught without\n// breaking React's hook-order invariant.\nconst useConvexPaginatedQueryInternal = (\n ConvexReact as unknown as Record<string, unknown>\n).usePaginatedQueryInternal as UseConvexPaginatedQueryInternal | undefined;\n\nconst MINIMUM_CONVEX_VERSION = \"1.36.0\";\n\n/**\n * The non-throwing mode of `usePaginatedQueryInternal` — its fourth,\n * `throwOnError` parameter — arrived in convex 1.36.0. Convex 1.32 through\n * 1.35 export the same symbol taking only three parameters, where a fourth\n * argument is silently ignored and errors are always thrown.\n *\n * The function itself cannot be interrogated for this: `Function.length`\n * counts parameters up to the first one with a default, and 1.36.0 declares\n * `throwOnError = true`, so both shapes report an arity of 3. The package\n * version is the only reliable signal.\n */\nconst supportsErrorsAsValues = ((): boolean => {\n const [major, minor] = String(convexVersion).split(\".\").map(Number);\n if (\n major === undefined ||\n minor === undefined ||\n Number.isNaN(major) ||\n Number.isNaN(minor)\n ) {\n return false;\n }\n const [minimumMajor, minimumMinor] = MINIMUM_CONVEX_VERSION.split(\".\").map(\n Number,\n ) as [number, number];\n return (\n major > minimumMajor || (major === minimumMajor && minor >= minimumMinor)\n );\n})();\n\n/**\n * Load data reactively from a paginated query defined with\n * `FunctionSpec.publicPaginatedQuery`, mirroring the ergonomics of\n * `usePaginatedQuery` from `convex/react`.\n *\n * Args are encoded via the ref's user-args schema (`paginationOpts` is managed\n * by the Convex hook, not the caller), and each loaded page is decoded via the\n * ref's item schema.\n *\n * Returns a {@link PaginatedQueryResult.PaginatedQueryResult}: the loaded\n * variants carry `results` and `isLoading`, and `CanLoadMore` additionally\n * carries `loadMore`; if the `Ref` declares an `error` schema and the query\n * fails with that typed error, the decoded error is returned as the `Failure`\n * variant, which also carries the pages loaded before the failure. Unknown\n * errors are thrown, to be caught by an error boundary.\n */\nexport const usePaginatedQuery = <Query extends Ref.AnyPublicPaginatedQuery>(\n ref: Query,\n args: UsePaginatedQueryArgs<Query>,\n options: PaginatedQueryOptions,\n): PaginatedQueryResult.PaginatedQueryResult<\n PaginatedQueryItem<Query>,\n Ref.Error<Query>\n> => {\n if (\n useConvexPaginatedQueryInternal === undefined ||\n !supportsErrorsAsValues\n ) {\n throw new Error(\n `usePaginatedQuery requires convex >= ${MINIMUM_CONVEX_VERSION}, but found ` +\n `${convexVersion}. Earlier versions always throw paginated query errors ` +\n \"instead of returning them, so a declared `error` schema cannot be \" +\n \"surfaced as a `Failure` — upgrade the `convex` package.\",\n );\n }\n\n const functionReference = Ref.getFunctionReference(ref);\n const skipped = args === \"skip\";\n\n // The encoded output is the wire form Convex's hook forwards verbatim, not\n // the ref's decoded args type.\n const encodedArgs = useMemo(\n () =>\n args === \"skip\"\n ? (\"skip\" as const)\n : (Ref.encodePaginatedQueryArgsSync(\n ref,\n args as unknown as Omit<Ref.Args<Query>, \"paginationOpts\">,\n ) as Record<string, Value>),\n [ref, args],\n );\n\n const { user: convexResult } = useConvexPaginatedQueryInternal(\n functionReference,\n encodedArgs,\n options,\n false,\n );\n\n // The Convex hook carries the pages loaded so far on every status,\n // failures included, so results are decoded unconditionally.\n //\n // Decoding allocates fresh items, so key on the referentially stable\n // `results` the Convex hook provides — the same identity-preservation\n // rationale as in `useQuery` above.\n const { results: encodedResults } = convexResult;\n const decodedResults = useMemo(\n () => Ref.decodePaginationPageSync(ref, encodedResults),\n [ref, encodedResults],\n );\n\n const { status, loadMore } = convexResult;\n const error = status === \"Error\" ? convexResult.error : undefined;\n\n return useMemo(\n (): PaginatedQueryResult.Variants<\n PaginatedQueryItem<Query>,\n Ref.Error<Query>\n > =>\n // `status` is a bare string union rather than a tagged one, so the arms\n // match on literals.\n Match.value(status).pipe(\n Match.when(\"Error\", () => {\n if (Ref.isConvexError(error)) {\n const decoded = Ref.decodeErrorOption(ref, error.data);\n if (Option.isSome(decoded)) {\n return PaginatedQueryResult.failure({\n error: decoded.value,\n results: decodedResults,\n });\n }\n }\n // Unknown errors still throw. All hooks have run by this point, so\n // an aborted render here is hook-order-safe.\n throw error;\n }),\n Match.when(\"LoadingFirstPage\", () =>\n PaginatedQueryResult.loadingFirstPage({ skipped }),\n ),\n Match.when(\"LoadingMore\", () =>\n PaginatedQueryResult.loadingMore({ results: decodedResults }),\n ),\n // `CanLoadMore` is the only status whose `loadMore` does anything —\n // the Convex hook returns an intentional no-op for all the others, so\n // they carry no callback at all.\n Match.when(\"CanLoadMore\", () =>\n PaginatedQueryResult.canLoadMore({\n results: decodedResults,\n loadMore,\n }),\n ),\n Match.when(\"Exhausted\", () =>\n PaginatedQueryResult.exhausted({ results: decodedResults }),\n ),\n Match.exhaustive,\n ),\n // The memo produces `Variants`, the conditional return type's superset —\n // when `E` is `never` the `Failure` arm is unreachable at runtime, which\n // is exactly what the conditional encodes.\n [ref, skipped, decodedResults, status, loadMore, error],\n ) as PaginatedQueryResult.PaginatedQueryResult<\n PaginatedQueryItem<Query>,\n Ref.Error<Query>\n >;\n};\n\n/**\n * An optimistic update for a Confect mutation. Mirrors Convex's\n * `OptimisticUpdate`, but receives a Confect {@link OptimisticLocalStore} and\n * the decoded mutation `args`.\n */\nexport type OptimisticUpdate<Mutation extends Ref.AnyPublicMutation> = (\n localStore: OptimisticLocalStore.OptimisticLocalStore,\n args: Ref.Args<Mutation>,\n) => void;\n\n/**\n * The handle returned by {@link useMutation}. It is callable like the function\n * returned by Convex's `useMutation`, and additionally exposes\n * `withOptimisticUpdate` for attaching an optimistic update. Mirrors the\n * `ReactMutation` type from `convex/react`.\n */\nexport interface ReactMutation<Mutation extends Ref.AnyPublicMutation> {\n (...args: Ref.OptionalArgs<Mutation>): InvokeReturn<Mutation>;\n withOptimisticUpdate(\n optimisticUpdate: OptimisticUpdate<Mutation>,\n ): ReactMutation<Mutation>;\n}\n\nconst makeReactMutation = <Mutation extends Ref.AnyPublicMutation>(\n ref: Mutation,\n convexReactMutation: ConvexReactMutation<\n Ref.FunctionReference<Mutation> & FunctionReference<\"mutation\">\n >,\n): ReactMutation<Mutation> => {\n const callable = ((...args: Ref.OptionalArgs<Mutation>) =>\n invokeAsResult(\n ref,\n (_, encodedArgs) => convexReactMutation(encodedArgs as never),\n args,\n ).then((result) =>\n Ref.hasErrorSchema(ref) ? result : Result.getOrThrow(result),\n )) as (...args: Ref.OptionalArgs<Mutation>) => InvokeReturn<Mutation>;\n\n const withOptimisticUpdate = (\n optimisticUpdate: OptimisticUpdate<Mutation>,\n ): ReactMutation<Mutation> => {\n const wrappedUpdate: ConvexOptimisticUpdate<Record<string, Value>> = (\n convexLocalStore,\n encodedArgs,\n ) => {\n const decodedArgs = Ref.decodeArgsSync(ref, encodedArgs);\n optimisticUpdate(\n OptimisticLocalStore.make(convexLocalStore),\n decodedArgs,\n );\n };\n const nextConvexReactMutation =\n convexReactMutation.withOptimisticUpdate(wrappedUpdate);\n return makeReactMutation(ref, nextConvexReactMutation);\n };\n\n return Object.assign(callable, { withOptimisticUpdate });\n};\n\n/**\n * Returns a {@link ReactMutation} handle for the provided `Ref`'s mutation. The\n * handle is callable to invoke the mutation, and exposes `withOptimisticUpdate`\n * for attaching an optimistic update, mirroring `useMutation` from\n * `convex/react`.\n *\n * If the `Ref` declares an `error` schema, the returned promise resolves to a\n * `Result` with the decoded `returns` value in the `Success` and the decoded\n * error in the `Failure`.\n *\n * If the `Ref` does not declare an `error` schema, the promise resolves\n * directly to the decoded `returns` value, matching the behavior of\n * `useMutation` from `convex/react`.\n *\n * Any other failure rejects the promise.\n */\nexport const useMutation = <Mutation extends Ref.AnyPublicMutation>(\n ref: Mutation,\n): ReactMutation<Mutation> => {\n const functionReference = Ref.getFunctionReference(ref);\n const convexReactMutation = useConvexMutation(functionReference);\n\n return useMemo(\n () =>\n makeReactMutation(\n ref,\n convexReactMutation as ConvexReactMutation<\n Ref.FunctionReference<Mutation> & FunctionReference<\"mutation\">\n >,\n ),\n [ref, convexReactMutation],\n );\n};\n\n/**\n * Returns a function that invokes the provided `Ref`'s action.\n *\n * If the `Ref` declares an `error` schema, the returned promise resolves to a\n * `Result` with the decoded `returns` value in the `Success` and the decoded\n * error in the `Failure`.\n *\n * If the `Ref` does not declare an `error` schema, the promise resolves\n * directly to the decoded `returns` value, matching the behavior of\n * `useMutation` from `convex/react`.\n *\n * Any other failure rejects the promise.\n */\nexport const useAction = <Action extends Ref.AnyPublicAction>(\n ref: Action,\n): ((...args: Ref.OptionalArgs<Action>) => InvokeReturn<Action>) => {\n const functionReference = Ref.getFunctionReference(ref);\n const actualAction = useConvexAction(functionReference);\n\n return useCallback(\n ((...args: Ref.OptionalArgs<Action>) =>\n invokeAsResult(\n ref,\n (_, encodedArgs) => actualAction(encodedArgs),\n args,\n ).then((result) =>\n Ref.hasErrorSchema(ref) ? result : Result.getOrThrow(result),\n )) as (...args: Ref.OptionalArgs<Action>) => InvokeReturn<Action>,\n [ref, actualAction],\n );\n};\n\nconst invokeAsResult = async <Ref_ extends Ref.Any>(\n ref: Ref_,\n invoke: (\n fnRef: Ref.FunctionReference<Ref_>,\n encodedArgs: unknown,\n ) => PromiseLike<unknown>,\n args: Ref.OptionalArgs<Ref_>,\n): Promise<Result.Result<Ref.Returns<Ref_>, Ref.Error<Ref_>>> => {\n const exit = await Effect.runPromiseExit(\n Ref.runWithCodec(ref, (args[0] ?? {}) as Ref.Args<Ref_>, invoke).pipe(\n Effect.catchTag(\"SchemaError\", Effect.die),\n Effect.result,\n ),\n );\n if (Exit.isSuccess(exit)) return exit.value;\n throw Cause.squash(exit.cause);\n};\n"],"mappings":";;;;;;;;;;;;;;;AAsCA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EAC5B,MAAM,iBACJ,kBACA,gBACG;GACH,MAAM,cAAc,IAAI,eAAe,KAAK,WAAW;GACvD,iBACEC,KAA0B,gBAAgB,GAC1C,WACF;EACF;EACA,MAAM,0BACJ,oBAAoB,qBAAqB,aAAa;EACxD,OAAO,kBAAkB,KAAK,uBAAuB;CACvD;CAEA,OAAO,OAAO,OAAO,UAAU,EAAE,qBAAqB,CAAC;AACzD;;;;;;;;;;;;;;;;;AAkBA,MAAa,eACX,QAC4B;CAE5B,MAAM,sBAAsBC,cADF,IAAI,qBAAqB,GACW,CAAC;CAE/D,OAAO,cAEH,kBACE,KACA,mBAGF,GACF,CAAC,KAAK,mBAAmB,CAC3B;AACF;;;;;;;;;;;;;;AAeA,MAAa,aACX,QACkE;CAElE,MAAM,eAAeC,YADK,IAAI,qBAAqB,GACE,CAAC;CAEtD,OAAO,cACH,GAAG,SACH,eACE,MACC,GAAG,gBAAgB,aAAa,WAAW,GAC5C,IACF,CAAC,CAAC,MAAM,WACN,IAAI,eAAe,GAAG,IAAI,SAAS,OAAO,WAAW,MAAM,CAC7D,IACF,CAAC,KAAK,YAAY,CACpB;AACF;AAEA,MAAM,iBAAiB,OACrB,KACA,QAIA,SAC+D;CAC/D,MAAM,OAAO,MAAM,OAAO,eACxB,IAAI,aAAa,KAAM,KAAK,MAAM,CAAC,GAAsB,MAAM,CAAC,CAAC,KAC/D,OAAO,SAAS,eAAe,OAAO,GAAG,GACzC,OAAO,MACT,CACF;CACA,IAAI,KAAK,UAAU,IAAI,GAAG,OAAO,KAAK;CACtC,MAAM,MAAM,OAAO,KAAK,KAAK;AAC/B"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["useConvexQuery","QueryResult.load","QueryResult.succeed","QueryResult.fail","convexVersion","PaginatedQueryResult.failure","PaginatedQueryResult.loadingFirstPage","PaginatedQueryResult.loadingMore","PaginatedQueryResult.canLoadMore","PaginatedQueryResult.exhausted","StreamPagination.empty","StreamPagination.initial","StreamPagination.pageRequests","useConvexQueries","StreamPagination.interpret","StreamPagination.isLastPageSplitting","StreamPagination.loadMore","OptimisticLocalStore.make","useConvexMutation","useConvexAction"],"sources":["../src/index.ts"],"sourcesContent":["import { Ref } from \"@confect/core\";\nimport { version as convexVersion } from \"convex\";\nimport type { OptimisticUpdate as ConvexOptimisticUpdate } from \"convex/browser\";\nimport * as ConvexReact from \"convex/react\";\nimport type { usePaginatedQuery as useConvexPaginatedQuery } from \"convex/react\";\nimport {\n useAction as useConvexAction,\n useMutation as useConvexMutation,\n useQueries as useConvexQueries,\n useQuery as useConvexQuery,\n type ReactMutation as ConvexReactMutation,\n} from \"convex/react\";\nimport { getFunctionName, type FunctionReference } from \"convex/server\";\nimport { ConvexError, convexToJson, type Value } from \"convex/values\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Result from \"effect/Result\";\nimport * as Exit from \"effect/Exit\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport { useCallback, useMemo, useState } from \"react\";\n\nimport * as OptimisticLocalStore from \"./OptimisticLocalStore\";\nimport * as PaginatedQueryResult from \"./PaginatedQueryResult\";\nimport * as QueryResult from \"./QueryResult\";\nimport * as StreamPagination from \"./StreamPagination\";\n\nexport {\n OptimisticLocalStore,\n PaginatedQueryResult,\n QueryResult,\n StreamPagination,\n};\n\nexport type InvokeReturn<Ref_ extends Ref.Any> = [Ref.Error<Ref_>] extends [\n never,\n]\n ? Promise<Ref.Returns<Ref_>>\n : Promise<Result.Result<Ref.Returns<Ref_>, Ref.Error<Ref_>>>;\n\ntype UseQueryArgs<Query extends Ref.AnyPublicQuery> =\n keyof Ref.Args<Query> extends never\n ? [args?: Ref.Args<Query> | \"skip\"]\n : [args: Ref.Args<Query> | \"skip\"];\n\nexport const useQuery = <Query extends Ref.AnyPublicQuery>(\n ref: Query,\n ...rest: UseQueryArgs<Query>\n): QueryResult.QueryResult<Ref.Returns<Query>, Ref.Error<Query>> => {\n const functionReference = Ref.getFunctionReference(ref);\n const args = rest[0];\n const skipped = args === \"skip\";\n const encodedArgs = skipped\n ? \"skip\"\n : Ref.encodeArgsSync(ref, (args ?? {}) as Ref.Args<Query>);\n\n // `useConvexQuery` returns a referentially stable value while the underlying\n // Convex result is unchanged, and throws a stable error when the query\n // fails. We capture either outcome as a `Result` and decode/wrap it inside\n // `useMemo` so that the returned `QueryResult` keeps a stable identity across\n // renders when nothing has actually changed. Decoding on every render would\n // hand consumers a fresh object each time, breaking effects and memoization\n // that depend on the result's identity.\n const encodedReturnsOrError: Result.Result<unknown, unknown> = Result.try(\n () => useConvexQuery(functionReference, encodedArgs),\n );\n\n return useMemo(\n () =>\n Result.match(encodedReturnsOrError, {\n onSuccess: (encodedReturnsOrUndefined) =>\n encodedReturnsOrUndefined === undefined\n ? QueryResult.load(skipped)\n : QueryResult.succeed(\n Ref.decodeReturnsSync(ref, encodedReturnsOrUndefined),\n ),\n onFailure: (error) => {\n if (Ref.isConvexError(error)) {\n const decoded = Ref.decodeErrorOption(ref, error.data);\n if (Option.isSome(decoded)) {\n return QueryResult.fail(decoded.value);\n }\n }\n throw error;\n },\n }),\n // `Result.try` allocates a fresh wrapper each render, so we key the memo on\n // the stable value it carries (the Convex result or thrown error) rather\n // than the wrapper itself; the decoded result is a function of that value,\n // `ref`, and `skipped`.\n [ref, skipped, Result.merge(encodedReturnsOrError)],\n );\n};\n\n/**\n * Like `Omit`, but implemented with key remapping so that optional modifiers\n * are preserved and index signatures don't reintroduce the omitted key's\n * literal type. Mirrors `BetterOmit` from `convex/server`.\n */\ntype OmitKey<T, K extends PropertyKey> = {\n [P in keyof T as P extends K ? never : P]: T[P];\n};\n\n/**\n * The args accepted by {@link usePaginatedQuery}: the ref's args without\n * `paginationOpts`, which the underlying Convex hook manages itself. When no\n * args remain, resolves to `Record<string, never>` (only the empty object is\n * accepted) rather than `{}`, which would accept any non-nullish value.\n */\nexport type PaginatedQueryArgs<Query extends Ref.AnyPublicPaginatedQuery> =\n OmitKey<Ref.Args<Query>, \"paginationOpts\"> extends infer Args_\n ? keyof Args_ extends never\n ? Record<string, never>\n : Args_\n : never;\n\n/**\n * The item type for a paginated query: the element type of the `page` field\n * of the ref's returns.\n */\nexport type PaginatedQueryItem<Query extends Ref.AnyPublicPaginatedQuery> =\n Ref.Returns<Query>[\"page\"][number];\n\n/**\n * The args parameter of {@link usePaginatedQuery}: the ref's args without\n * `paginationOpts`, or `\"skip\"` to skip the query.\n */\nexport type UsePaginatedQueryArgs<Query extends Ref.AnyPublicPaginatedQuery> =\n | PaginatedQueryArgs<Query>\n | \"skip\";\n\nexport type PaginatedQueryOptions = Parameters<\n typeof useConvexPaginatedQuery\n>[2];\n\n/**\n * The `user`-facing result of `usePaginatedQueryInternal` from `convex/react`,\n * including the `\"Error\"` status its non-throwing mode can return.\n */\ninterface ConvexPaginatedQueryInternalUser {\n readonly results: ReadonlyArray<unknown>;\n readonly status:\n | \"LoadingFirstPage\"\n | \"LoadingMore\"\n | \"CanLoadMore\"\n | \"Exhausted\"\n | \"Error\";\n readonly isLoading: boolean;\n readonly loadMore: (numItems: number) => void;\n readonly error?: unknown;\n}\n\ntype UseConvexPaginatedQueryInternal = (\n query: FunctionReference<\"query\">,\n args: Record<string, Value> | \"skip\",\n options: PaginatedQueryOptions,\n throwOnError: boolean,\n) => { user: ConvexPaginatedQueryInternalUser };\n\n// `usePaginatedQueryInternal` is runtime-exported by convex/react but absent\n// from its public type declarations. It is the only way to observe query\n// errors as values: the public positional `usePaginatedQuery` hard-codes\n// throwOnError and throws mid-hook-sequence, which cannot be caught without\n// breaking React's hook-order invariant.\nconst useConvexPaginatedQueryInternal = (\n ConvexReact as unknown as Record<string, unknown>\n).usePaginatedQueryInternal as UseConvexPaginatedQueryInternal | undefined;\n\nconst MINIMUM_CONVEX_VERSION = \"1.36.0\";\n\n/**\n * The non-throwing mode of `usePaginatedQueryInternal`—its fourth,\n * `throwOnError` parameter—arrived in convex 1.36.0. Convex 1.32 through\n * 1.35 export the same symbol taking only three parameters, where a fourth\n * argument is silently ignored and errors are always thrown.\n *\n * The function itself cannot be interrogated for this: `Function.length`\n * counts parameters up to the first one with a default, and 1.36.0 declares\n * `throwOnError = true`, so both shapes report an arity of 3. The package\n * version is the only reliable signal.\n */\nconst supportsErrorsAsValues = ((): boolean => {\n const [major, minor] = convexVersion.split(\".\").map(Number);\n if (\n major === undefined ||\n minor === undefined ||\n Number.isNaN(major) ||\n Number.isNaN(minor)\n ) {\n return false;\n }\n const [minimumMajor, minimumMinor] = MINIMUM_CONVEX_VERSION.split(\".\").map(\n Number,\n ) as [number, number];\n return (\n major > minimumMajor || (major === minimumMajor && minor >= minimumMinor)\n );\n})();\n\n/**\n * Load data reactively from a paginated query defined with\n * `FunctionSpec.publicPaginatedQuery`, mirroring the ergonomics of\n * `usePaginatedQuery` from `convex/react`.\n *\n * Args are encoded via the ref's user-args schema (`paginationOpts` is managed\n * by the Convex hook, not the caller), and each loaded page is decoded via the\n * ref's item schema.\n *\n * Returns a {@link PaginatedQueryResult.PaginatedQueryResult}: the loaded\n * variants carry `results` and `isLoading`, and `CanLoadMore` additionally\n * carries `loadMore`; if the `Ref` declares an `error` schema and the query\n * fails with that typed error, the decoded error is returned as the `Failure`\n * variant, which also carries the pages loaded before the failure. Unknown\n * errors are thrown, to be caught by an error boundary.\n */\nexport const usePaginatedQuery = <Query extends Ref.AnyPublicPaginatedQuery>(\n ref: Query,\n args: UsePaginatedQueryArgs<Query>,\n options: PaginatedQueryOptions,\n): PaginatedQueryResult.PaginatedQueryResult<\n PaginatedQueryItem<Query>,\n Ref.Error<Query>\n> => {\n if (\n useConvexPaginatedQueryInternal === undefined ||\n !supportsErrorsAsValues\n ) {\n throw new Error(\n `usePaginatedQuery requires convex >= ${MINIMUM_CONVEX_VERSION}, but found ` +\n `${convexVersion}. Earlier versions always throw paginated query errors ` +\n \"instead of returning them, so a declared `error` schema cannot be \" +\n \"surfaced as a `Failure`—upgrade the `convex` package.\",\n );\n }\n\n const functionReference = Ref.getFunctionReference(ref);\n const skipped = args === \"skip\";\n\n // The encoded output is the wire form Convex's hook forwards verbatim, not\n // the ref's decoded args type.\n const encodedArgs = useMemo(\n () =>\n args === \"skip\"\n ? (\"skip\" as const)\n : (Ref.encodePaginatedQueryArgsSync(\n ref,\n args as unknown as Omit<Ref.Args<Query>, \"paginationOpts\">,\n ) as Record<string, Value>),\n [ref, args],\n );\n\n const { user: convexResult } = useConvexPaginatedQueryInternal(\n functionReference,\n encodedArgs,\n options,\n false,\n );\n\n // The Convex hook carries the pages loaded so far on every status,\n // failures included, so results are decoded unconditionally.\n //\n // Decoding allocates fresh items, so key on the referentially stable\n // `results` the Convex hook provides—the same identity-preservation\n // rationale as in `useQuery` above.\n const { results: encodedResults } = convexResult;\n const decodedResults = useMemo(\n () => Ref.decodePaginationPageSync(ref, encodedResults),\n [ref, encodedResults],\n );\n\n const { status, loadMore } = convexResult;\n const error = status === \"Error\" ? convexResult.error : undefined;\n\n return useMemo(\n (): PaginatedQueryResult.Variants<\n PaginatedQueryItem<Query>,\n Ref.Error<Query>\n > =>\n // `status` is a bare string union rather than a tagged one, so the arms\n // match on literals.\n Match.value(status).pipe(\n Match.when(\"Error\", () => {\n if (Ref.isConvexError(error)) {\n const decoded = Ref.decodeErrorOption(ref, error.data);\n if (Option.isSome(decoded)) {\n return PaginatedQueryResult.failure({\n error: decoded.value,\n results: decodedResults,\n });\n }\n }\n // Unknown errors still throw. All hooks have run by this point, so\n // an aborted render here is hook-order-safe.\n throw error;\n }),\n Match.when(\"LoadingFirstPage\", () =>\n PaginatedQueryResult.loadingFirstPage({ skipped }),\n ),\n Match.when(\"LoadingMore\", () =>\n PaginatedQueryResult.loadingMore({ results: decodedResults }),\n ),\n // `CanLoadMore` is the only status whose `loadMore` does anything—the Convex hook returns an intentional no-op for all the others, so\n // they carry no callback at all.\n Match.when(\"CanLoadMore\", () =>\n PaginatedQueryResult.canLoadMore({\n results: decodedResults,\n loadMore,\n }),\n ),\n Match.when(\"Exhausted\", () =>\n PaginatedQueryResult.exhausted({ results: decodedResults }),\n ),\n Match.exhaustive,\n ),\n // The memo produces `Variants`, the conditional return type's superset—when `E` is `never` the `Failure` arm is unreachable at runtime, which\n // is exactly what the conditional encodes.\n [ref, skipped, decodedResults, status, loadMore, error],\n ) as PaginatedQueryResult.PaginatedQueryResult<\n PaginatedQueryItem<Query>,\n Ref.Error<Query>\n >;\n};\n\n/**\n * Whether a paginated query error means the stored cursors no longer match\n * the query (a data-dependent query changed underneath us), calling for a\n * full pagination reset rather than a failure.\n */\nconst isInvalidCursorError = (error: Error): boolean =>\n error.message.includes(\"InvalidCursor\") ||\n (error instanceof ConvexError &&\n typeof error.data === \"object\" &&\n error.data !== null &&\n // Both Convex's built-in pagination (which also sets\n // `isConvexSystemError`) and `QueryStream.paginate` signal an invalid\n // cursor with this data shape—the same check `convex/react` performs.\n (error.data as { paginationError?: unknown }).paginationError ===\n \"InvalidCursor\");\n\nconst NO_ITEMS: ReadonlyArray<unknown> = [];\n\n/**\n * EXPERIMENTAL—endCursor-pinned reactive pagination (see\n * `notes/stream-based-querying.md`). Use it with paginated queries whose\n * handlers paginate via `QueryStream.paginate`: those don't write the query\n * journal that {@link usePaginatedQuery}'s built-in reactivity relies on,\n * so gap-free pages must be maintained by the client instead. (It works\n * with any paginated query honoring the `endCursor` protocol field,\n * including the built-in `paginate`.)\n *\n * Each loaded page is pinned to a fixed index range by re-subscribing it\n * with its `continueCursor` echoed back as `endCursor`—pages then grow\n * and shrink reactively but always meet exactly, and a page that outgrows\n * `initialNumItems` is split in two. This is the mechanism of\n * `convex-helpers/react`'s `usePaginatedQuery`, re-expressed over the pure\n * {@link StreamPagination} state machine, with args/items/errors codec'd\n * through the ref's schemas exactly like {@link usePaginatedQuery}.\n */\nexport const useStreamPaginatedQuery = <\n Query extends Ref.AnyPublicPaginatedQuery,\n>(\n ref: Query,\n args: UsePaginatedQueryArgs<Query>,\n options: {\n readonly initialNumItems: number;\n /**\n * Per-page read budgets forwarded as `paginationOpts.maximumRowsRead`\n * and `paginationOpts.maximumBytesRead`: a page that would scan more\n * rows, or read more bytes, than these returns truncated with\n * `SplitRequired` (and the hook splits it) instead of exceeding\n * Convex's query limits on a filter-heavy stream.\n */\n readonly maximumRowsRead?: number;\n readonly maximumBytesRead?: number;\n },\n): PaginatedQueryResult.PaginatedQueryResult<\n PaginatedQueryItem<Query>,\n Ref.Error<Query>\n> => {\n // `useQueries` requires a *referentially stable* queries object while\n // nothing has changed: its subscription memo keys on identity, and its\n // `useSubscription` re-runs a render-phase state update whenever the\n // subscription changes—an unstable input loops the render. Callers\n // typically pass a fresh `args` literal each render, so everything that\n // feeds the queries object is stabilized by *value* here: the function\n // reference by `ref`, and the encoded args by their serialized form (as\n // `convex/react`'s own paginated hook does).\n const functionReference = useMemo(() => Ref.getFunctionReference(ref), [ref]);\n const skipped = args === \"skip\";\n\n const rawEncodedArgs =\n args === \"skip\"\n ? undefined\n : (Ref.encodePaginatedQueryArgsSync(\n ref,\n args as unknown as Omit<Ref.Args<Query>, \"paginationOpts\">,\n ) as Record<string, Value>);\n const encodedArgsKey =\n rawEncodedArgs === undefined\n ? \"skip\"\n : JSON.stringify(convexToJson(rawEncodedArgs));\n const encodedArgs = useMemo(\n () => rawEncodedArgs,\n // The serialized form stands in for the freshly allocated object.\n [ref, encodedArgsKey],\n );\n\n // A change of query, args, skippedness, or page size restarts pagination\n // from scratch.\n const resetKey = useMemo(\n () =>\n JSON.stringify([\n getFunctionName(functionReference),\n encodedArgsKey,\n options.initialNumItems,\n options.maximumRowsRead ?? null,\n options.maximumBytesRead ?? null,\n ]),\n [\n functionReference,\n encodedArgsKey,\n options.initialNumItems,\n options.maximumRowsRead,\n options.maximumBytesRead,\n ],\n );\n\n const freshState = () =>\n skipped\n ? StreamPagination.empty\n : StreamPagination.initial(options.initialNumItems, options);\n\n const [tracked, setTracked] = useState(() => ({\n resetKey,\n state: freshState(),\n }));\n // Render-phase reset—the React-sanctioned derived-state-from-props\n // pattern, also how `convex/react`'s own paginated hook resets.\n let current = tracked;\n if (current.resetKey !== resetKey) {\n current = { resetKey, state: freshState() };\n setTracked(current);\n }\n\n const applyTransitions = useCallback(\n (\n transitions: ReadonlyArray<\n (state: StreamPagination.State) => StreamPagination.State\n >,\n ) =>\n setTracked((previous) => ({\n resetKey: previous.resetKey,\n state: transitions.reduce(\n (state, transition) => transition(state),\n previous.state,\n ),\n })),\n [],\n );\n\n const queries = useMemo(\n () =>\n StreamPagination.pageRequests(current.state, (page) => ({\n query: functionReference,\n args: { ...encodedArgs, paginationOpts: page },\n })),\n [current.state, functionReference, encodedArgs],\n );\n\n const resultsObject = useConvexQueries(\n queries as unknown as Parameters<typeof useConvexQueries>[0],\n );\n\n const interpretation = useMemo(\n () =>\n StreamPagination.interpret(\n current.state,\n resultsObject as StreamPagination.Results,\n { initialNumItems: options.initialNumItems, isInvalidCursorError },\n ),\n [current.state, resultsObject, options.initialNumItems],\n );\n\n // Apply the transitions this render discovered (completed split swaps,\n // new splits of overgrown pages) or restart after an invalid cursor—render-phase state updates, as in `convex-helpers`' hook. Both settle:\n // the updated state no longer produces the same discovery.\n if (interpretation._tag === \"ResetRequired\") {\n setTracked((previous) => ({\n resetKey: previous.resetKey,\n state: freshState(),\n }));\n } else if (\n interpretation._tag === \"Interpreted\" &&\n interpretation.transitions.length > 0\n ) {\n applyTransitions(interpretation.transitions);\n }\n\n const encodedItems =\n interpretation._tag === \"ResetRequired\" ? NO_ITEMS : interpretation.items;\n // Page results keep their identity while unchanged (only the page that\n // actually updated is a fresh object), so caching decodes per encoded\n // item makes a single-page update decode only that page's items rather\n // than every loaded page's.\n const decodeCache = useMemo(\n () => new WeakMap<object, PaginatedQueryItem<Query>>(),\n [ref],\n );\n const decodedResults = useMemo(\n () =>\n encodedItems.map((item): PaginatedQueryItem<Query> => {\n if (typeof item !== \"object\" || item === null) {\n return Ref.decodePaginationPageSync(ref, [\n item,\n ])[0] as PaginatedQueryItem<Query>;\n }\n const cached = decodeCache.get(item);\n if (cached !== undefined) {\n return cached;\n }\n const decoded = Ref.decodePaginationPageSync(ref, [\n item,\n ])[0] as PaginatedQueryItem<Query>;\n decodeCache.set(item, decoded);\n return decoded;\n }),\n [ref, encodedItems, decodeCache],\n );\n\n return useMemo((): PaginatedQueryResult.Variants<\n PaginatedQueryItem<Query>,\n Ref.Error<Query>\n > => {\n if (interpretation._tag === \"ResetRequired\") {\n return PaginatedQueryResult.loadingFirstPage({ skipped });\n }\n if (interpretation._tag === \"Failed\") {\n const error = interpretation.error;\n if (Ref.isConvexError(error)) {\n const decoded = Ref.decodeErrorOption(ref, error.data);\n if (Option.isSome(decoded)) {\n return PaginatedQueryResult.failure({\n error: decoded.value,\n results: decodedResults,\n });\n }\n }\n // Unknown errors still throw, to be caught by an error boundary.\n throw error;\n }\n\n const { lastResult } = interpretation;\n if (Option.isNone(lastResult) && current.state.pageKeys.length <= 1) {\n return PaginatedQueryResult.loadingFirstPage({ skipped });\n }\n if (\n Option.isNone(lastResult) ||\n StreamPagination.isLastPageSplitting(current.state)\n ) {\n return PaginatedQueryResult.loadingMore({ results: decodedResults });\n }\n if (lastResult.value.isDone) {\n return PaginatedQueryResult.exhausted({ results: decodedResults });\n }\n\n const continueCursor = lastResult.value.continueCursor;\n // A per-result guard, as in `convex-helpers`: calling `loadMore`\n // repeatedly before the next render is a single load.\n let alreadyLoadingMore = false;\n return PaginatedQueryResult.canLoadMore({\n results: decodedResults,\n loadMore: (numItems: number) => {\n if (!alreadyLoadingMore) {\n alreadyLoadingMore = true;\n applyTransitions([\n StreamPagination.loadMore(continueCursor, numItems, options),\n ]);\n }\n },\n });\n }, [\n interpretation,\n decodedResults,\n current.state,\n skipped,\n ref,\n applyTransitions,\n ]) as PaginatedQueryResult.PaginatedQueryResult<\n PaginatedQueryItem<Query>,\n Ref.Error<Query>\n >;\n};\n\n/**\n * An optimistic update for a Confect mutation. Mirrors Convex's\n * `OptimisticUpdate`, but receives a Confect {@link OptimisticLocalStore} and\n * the decoded mutation `args`.\n */\nexport type OptimisticUpdate<Mutation extends Ref.AnyPublicMutation> = (\n localStore: OptimisticLocalStore.OptimisticLocalStore,\n args: Ref.Args<Mutation>,\n) => void;\n\n/**\n * The handle returned by {@link useMutation}. It is callable like the function\n * returned by Convex's `useMutation`, and additionally exposes\n * `withOptimisticUpdate` for attaching an optimistic update. Mirrors the\n * `ReactMutation` type from `convex/react`.\n */\nexport interface ReactMutation<Mutation extends Ref.AnyPublicMutation> {\n (...args: Ref.OptionalArgs<Mutation>): InvokeReturn<Mutation>;\n withOptimisticUpdate(\n optimisticUpdate: OptimisticUpdate<Mutation>,\n ): ReactMutation<Mutation>;\n}\n\nconst makeReactMutation = <Mutation extends Ref.AnyPublicMutation>(\n ref: Mutation,\n convexReactMutation: ConvexReactMutation<\n Ref.FunctionReference<Mutation> & FunctionReference<\"mutation\">\n >,\n): ReactMutation<Mutation> => {\n const callable = ((...args: Ref.OptionalArgs<Mutation>) =>\n invokeAsResult(\n ref,\n (_, encodedArgs) => convexReactMutation(encodedArgs as never),\n args,\n ).then((result) =>\n Ref.hasErrorSchema(ref) ? result : Result.getOrThrow(result),\n )) as (...args: Ref.OptionalArgs<Mutation>) => InvokeReturn<Mutation>;\n\n const withOptimisticUpdate = (\n optimisticUpdate: OptimisticUpdate<Mutation>,\n ): ReactMutation<Mutation> => {\n const wrappedUpdate: ConvexOptimisticUpdate<Record<string, Value>> = (\n convexLocalStore,\n encodedArgs,\n ) => {\n const decodedArgs = Ref.decodeArgsSync(ref, encodedArgs);\n optimisticUpdate(\n OptimisticLocalStore.make(convexLocalStore),\n decodedArgs,\n );\n };\n const nextConvexReactMutation =\n convexReactMutation.withOptimisticUpdate(wrappedUpdate);\n return makeReactMutation(ref, nextConvexReactMutation);\n };\n\n return Object.assign(callable, { withOptimisticUpdate });\n};\n\n/**\n * Returns a {@link ReactMutation} handle for the provided `Ref`'s mutation. The\n * handle is callable to invoke the mutation, and exposes `withOptimisticUpdate`\n * for attaching an optimistic update, mirroring `useMutation` from\n * `convex/react`.\n *\n * If the `Ref` declares an `error` schema, the returned promise resolves to a\n * `Result` with the decoded `returns` value in the `Success` and the decoded\n * error in the `Failure`.\n *\n * If the `Ref` does not declare an `error` schema, the promise resolves\n * directly to the decoded `returns` value, matching the behavior of\n * `useMutation` from `convex/react`.\n *\n * Any other failure rejects the promise.\n */\nexport const useMutation = <Mutation extends Ref.AnyPublicMutation>(\n ref: Mutation,\n): ReactMutation<Mutation> => {\n const functionReference = Ref.getFunctionReference(ref);\n const convexReactMutation = useConvexMutation(functionReference);\n\n return useMemo(\n () =>\n makeReactMutation(\n ref,\n convexReactMutation as ConvexReactMutation<\n Ref.FunctionReference<Mutation> & FunctionReference<\"mutation\">\n >,\n ),\n [ref, convexReactMutation],\n );\n};\n\n/**\n * Returns a function that invokes the provided `Ref`'s action.\n *\n * If the `Ref` declares an `error` schema, the returned promise resolves to a\n * `Result` with the decoded `returns` value in the `Success` and the decoded\n * error in the `Failure`.\n *\n * If the `Ref` does not declare an `error` schema, the promise resolves\n * directly to the decoded `returns` value, matching the behavior of\n * `useMutation` from `convex/react`.\n *\n * Any other failure rejects the promise.\n */\nexport const useAction = <Action extends Ref.AnyPublicAction>(\n ref: Action,\n): ((...args: Ref.OptionalArgs<Action>) => InvokeReturn<Action>) => {\n const functionReference = Ref.getFunctionReference(ref);\n const actualAction = useConvexAction(functionReference);\n\n return useCallback(\n ((...args: Ref.OptionalArgs<Action>) =>\n invokeAsResult(\n ref,\n (_, encodedArgs) => actualAction(encodedArgs),\n args,\n ).then((result) =>\n Ref.hasErrorSchema(ref) ? result : Result.getOrThrow(result),\n )) as (...args: Ref.OptionalArgs<Action>) => InvokeReturn<Action>,\n [ref, actualAction],\n );\n};\n\nconst invokeAsResult = <Ref_ extends Ref.Any>(\n ref: Ref_,\n invoke: (\n fnRef: Ref.FunctionReference<Ref_>,\n encodedArgs: unknown,\n ) => PromiseLike<unknown>,\n args: Ref.OptionalArgs<Ref_>,\n): Promise<Result.Result<Ref.Returns<Ref_>, Ref.Error<Ref_>>> => {\n const exitPromise = Effect.runPromiseExit(\n Ref.runWithCodec(ref, (args[0] ?? {}) as Ref.Args<Ref_>, invoke).pipe(\n Effect.catchTag(\"SchemaError\", Effect.die),\n Effect.result,\n ),\n );\n return exitPromise.then((exit) => {\n if (Exit.isSuccess(exit)) return exit.value;\n throw Cause.squash(exit.cause);\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AA6CA,MAAa,YACX,KACA,GAAG,SAC+D;CAClE,MAAM,oBAAoB,IAAI,qBAAqB,GAAG;CACtD,MAAM,OAAO,KAAK;CAClB,MAAM,UAAU,SAAS;CACzB,MAAM,cAAc,UAChB,SACA,IAAI,eAAe,KAAM,QAAQ,CAAC,CAAqB;CAS3D,MAAM,wBAAyD,OAAO,UAC9DA,WAAe,mBAAmB,WAAW,CACrD;CAEA,OAAO,cAEH,OAAO,MAAM,uBAAuB;EAClC,YAAY,8BACV,8BAA8B,KAAA,IAC1BC,KAAiB,OAAO,IACxBC,QACE,IAAI,kBAAkB,KAAK,yBAAyB,CACtD;EACN,YAAY,UAAU;GACpB,IAAI,IAAI,cAAc,KAAK,GAAG;IAC5B,MAAM,UAAU,IAAI,kBAAkB,KAAK,MAAM,IAAI;IACrD,IAAI,OAAO,OAAO,OAAO,GACvB,OAAOC,KAAiB,QAAQ,KAAK;GAEzC;GACA,MAAM;EACR;CACF,CAAC,GAKH;EAAC;EAAK;EAAS,OAAO,MAAM,qBAAqB;CAAC,CACpD;AACF;AAwEA,MAAM,kCACJ,YACA;AAEF,MAAM,yBAAyB;;;;;;;;;;;;AAa/B,MAAM,gCAAyC;CAC7C,MAAM,CAAC,OAAO,SAASC,QAAc,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CAC1D,IACE,UAAU,KAAA,KACV,UAAU,KAAA,KACV,OAAO,MAAM,KAAK,KAClB,OAAO,MAAM,KAAK,GAElB,OAAO;CAET,MAAM,CAAC,cAAc,gBAAgB,uBAAuB,MAAM,GAAG,CAAC,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KACA,mBAGF,GACF,CAAC,KAAK,mBAAmB,CAC3B;AACF;;;;;;;;;;;;;;AAeA,MAAa,aACX,QACkE;CAClE,MAAM,oBAAoB,IAAI,qBAAqB,GAAG;CACtD,MAAM,eAAeC,YAAgB,iBAAiB;CAEtD,OAAO,cACH,GAAG,SACH,eACE,MACC,GAAG,gBAAgB,aAAa,WAAW,GAC5C,IACF,CAAC,CAAC,MAAM,WACN,IAAI,eAAe,GAAG,IAAI,SAAS,OAAO,WAAW,MAAM,CAC7D,IACF,CAAC,KAAK,YAAY,CACpB;AACF;AAEA,MAAM,kBACJ,KACA,QAIA,SAC+D;CAO/D,OANoB,OAAO,eACzB,IAAI,aAAa,KAAM,KAAK,MAAM,CAAC,GAAsB,MAAM,CAAC,CAAC,KAC/D,OAAO,SAAS,eAAe,OAAO,GAAG,GACzC,OAAO,MACT,CAEe,CAAC,CAAC,MAAM,SAAS;EAChC,IAAI,KAAK,UAAU,IAAI,GAAG,OAAO,KAAK;EACtC,MAAM,MAAM,OAAO,KAAK,KAAK;CAC/B,CAAC;AACH"}
|
package/package.json
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@confect/react",
|
|
3
3
|
"description": "Client-side bindings for React apps",
|
|
4
|
-
"version": "10.0.0-next.
|
|
4
|
+
"version": "10.0.0-next.22",
|
|
5
5
|
"author": "RJ Dellecese",
|
|
6
6
|
"bugs": {
|
|
7
7
|
"url": "https://github.com/rjdellecese/confect/issues"
|
|
8
8
|
},
|
|
9
9
|
"devDependencies": {
|
|
10
|
-
"@effect/vitest": "4.0.0-rc.
|
|
11
|
-
"@testing-library/react": "16.3.
|
|
12
|
-
"@types/node": "
|
|
13
|
-
"@types/react": "19.
|
|
14
|
-
"@types/react-dom": "19.
|
|
10
|
+
"@effect/vitest": "4.0.0-rc.115",
|
|
11
|
+
"@testing-library/react": "16.3.3",
|
|
12
|
+
"@types/node": "24.13.3",
|
|
13
|
+
"@types/react": "19.3.0",
|
|
14
|
+
"@types/react-dom": "19.3.0",
|
|
15
15
|
"convex": "1.45.0",
|
|
16
|
-
"effect": "4.0.0-rc.
|
|
17
|
-
"happy-dom": "20.
|
|
18
|
-
"react": "19.
|
|
19
|
-
"react-dom": "19.
|
|
20
|
-
"tsdown": "0.
|
|
16
|
+
"effect": "4.0.0-rc.115",
|
|
17
|
+
"happy-dom": "20.14.3",
|
|
18
|
+
"react": "19.3.0",
|
|
19
|
+
"react-dom": "19.3.0",
|
|
20
|
+
"tsdown": "0.23.0",
|
|
21
21
|
"typescript": "7.0.2",
|
|
22
22
|
"unrun": "0.3.1",
|
|
23
|
-
"vite": "8.2.
|
|
24
|
-
"vitest": "
|
|
23
|
+
"vite": "8.2.2",
|
|
24
|
+
"vitest": "5.0.0"
|
|
25
25
|
},
|
|
26
26
|
"engines": {
|
|
27
|
-
"node": ">=
|
|
27
|
+
"node": ">=24"
|
|
28
28
|
},
|
|
29
29
|
"exports": {
|
|
30
30
|
".": {
|
|
@@ -56,10 +56,10 @@
|
|
|
56
56
|
"main": "./dist/index.js",
|
|
57
57
|
"module": "./dist/index.js",
|
|
58
58
|
"peerDependencies": {
|
|
59
|
+
"@confect/core": "^10.0.0-next.22",
|
|
59
60
|
"convex": "^1.36.0",
|
|
60
|
-
"effect": "^4.0.0-rc.
|
|
61
|
-
"react": "^18.0.0 || ^19.0.0"
|
|
62
|
-
"@confect/core": "^10.0.0-next.20"
|
|
61
|
+
"effect": "^4.0.0-rc.115",
|
|
62
|
+
"react": "^18.0.0 || ^19.0.0"
|
|
63
63
|
},
|
|
64
64
|
"repository": {
|
|
65
65
|
"type": "git",
|
|
@@ -12,7 +12,7 @@ type TypeId = typeof TypeId;
|
|
|
12
12
|
* A `PaginatedQueryResult` represents the result of a Confect paginated query.
|
|
13
13
|
* The non-`Failure` variants mirror the statuses of `usePaginatedQuery` from
|
|
14
14
|
* `convex/react` and all carry `results` and `isLoading`, so the common UI
|
|
15
|
-
* shape
|
|
15
|
+
* shape—render the list, show a spinner while loading—needs only an
|
|
16
16
|
* {@link isFailure} early-out and plain field access.
|
|
17
17
|
*
|
|
18
18
|
* Every variant carries `results`, including `Failure`: when a later page
|
|
@@ -23,8 +23,8 @@ type TypeId = typeof TypeId;
|
|
|
23
23
|
* `loadMore` appears only on `CanLoadMore`, the one state it can make
|
|
24
24
|
* progress from. The underlying Convex hook exposes it on every status, but
|
|
25
25
|
* calling it while a page is in flight, once the list is exhausted, or after
|
|
26
|
-
* a failure is an intentional no-op there; narrowing to `CanLoadMore
|
|
27
|
-
* {@link isCanLoadMore} or {@link match}
|
|
26
|
+
* a failure is an intentional no-op there; narrowing to `CanLoadMore`—via
|
|
27
|
+
* {@link isCanLoadMore} or {@link match}—makes that statically apparent
|
|
28
28
|
* instead of silently dropping the call.
|
|
29
29
|
*
|
|
30
30
|
* When the query declares no `error` schema (`E` is `never`), the `Failure`
|
|
@@ -48,7 +48,7 @@ export type PaginatedQueryResult<Item, E = never> = [E] extends [never]
|
|
|
48
48
|
| Failure<Item, E>;
|
|
49
49
|
|
|
50
50
|
/**
|
|
51
|
-
* Every variant regardless of `E
|
|
51
|
+
* Every variant regardless of `E`—the parameter type for guards and
|
|
52
52
|
* {@link match}, since `PaginatedQueryResult` itself excludes `Failure` when
|
|
53
53
|
* `E` is `never`.
|
|
54
54
|
*/
|
|
@@ -60,7 +60,7 @@ export type Variants<Item, E = never> =
|
|
|
60
60
|
| Failure<Item, E>;
|
|
61
61
|
|
|
62
62
|
export declare namespace PaginatedQueryResult {
|
|
63
|
-
// eslint-disable-next-line @typescript-eslint/no-shadow
|
|
63
|
+
// eslint-disable-next-line @typescript-eslint/no-shadow
|
|
64
64
|
export interface Proto<out Item, out E> extends Pipeable.Pipeable {
|
|
65
65
|
readonly [TypeId]: TypeId;
|
|
66
66
|
readonly "~Item": Item;
|
package/src/QueryResult.ts
CHANGED
|
@@ -20,7 +20,6 @@ export type QueryResult<A, E = never> =
|
|
|
20
20
|
| Failure<A, E>;
|
|
21
21
|
|
|
22
22
|
export declare namespace QueryResult {
|
|
23
|
-
// eslint-disable-next-line import/namespace -- oxlint's namespace resolution misses type-only exports, and `Pipeable` is an interface
|
|
24
23
|
export interface Proto<out A, out E> extends Pipeable.Pipeable {
|
|
25
24
|
readonly [TypeId]: TypeId;
|
|
26
25
|
readonly "~A": A;
|
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* EXPERIMENTAL—the pure state machine behind {@link useStreamPaginatedQuery}
|
|
3
|
+
* (see `notes/stream-based-querying.md` in the repo root).
|
|
4
|
+
*
|
|
5
|
+
* Reactive pagination without the query journal: every loaded page—including the first—is pinned to a fixed index range by echoing its
|
|
6
|
+
* `continueCursor` back as the next subscription's `endCursor` (the last
|
|
7
|
+
* page pins to the end-of-stream sentinel once exhausted), so adjacent
|
|
8
|
+
* pages stay exactly contiguous and pages never shed items as data changes—the "range-defined pages" the Fully Reactive Pagination article calls
|
|
9
|
+
* for, and the mechanism of `convex-helpers/react`'s `usePaginatedQuery`.
|
|
10
|
+
*
|
|
11
|
+
* Pinning a freshly loaded page, loading more, and splitting an overgrown
|
|
12
|
+
* page are the same transition shape: the affected page keeps rendering
|
|
13
|
+
* while its replacement subscriptions ("ongoing split") load, and is
|
|
14
|
+
* swapped out once all of them have results.
|
|
15
|
+
*
|
|
16
|
+
* This module is framework-free (it imports only `effect/*` and a type
|
|
17
|
+
* from `convex/server`); it lives here for now because the React hook is
|
|
18
|
+
* its only consumer—a second client (e.g. `@confect/foldkit`) should
|
|
19
|
+
* prompt a move down to `@confect/js`.
|
|
20
|
+
*/
|
|
21
|
+
import type { PaginationResult } from "convex/server";
|
|
22
|
+
import * as Array from "effect/Array";
|
|
23
|
+
import * as Option from "effect/Option";
|
|
24
|
+
import { pipe } from "effect/Function";
|
|
25
|
+
import * as Record from "effect/Record";
|
|
26
|
+
|
|
27
|
+
/** The `paginationOpts` one subscribed page queries with. */
|
|
28
|
+
export interface PageRequest {
|
|
29
|
+
readonly numItems: number;
|
|
30
|
+
readonly cursor: string | null;
|
|
31
|
+
/** Present once the page is pinned to a fixed range. */
|
|
32
|
+
readonly endCursor?: string;
|
|
33
|
+
/**
|
|
34
|
+
* Per-page read budgets, forwarded to the server so a scan-heavy page
|
|
35
|
+
* fails over to `SplitRequired` instead of exceeding query limits.
|
|
36
|
+
*/
|
|
37
|
+
readonly maximumRowsRead?: number;
|
|
38
|
+
readonly maximumBytesRead?: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The per-page read budgets every growing page is requested with. */
|
|
42
|
+
export interface ReadBudget {
|
|
43
|
+
readonly maximumRowsRead?: number | undefined;
|
|
44
|
+
readonly maximumBytesRead?: number | undefined;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A fresh growing-page request (no `endCursor`). */
|
|
48
|
+
const growingRequest = (
|
|
49
|
+
numItems: number,
|
|
50
|
+
cursor: string | null,
|
|
51
|
+
budget: ReadBudget,
|
|
52
|
+
): PageRequest => ({
|
|
53
|
+
numItems,
|
|
54
|
+
cursor,
|
|
55
|
+
...(budget.maximumRowsRead === undefined
|
|
56
|
+
? {}
|
|
57
|
+
: { maximumRowsRead: budget.maximumRowsRead }),
|
|
58
|
+
...(budget.maximumBytesRead === undefined
|
|
59
|
+
? {}
|
|
60
|
+
: { maximumBytesRead: budget.maximumBytesRead }),
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
export interface State {
|
|
64
|
+
readonly nextPageKey: number;
|
|
65
|
+
/** Page keys in display order. */
|
|
66
|
+
readonly pageKeys: ReadonlyArray<string>;
|
|
67
|
+
/** The request each subscribed page queries with, by page key. */
|
|
68
|
+
readonly pages: Record.ReadonlyRecord<string, PageRequest>;
|
|
69
|
+
/**
|
|
70
|
+
* Pages being replaced by one (a pin) or two (a split) narrower
|
|
71
|
+
* subscriptions: the original stays subscribed (and rendered) until every
|
|
72
|
+
* replacement has a result.
|
|
73
|
+
*/
|
|
74
|
+
readonly ongoingSplits: Record.ReadonlyRecord<string, ReadonlyArray<string>>;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The skipped state: nothing subscribed. */
|
|
78
|
+
export const empty: State = {
|
|
79
|
+
nextPageKey: 0,
|
|
80
|
+
pageKeys: [],
|
|
81
|
+
pages: Record.empty(),
|
|
82
|
+
ongoingSplits: Record.empty(),
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
/** One growing (unpinned) page from the start of the stream. */
|
|
86
|
+
export const initial = (
|
|
87
|
+
initialNumItems: number,
|
|
88
|
+
budget: ReadBudget = {},
|
|
89
|
+
): State => ({
|
|
90
|
+
nextPageKey: 1,
|
|
91
|
+
pageKeys: ["0"],
|
|
92
|
+
pages: Record.singleton("0", growingRequest(initialNumItems, null, budget)),
|
|
93
|
+
ongoingSplits: Record.empty(),
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Pin a freshly loaded growing page at its `continueCursor` (or, once
|
|
98
|
+
* exhausted, at the end-of-stream sentinel), so it stops being a sliding
|
|
99
|
+
* window: a pinned page grows and shrinks with the data in its range but
|
|
100
|
+
* never sheds items past its edges. Modeled as a one-replacement split so
|
|
101
|
+
* the original keeps rendering until the pinned twin has a result.
|
|
102
|
+
*/
|
|
103
|
+
export const pin =
|
|
104
|
+
(key: string, endCursor: string): ((state: State) => State) =>
|
|
105
|
+
(state) =>
|
|
106
|
+
Option.match(Record.get(state.pages, key), {
|
|
107
|
+
onNone: () => state,
|
|
108
|
+
onSome: (page) => {
|
|
109
|
+
if (
|
|
110
|
+
page.endCursor !== undefined ||
|
|
111
|
+
Record.has(state.ongoingSplits, key)
|
|
112
|
+
) {
|
|
113
|
+
return state;
|
|
114
|
+
}
|
|
115
|
+
const pinnedKey = String(state.nextPageKey);
|
|
116
|
+
return {
|
|
117
|
+
nextPageKey: state.nextPageKey + 1,
|
|
118
|
+
pageKeys: state.pageKeys,
|
|
119
|
+
pages: Record.set(state.pages, pinnedKey, { ...page, endCursor }),
|
|
120
|
+
ongoingSplits: Record.set(state.ongoingSplits, key, [pinnedKey]),
|
|
121
|
+
};
|
|
122
|
+
},
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Pin the growing last page at `continueCursor` and start a new growing
|
|
127
|
+
* page from there. Modeled as a split of the last page into its pinned
|
|
128
|
+
* replacement and the new page, so the swap waits for both.
|
|
129
|
+
*/
|
|
130
|
+
export const loadMore =
|
|
131
|
+
(
|
|
132
|
+
continueCursor: string,
|
|
133
|
+
numItems: number,
|
|
134
|
+
budget: ReadBudget = {},
|
|
135
|
+
): ((state: State) => State) =>
|
|
136
|
+
(state) =>
|
|
137
|
+
pipe(
|
|
138
|
+
Option.Do,
|
|
139
|
+
Option.bind("lastKey", () => Array.last(state.pageKeys)),
|
|
140
|
+
Option.bind("lastPage", ({ lastKey }) =>
|
|
141
|
+
Record.get(state.pages, lastKey),
|
|
142
|
+
),
|
|
143
|
+
Option.match({
|
|
144
|
+
onNone: () => state,
|
|
145
|
+
onSome: ({ lastKey, lastPage }) => {
|
|
146
|
+
if (lastPage.endCursor !== undefined) {
|
|
147
|
+
// The last page is already pinned (the usual case, since pages
|
|
148
|
+
// pin themselves on first load): just append a new growing page.
|
|
149
|
+
const nextKey = String(state.nextPageKey);
|
|
150
|
+
return {
|
|
151
|
+
nextPageKey: state.nextPageKey + 1,
|
|
152
|
+
pageKeys: Array.append(state.pageKeys, nextKey),
|
|
153
|
+
pages: Record.set(
|
|
154
|
+
state.pages,
|
|
155
|
+
nextKey,
|
|
156
|
+
growingRequest(numItems, continueCursor, budget),
|
|
157
|
+
),
|
|
158
|
+
ongoingSplits: state.ongoingSplits,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
const pinnedKey = String(state.nextPageKey);
|
|
162
|
+
const nextKey = String(state.nextPageKey + 1);
|
|
163
|
+
return {
|
|
164
|
+
nextPageKey: state.nextPageKey + 2,
|
|
165
|
+
pageKeys: state.pageKeys,
|
|
166
|
+
pages: pipe(
|
|
167
|
+
state.pages,
|
|
168
|
+
Record.set(pinnedKey, { ...lastPage, endCursor: continueCursor }),
|
|
169
|
+
Record.set(
|
|
170
|
+
nextKey,
|
|
171
|
+
growingRequest(numItems, continueCursor, budget),
|
|
172
|
+
),
|
|
173
|
+
),
|
|
174
|
+
ongoingSplits: Record.set(state.ongoingSplits, lastKey, [
|
|
175
|
+
pinnedKey,
|
|
176
|
+
nextKey,
|
|
177
|
+
]),
|
|
178
|
+
};
|
|
179
|
+
},
|
|
180
|
+
}),
|
|
181
|
+
);
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Split the page at `key` in two at `splitCursor`. The first replacement
|
|
185
|
+
* pins at the split point; the second keeps the page's own `endCursor`—for a pinned page its original end (so a truncated `SplitRequired` page
|
|
186
|
+
* loses none of its range), and for a growing page no end at all (it keeps
|
|
187
|
+
* growing).
|
|
188
|
+
*/
|
|
189
|
+
export const split =
|
|
190
|
+
(key: string, splitCursor: string): ((state: State) => State) =>
|
|
191
|
+
(state) =>
|
|
192
|
+
Option.match(Record.get(state.pages, key), {
|
|
193
|
+
onNone: () => state,
|
|
194
|
+
onSome: (page) => {
|
|
195
|
+
const firstKey = String(state.nextPageKey);
|
|
196
|
+
const secondKey = String(state.nextPageKey + 1);
|
|
197
|
+
return {
|
|
198
|
+
nextPageKey: state.nextPageKey + 2,
|
|
199
|
+
pageKeys: state.pageKeys,
|
|
200
|
+
pages: pipe(
|
|
201
|
+
state.pages,
|
|
202
|
+
Record.set(firstKey, { ...page, endCursor: splitCursor }),
|
|
203
|
+
Record.set(secondKey, { ...page, cursor: splitCursor }),
|
|
204
|
+
),
|
|
205
|
+
ongoingSplits: Record.set(state.ongoingSplits, key, [
|
|
206
|
+
firstKey,
|
|
207
|
+
secondKey,
|
|
208
|
+
]),
|
|
209
|
+
};
|
|
210
|
+
},
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
/** Swap a completed split's replacements in for the original page. */
|
|
214
|
+
export const completeSplit =
|
|
215
|
+
(key: string): ((state: State) => State) =>
|
|
216
|
+
(state) =>
|
|
217
|
+
Option.match(Record.get(state.ongoingSplits, key), {
|
|
218
|
+
onNone: () => state,
|
|
219
|
+
onSome: (replacements) => ({
|
|
220
|
+
nextPageKey: state.nextPageKey,
|
|
221
|
+
pageKeys: Array.flatMap(state.pageKeys, (pageKey) =>
|
|
222
|
+
pageKey === key ? replacements : [pageKey],
|
|
223
|
+
),
|
|
224
|
+
pages: Record.remove(state.pages, key),
|
|
225
|
+
ongoingSplits: Record.remove(state.ongoingSplits, key),
|
|
226
|
+
}),
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
/** Whether the last (rendered) page is currently being split or pinned. */
|
|
230
|
+
export const isLastPageSplitting = (state: State): boolean =>
|
|
231
|
+
Option.exists(Array.last(state.pageKeys), (lastKey) =>
|
|
232
|
+
Record.has(state.ongoingSplits, lastKey),
|
|
233
|
+
);
|
|
234
|
+
|
|
235
|
+
/** Build one subscription request per subscribed page. */
|
|
236
|
+
export const pageRequests = <A>(
|
|
237
|
+
state: State,
|
|
238
|
+
f: (page: PageRequest) => A,
|
|
239
|
+
): Record.ReadonlyRecord<string, A> => Record.map(state.pages, f);
|
|
240
|
+
|
|
241
|
+
/** The per-page results a render observes, keyed like {@link pageRequests}. */
|
|
242
|
+
export type Results = Record.ReadonlyRecord<
|
|
243
|
+
string,
|
|
244
|
+
PageResult | Error | undefined
|
|
245
|
+
>;
|
|
246
|
+
|
|
247
|
+
// -----------------------------------------------------------------------------
|
|
248
|
+
// Interpretation
|
|
249
|
+
// -----------------------------------------------------------------------------
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* The wire shape of one loaded page—`PaginationResult` from
|
|
253
|
+
* `convex/server`, so the protocol has a single source of truth.
|
|
254
|
+
*/
|
|
255
|
+
export type PageResult = PaginationResult<unknown>;
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* What one render pass derives from the subscribed pages' results: the
|
|
259
|
+
* items to show, the trailing complete result (absent while the tail is
|
|
260
|
+
* loading or force-splitting), state transitions to apply, and whether a
|
|
261
|
+
* failure or an invalid cursor was hit.
|
|
262
|
+
*/
|
|
263
|
+
export type Interpretation =
|
|
264
|
+
| { readonly _tag: "ResetRequired" }
|
|
265
|
+
| {
|
|
266
|
+
readonly _tag: "Failed";
|
|
267
|
+
readonly error: unknown;
|
|
268
|
+
/** Encoded items loaded before the failing page. */
|
|
269
|
+
readonly items: ReadonlyArray<unknown>;
|
|
270
|
+
}
|
|
271
|
+
| {
|
|
272
|
+
readonly _tag: "Interpreted";
|
|
273
|
+
/** Encoded items across the loaded pages, in order. */
|
|
274
|
+
readonly items: ReadonlyArray<unknown>;
|
|
275
|
+
/** The last page's result, when every page has loaded completely. */
|
|
276
|
+
readonly lastResult: Option.Option<PageResult>;
|
|
277
|
+
/** Split/swap transitions this render discovered. */
|
|
278
|
+
readonly transitions: ReadonlyArray<(state: State) => State>;
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
const interpreted = (
|
|
282
|
+
items: ReadonlyArray<unknown>,
|
|
283
|
+
lastResult: Option.Option<PageResult>,
|
|
284
|
+
transitions: ReadonlyArray<(state: State) => State>,
|
|
285
|
+
): Interpretation => ({ _tag: "Interpreted", items, lastResult, transitions });
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Walk the pages in display order, concatenating their items and
|
|
289
|
+
* collecting the transitions to apply (completed split swaps, recommended
|
|
290
|
+
* splits, eager splits of pages that outgrew `initialNumItems`).
|
|
291
|
+
*
|
|
292
|
+
* `isInvalidCursorError` marks errors that call for a full pagination
|
|
293
|
+
* reset rather than a failure (the cursor no longer matches the query).
|
|
294
|
+
*/
|
|
295
|
+
export const interpret = (
|
|
296
|
+
state: State,
|
|
297
|
+
results: Record.ReadonlyRecord<string, PageResult | Error | undefined>,
|
|
298
|
+
options: {
|
|
299
|
+
readonly initialNumItems: number;
|
|
300
|
+
readonly isInvalidCursorError: (error: Error) => boolean;
|
|
301
|
+
},
|
|
302
|
+
): Interpretation => {
|
|
303
|
+
const go = (
|
|
304
|
+
remaining: ReadonlyArray<string>,
|
|
305
|
+
items: ReadonlyArray<unknown>,
|
|
306
|
+
transitions: ReadonlyArray<(s: State) => State>,
|
|
307
|
+
lastResult: Option.Option<PageResult>,
|
|
308
|
+
): Interpretation =>
|
|
309
|
+
Option.match(Array.head(remaining), {
|
|
310
|
+
onNone: () => interpreted(items, lastResult, transitions),
|
|
311
|
+
onSome: (pageKey) => {
|
|
312
|
+
const result = Record.get(results, pageKey).pipe(
|
|
313
|
+
Option.flatMap(Option.fromNullishOr),
|
|
314
|
+
Option.getOrUndefined,
|
|
315
|
+
);
|
|
316
|
+
if (result === undefined) {
|
|
317
|
+
// The trailing pages are still loading.
|
|
318
|
+
return interpreted(items, Option.none(), transitions);
|
|
319
|
+
}
|
|
320
|
+
if (result instanceof Error) {
|
|
321
|
+
return options.isInvalidCursorError(result)
|
|
322
|
+
? { _tag: "ResetRequired" }
|
|
323
|
+
: { _tag: "Failed", error: result, items };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const hasResult = (key: string) =>
|
|
327
|
+
Record.get(results, key).pipe(
|
|
328
|
+
Option.flatMap(Option.fromNullishOr),
|
|
329
|
+
Option.isSome,
|
|
330
|
+
);
|
|
331
|
+
const ongoingSplit = Record.get(state.ongoingSplits, pageKey);
|
|
332
|
+
const nextTransitions = Option.match(ongoingSplit, {
|
|
333
|
+
onSome: (replacements) =>
|
|
334
|
+
// Swap the replacements in once all of them have results.
|
|
335
|
+
Array.every(replacements, hasResult)
|
|
336
|
+
? Array.append(transitions, completeSplit(pageKey))
|
|
337
|
+
: transitions,
|
|
338
|
+
onNone: () =>
|
|
339
|
+
typeof result.splitCursor === "string" &&
|
|
340
|
+
(result.pageStatus === "SplitRecommended" ||
|
|
341
|
+
result.pageStatus === "SplitRequired" ||
|
|
342
|
+
result.page.length > options.initialNumItems)
|
|
343
|
+
? Array.append(transitions, split(pageKey, result.splitCursor))
|
|
344
|
+
: // A loaded growing page pins itself to the range it just
|
|
345
|
+
// served (`END_CURSOR` once exhausted), so it stops being a
|
|
346
|
+
// sliding window that sheds items as new documents arrive.
|
|
347
|
+
Option.exists(
|
|
348
|
+
Record.get(state.pages, pageKey),
|
|
349
|
+
(request) => request.endCursor === undefined,
|
|
350
|
+
) && result.pageStatus !== "SplitRequired"
|
|
351
|
+
? Array.append(transitions, pin(pageKey, result.continueCursor))
|
|
352
|
+
: transitions,
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
// A force-split page couldn't be fetched in full: show the items
|
|
356
|
+
// before it and report the tail as still loading.
|
|
357
|
+
return result.pageStatus === "SplitRequired"
|
|
358
|
+
? interpreted(items, Option.none(), nextTransitions)
|
|
359
|
+
: go(
|
|
360
|
+
Array.drop(remaining, 1),
|
|
361
|
+
Array.appendAll(items, result.page),
|
|
362
|
+
nextTransitions,
|
|
363
|
+
Option.some(result),
|
|
364
|
+
);
|
|
365
|
+
},
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
return go(state.pageKeys, [], [], Option.none());
|
|
369
|
+
};
|