@confect/react 9.2.5 → 9.4.0

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["useConvexQuery","QueryResult.load","QueryResult.succeed","QueryResult.fail","OptimisticLocalStore.make","useConvexMutation","useConvexAction"],"sources":["../src/index.ts"],"sourcesContent":["import { Ref } from \"@confect/core\";\nimport type { OptimisticUpdate as ConvexOptimisticUpdate } from \"convex/browser\";\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 Either from \"effect/Either\";\nimport * as Exit from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport { useCallback, useMemo } from \"react\";\n\nimport * as OptimisticLocalStore from \"./OptimisticLocalStore\";\nimport * as QueryResult from \"./QueryResult\";\n\nexport { OptimisticLocalStore, QueryResult };\n\nexport type InvokeReturn<Ref_ extends Ref.Any> = [Ref.Error<Ref_>] extends [\n never,\n]\n ? Promise<Ref.Returns<Ref_>>\n : Promise<Either.Either<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 an `Either` 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: Either.Either<unknown, unknown> = Either.try(\n () => useConvexQuery(functionReference, encodedArgs),\n );\n\n return useMemo(\n () =>\n Either.match(encodedReturnsOrError, {\n onRight: (encodedReturnsOrUndefined) =>\n encodedReturnsOrUndefined === undefined\n ? QueryResult.load(skipped)\n : QueryResult.succeed(\n Ref.decodeReturnsSync(ref, encodedReturnsOrUndefined),\n ),\n onLeft: (error) => {\n if (Ref.isConvexError(error)) {\n const decoded = Ref.decodeErrorSync(ref, error.data);\n if (Option.isSome(decoded)) {\n return QueryResult.fail(decoded.value);\n }\n }\n throw error;\n },\n }),\n // `Either.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, Either.merge(encodedReturnsOrError)],\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 invokeAsEither(\n ref,\n (_, encodedArgs) => convexReactMutation(encodedArgs as never),\n args,\n ).then((either) =>\n Ref.hasErrorSchema(ref) ? either : Either.getOrThrow(either),\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 an\n * `Either` with the decoded `returns` value on the right and the decoded error\n * on the left.\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 an\n * `Either` with the decoded `returns` value on the right and the decoded error\n * on the left.\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 invokeAsEither(\n ref,\n (_, encodedArgs) => actualAction(encodedArgs),\n args,\n ).then((either) =>\n Ref.hasErrorSchema(ref) ? either : Either.getOrThrow(either),\n )) as (...args: Ref.OptionalArgs<Action>) => InvokeReturn<Action>,\n [ref, actualAction],\n );\n};\n\nconst invokeAsEither = 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<Either.Either<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(\"ParseError\", Effect.die),\n Effect.either,\n ),\n );\n if (Exit.isSuccess(exit)) return exit.value;\n throw Cause.squash(exit.cause);\n};\n"],"mappings":";;;;;;;;;;;AAiCA,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,QA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AAO,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,cAAc,OAAO,GAAG,GACxC,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","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 Either from \"effect/Either\";\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<Either.Either<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 an `Either` 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: Either.Either<unknown, unknown> = Either.try(\n () => useConvexQuery(functionReference, encodedArgs),\n );\n\n return useMemo(\n () =>\n Either.match(encodedReturnsOrError, {\n onRight: (encodedReturnsOrUndefined) =>\n encodedReturnsOrUndefined === undefined\n ? QueryResult.load(skipped)\n : QueryResult.succeed(\n Ref.decodeReturnsSync(ref, encodedReturnsOrUndefined),\n ),\n onLeft: (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 // `Either.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, Either.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 invokeAsEither(\n ref,\n (_, encodedArgs) => convexReactMutation(encodedArgs as never),\n args,\n ).then((either) =>\n Ref.hasErrorSchema(ref) ? either : Either.getOrThrow(either),\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 an\n * `Either` with the decoded `returns` value on the right and the decoded error\n * on the left.\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 an\n * `Either` with the decoded `returns` value on the right and the decoded error\n * on the left.\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 invokeAsEither(\n ref,\n (_, encodedArgs) => actualAction(encodedArgs),\n args,\n ).then((either) =>\n Ref.hasErrorSchema(ref) ? either : Either.getOrThrow(either),\n )) as (...args: Ref.OptionalArgs<Action>) => InvokeReturn<Action>,\n [ref, actualAction],\n );\n};\n\nconst invokeAsEither = 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<Either.Either<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(\"ParseError\", Effect.die),\n Effect.either,\n ),\n );\n if (Exit.isSuccess(exit)) return exit.value;\n throw Cause.squash(exit.cause);\n};\n"],"mappings":";;;;;;;;;;;;;;;AAsCA,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,I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