@trpc/tanstack-react-query
Version:
TanStack React Query Integration for tRPC
397 lines (396 loc) • 15.7 kB
JavaScript
// \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
const require_utils = require("./utils-B3wZ5_eo.cjs");
let react = require("react");
react = __toESM(react, 1);
let _trpc_client = require("@trpc/client");
let _trpc_server = require("@trpc/server");
let _tanstack_react_query = require("@tanstack/react-query");
let _trpc_server_unstable_core_do_not_import = require("@trpc/server/unstable-core-do-not-import");
// src/internals/infiniteQueryOptions.ts
function trpcInfiniteQueryOptions(args) {
var _opts$initialCursor;
const { input, query, path, queryKey, opts } = args;
const inputIsSkipToken = input === _tanstack_react_query.skipToken;
const queryFn = async (queryFnContext) => {
var _opts$trpc;
const actualOpts = require_utils._objectSpread2(require_utils._objectSpread2({}, opts), {}, { trpc: require_utils._objectSpread2(require_utils._objectSpread2({}, opts === null || opts === void 0 ? void 0 : opts.trpc), (opts === null || opts === void 0 || (_opts$trpc = opts.trpc) === null || _opts$trpc === void 0 ? void 0 : _opts$trpc.abortOnUnmount) ? { signal: queryFnContext.signal } : { signal: null }) });
return await query(...require_utils.getClientArgs(queryKey, actualOpts, {
direction: queryFnContext.direction,
pageParam: queryFnContext.pageParam
}));
};
return Object.assign((0, _tanstack_react_query.infiniteQueryOptions)(require_utils._objectSpread2(require_utils._objectSpread2({}, opts !== null && opts !== void 0 ? opts : {}), {}, {
queryKey,
queryFn: inputIsSkipToken ? _tanstack_react_query.skipToken : queryFn,
initialPageParam: (_opts$initialCursor = opts === null || opts === void 0 ? void 0 : opts.initialCursor) !== null && _opts$initialCursor !== void 0 ? _opts$initialCursor : input === null || input === void 0 ? void 0 : input.cursor
})), { trpc: require_utils.createTRPCOptionsResult({ path }) });
}
// src/internals/mutationOptions.ts
/**
* @internal
*/
function trpcMutationOptions(args) {
var _opts$keyPrefix, _overrides$onSuccess;
const { mutate, path, prefix, opts, overrides } = args;
const queryClient = require_utils.unwrapLazyArg(args.queryClient);
const mutationKey = require_utils.getMutationKeyInternal({
path,
prefix: (_opts$keyPrefix = opts === null || opts === void 0 ? void 0 : opts.keyPrefix) !== null && _opts$keyPrefix !== void 0 ? _opts$keyPrefix : prefix
});
const defaultOpts = queryClient.defaultMutationOptions(queryClient.getMutationDefaults(mutationKey));
const mutationSuccessOverride = (_overrides$onSuccess = overrides === null || overrides === void 0 ? void 0 : overrides.onSuccess) !== null && _overrides$onSuccess !== void 0 ? _overrides$onSuccess : ((options) => options.originalFn());
const mutationFn = async (input) => {
return await mutate(...require_utils.getClientArgs([...mutationKey, { input }], opts));
};
return require_utils._objectSpread2(require_utils._objectSpread2({}, opts), {}, {
mutationKey,
mutationFn,
onSuccess(...args) {
var _ref, _opts$meta;
const originalFn = () => {
var _opts$onSuccess, _opts$onSuccess2, _defaultOpts$onSucces;
return (_opts$onSuccess = opts === null || opts === void 0 || (_opts$onSuccess2 = opts.onSuccess) === null || _opts$onSuccess2 === void 0 ? void 0 : _opts$onSuccess2.call(opts, ...args)) !== null && _opts$onSuccess !== void 0 ? _opts$onSuccess : defaultOpts === null || defaultOpts === void 0 || (_defaultOpts$onSucces = defaultOpts.onSuccess) === null || _defaultOpts$onSucces === void 0 ? void 0 : _defaultOpts$onSucces.call(defaultOpts, ...args);
};
return mutationSuccessOverride({
originalFn,
queryClient,
meta: (_ref = (_opts$meta = opts === null || opts === void 0 ? void 0 : opts.meta) !== null && _opts$meta !== void 0 ? _opts$meta : defaultOpts === null || defaultOpts === void 0 ? void 0 : defaultOpts.meta) !== null && _ref !== void 0 ? _ref : {}
});
},
trpc: require_utils.createTRPCOptionsResult({ path })
});
}
// src/internals/queryOptions.ts
/**
* @internal
*/
function trpcQueryOptions(args) {
const { input, query, path, queryKey, opts } = args;
const queryClient = require_utils.unwrapLazyArg(args.queryClient);
const inputIsSkipToken = input === _tanstack_react_query.skipToken;
const queryFn = async (queryFnContext) => {
var _opts$trpc;
const abortController = new AbortController();
const actualOpts = require_utils._objectSpread2(require_utils._objectSpread2({}, opts), {}, { trpc: require_utils._objectSpread2(require_utils._objectSpread2({}, opts === null || opts === void 0 ? void 0 : opts.trpc), (opts === null || opts === void 0 || (_opts$trpc = opts.trpc) === null || _opts$trpc === void 0 ? void 0 : _opts$trpc.abortOnUnmount) ? { signal: queryFnContext.signal } : { signal: abortController.signal }) });
const queryKey = queryFnContext.queryKey;
const result = await query(...require_utils.getClientArgs(queryKey, actualOpts));
if ((0, _trpc_server_unstable_core_do_not_import.isAsyncIterable)(result)) return require_utils.streamIntoQuery({
iterable: result,
context: queryFnContext,
queryClient,
abortController
});
return result;
};
return Object.assign((0, _tanstack_react_query.queryOptions)(require_utils._objectSpread2(require_utils._objectSpread2({}, opts), {}, {
queryKey,
queryFn: inputIsSkipToken ? _tanstack_react_query.skipToken : queryFn
})), { trpc: require_utils.createTRPCOptionsResult({ path }) });
}
// src/internals/subscriptionOptions.ts
/**
* @internal
*/
const trpcSubscriptionOptions = (args) => {
const { subscribe, path, queryKey, input, opts = {} } = args;
const enabled = "enabled" in opts ? !!opts.enabled : input !== _tanstack_react_query.skipToken;
const _subscribe = (innerOpts) => {
return subscribe(path.join("."), input === _tanstack_react_query.skipToken ? void 0 : input, require_utils._objectSpread2(require_utils._objectSpread2({}, innerOpts), {}, { onComplete: () => {
var _innerOpts$onComplete;
return (_innerOpts$onComplete = innerOpts.onComplete) === null || _innerOpts$onComplete === void 0 ? void 0 : _innerOpts$onComplete.call(innerOpts);
} }));
};
return require_utils._objectSpread2(require_utils._objectSpread2({}, opts), {}, {
enabled,
subscribe: _subscribe,
queryKey,
trpc: require_utils.createTRPCOptionsResult({ path })
});
};
// src/internals/createOptionsProxy.ts
/**
* Creates the options proxy without React context. Works on the server too.
*
* @example
* ```ts
* export const trpc = createTRPCOptionsProxy<AppRouter>({
* client: trpcClient,
* queryClient,
* });
* ```
*
* @see https://trpc.io/docs/client/tanstack-react-query/setup#3c-set-up-without-react-context
* @see https://trpc.io/docs/client/tanstack-react-query/server-components#5-create-a-trpc-caller-for-server-components
*/
function createTRPCOptionsProxy(opts) {
const prefix = opts.keyPrefix;
const callIt = (type) => {
return (path, input, trpcOpts) => {
if ("router" in opts) return Promise.resolve(require_utils.unwrapLazyArg(opts.ctx)).then((ctx) => (0, _trpc_server.callTRPCProcedure)({
router: opts.router,
path,
getRawInput: async () => input,
ctx,
type,
signal: void 0,
batchIndex: 0
}));
return (opts.client instanceof _trpc_client.TRPCUntypedClient ? opts.client : (0, _trpc_client.getUntypedClient)(opts.client))[type](path, input, trpcOpts);
};
};
return (0, _trpc_server.createTRPCRecursiveProxy)(({ args, path: _path }) => {
const path = [..._path];
const utilName = path.pop();
const [arg1, arg2] = args;
return {
"~types": void 0,
"~queryClient": () => require_utils.unwrapLazyArg(opts.queryClient),
pathKey: () => {
return require_utils.getQueryKeyInternal({
path,
type: "any",
prefix
});
},
pathFilter: () => {
return require_utils._objectSpread2(require_utils._objectSpread2({}, arg1), {}, { queryKey: require_utils.getQueryKeyInternal({
path,
type: "any",
prefix
}) });
},
queryOptions: () => {
return trpcQueryOptions({
input: arg1,
opts: arg2,
path,
queryClient: opts.queryClient,
queryKey: require_utils.getQueryKeyInternal({
path,
input: arg1,
type: "query",
prefix
}),
query: callIt("query")
});
},
queryKey: () => {
return require_utils.getQueryKeyInternal({
path,
input: arg1,
type: "query",
prefix
});
},
queryFilter: () => {
return require_utils._objectSpread2(require_utils._objectSpread2({}, arg2), {}, { queryKey: require_utils.getQueryKeyInternal({
path,
input: arg1,
type: "query",
prefix
}) });
},
infiniteQueryOptions: () => {
return trpcInfiniteQueryOptions({
input: arg1,
opts: arg2,
path,
queryClient: opts.queryClient,
queryKey: require_utils.getQueryKeyInternal({
path,
input: arg1,
type: "infinite",
prefix
}),
query: callIt("query")
});
},
infiniteQueryKey: () => {
return require_utils.getQueryKeyInternal({
path,
input: arg1,
type: "infinite",
prefix
});
},
infiniteQueryFilter: () => {
return require_utils._objectSpread2(require_utils._objectSpread2({}, arg2), {}, { queryKey: require_utils.getQueryKeyInternal({
path,
input: arg1,
type: "infinite",
prefix
}) });
},
mutationOptions: () => {
var _opts$overrides;
return trpcMutationOptions({
opts: arg1,
path,
prefix,
queryClient: opts.queryClient,
mutate: callIt("mutation"),
overrides: (_opts$overrides = opts.overrides) === null || _opts$overrides === void 0 ? void 0 : _opts$overrides.mutations
});
},
mutationKey: () => {
return require_utils.getMutationKeyInternal({
path,
prefix
});
},
subscriptionOptions: () => {
return trpcSubscriptionOptions({
opts: arg2,
path,
input: arg1,
queryKey: require_utils.getQueryKeyInternal({
path,
input: arg1,
type: "any",
prefix
}),
subscribe: callIt("subscription")
});
}
}[utilName]();
});
}
// src/internals/hydration.ts
/**
* Keyed by the request's `QueryClient`, so one server render's boundaries
* share it and the next request starts over.
*/
const sentByClient = /* @__PURE__ */ new WeakMap();
function sentEntries(queryClient) {
let sent = sentByClient.get(queryClient);
if (!sent) {
sent = {
queries: /* @__PURE__ */ new Map(),
mutations: /* @__PURE__ */ new WeakSet(),
watchingPending: false
};
sentByClient.set(queryClient, sent);
}
return sent;
}
/**
* A query sent pending carries its request's promise, so the data that
* request writes is already on its way. Record it once it lands: the query
* drops its promise after settling, so it can't be compared later.
*/
function watchPendingSends(queryClient, sent) {
if (sent.watchingPending) return;
sent.watchingPending = true;
queryClient.getQueryCache().subscribe((event) => {
if (event.type !== "updated" || event.action.type !== "success" || event.action.manual) return;
const entry = sent.queries.get(event.query.queryHash);
if ((entry === null || entry === void 0 ? void 0 : entry.promise) && entry.promise === event.query.promise) {
entry.dataUpdatedAt = event.query.state.dataUpdatedAt;
entry.promise = void 0;
}
});
}
function isAlreadySent(query, sent) {
return sent !== void 0 && query.state.dataUpdatedAt <= sent.dataUpdatedAt;
}
/**
* Dehydrate what the client's `dehydrate` defaults select, minus entries an
* earlier call already sent for this client with the same or newer data.
* @internal
*/
function dehydrateUnsent(queryClient) {
var _defaults$shouldDehyd, _defaults$shouldDehyd2;
const defaults = queryClient.getDefaultOptions().dehydrate;
const shouldDehydrateQuery = (_defaults$shouldDehyd = defaults === null || defaults === void 0 ? void 0 : defaults.shouldDehydrateQuery) !== null && _defaults$shouldDehyd !== void 0 ? _defaults$shouldDehyd : _tanstack_react_query.defaultShouldDehydrateQuery;
const shouldDehydrateMutation = (_defaults$shouldDehyd2 = defaults === null || defaults === void 0 ? void 0 : defaults.shouldDehydrateMutation) !== null && _defaults$shouldDehyd2 !== void 0 ? _defaults$shouldDehyd2 : _tanstack_react_query.defaultShouldDehydrateMutation;
const sent = sentEntries(queryClient);
return (0, _tanstack_react_query.dehydrate)(queryClient, {
shouldDehydrateQuery: (query) => {
if (isAlreadySent(query, sent.queries.get(query.queryHash)) || !shouldDehydrateQuery(query)) return false;
const promise = query.state.status === "pending" ? query.promise : void 0;
if (promise) watchPendingSends(queryClient, sent);
sent.queries.set(query.queryHash, {
dataUpdatedAt: query.state.dataUpdatedAt,
promise
});
return true;
},
shouldDehydrateMutation: (mutation) => {
if (sent.mutations.has(mutation) || !shouldDehydrateMutation(mutation)) return false;
sent.mutations.add(mutation);
return true;
}
});
}
// src/internals/HydrateClient.tsx
/**
* Create a `HydrateClient` server component for the request's `QueryClient`.
* It sends the queries started so far in this request to the browser,
* pending ones as promises that stream in as they settle. A query an earlier
* `HydrateClient` already sent is skipped, so nesting them is fine.
*
* React Server Components only: the package resolves to the server build
* through the `react-server` export condition.
*
* @see https://trpc.io/docs/client/tanstack-react-query/handles#hydrate-client
*/
function unstable_createHydrateClient(_queryClient) {
function HydrateClient() {
throw new Error("`HydrateClient` from `unstable_createHydrateClient()` works only in React Server Components. Render it from a server component; in client components, use TanStack Query's `HydrationBoundary`.");
}
return HydrateClient;
}
/**
* `unstable_createHydrateClient` for the `react-server` export condition.
* @internal
*/
function createHydrateClientReactServer(queryClient) {
function HydrateClient(props) {
return /* @__PURE__ */ react.createElement(_tanstack_react_query.HydrationBoundary, { state: dehydrateUnsent(require_utils.unwrapLazyArg(queryClient)) }, props.children);
}
return HydrateClient;
}
Object.defineProperty(exports, "__toESM", {
enumerable: true,
get: function() {
return __toESM;
}
});
Object.defineProperty(exports, "createHydrateClientReactServer", {
enumerable: true,
get: function() {
return createHydrateClientReactServer;
}
});
Object.defineProperty(exports, "createTRPCOptionsProxy", {
enumerable: true,
get: function() {
return createTRPCOptionsProxy;
}
});
Object.defineProperty(exports, "unstable_createHydrateClient", {
enumerable: true,
get: function() {
return unstable_createHydrateClient;
}
});