UNPKG

@cometh/connect-react-hooks

Version:
1,280 lines (1,239 loc) 85.1 kB
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var __typeError = (msg) => { throw TypeError(msg); }; var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); // src/actions/createSmartAccount.ts var _connectsdk4337 = require('@cometh/connect-sdk-4337'); var _wagmi = require('wagmi'); async function createSmartAccount(config) { const { bundlerUrl, paymasterUrl, apiKey, chain, publicClient, baseUrl, comethSignerConfig, safeContractConfig, smartAccountAddress } = config; const account = await _connectsdk4337.createSafeSmartAccount.call(void 0, { apiKey, chain, publicClient, baseUrl, smartAccountAddress, comethSignerConfig, safeContractConfig }); let client; if (paymasterUrl) { const paymasterClient = await _connectsdk4337.createComethPaymasterClient.call(void 0, { transport: _wagmi.http.call(void 0, paymasterUrl), chain, publicClient }); client = _connectsdk4337.createSmartAccountClient.call(void 0, { account, chain, bundlerTransport: _wagmi.http.call(void 0, bundlerUrl), paymaster: paymasterClient, userOperation: { estimateFeesPerGas: async () => { return await paymasterClient.getUserOperationGasPrice(); } }, publicClient }); } else { client = _connectsdk4337.createSmartAccountClient.call(void 0, { account, chain, bundlerTransport: _wagmi.http.call(void 0, bundlerUrl), publicClient }); } const address = client.account.address; return { client, address }; } // src/providers/ConnectProvider.tsx var _react = require('react'); var React2 = _interopRequireWildcard(_react); var React3 = _interopRequireWildcard(_react); var React4 = _interopRequireWildcard(_react); var React5 = _interopRequireWildcard(_react); var React6 = _interopRequireWildcard(_react); var React7 = _interopRequireWildcard(_react); var CHAIN_STORAGE_KEY = "currentChain"; var ConnectContext = _react.createContext.call(void 0, { queryClient: void 0, smartAccountClient: null, smartAccountAddress: void 0, updateSmartAccountClient: async () => { }, disconnectSmartAccount: async () => { }, networksConfig: void 0, apikey: void 0 }); var ConnectProvider = ({ children, config, queryClient }) => { const [smartAccountClient, setSmartAccountClient] = _react.useState.call(void 0, null); const [smartAccountAddress, setSmartAccountAddress] = _react.useState.call(void 0, void 0); const updateSmartAccountClient = _react.useCallback.call(void 0, async (params = {}) => { const chain = _nullishCoalesce(_nullishCoalesce(params.chain, () => ( JSON.parse(_nullishCoalesce(localStorage.getItem(CHAIN_STORAGE_KEY), () => ( "null"))))), () => ( config.networksConfig[0].chain)); const bundlerUrl = _optionalChain([config, 'access', _2 => _2.networksConfig, 'access', _3 => _3.find, 'call', _4 => _4( (network) => _optionalChain([network, 'access', _5 => _5.chain, 'optionalAccess', _6 => _6.id]) === chain.id ), 'optionalAccess', _7 => _7.bundlerUrl]); const paymasterUrl = _optionalChain([config, 'access', _8 => _8.networksConfig, 'access', _9 => _9.find, 'call', _10 => _10( (network) => _optionalChain([network, 'access', _11 => _11.chain, 'optionalAccess', _12 => _12.id]) === chain.id ), 'optionalAccess', _13 => _13.paymasterUrl]); const publicClient = _optionalChain([config, 'access', _14 => _14.networksConfig, 'access', _15 => _15.find, 'call', _16 => _16( (network) => _optionalChain([network, 'access', _17 => _17.chain, 'optionalAccess', _18 => _18.id]) === chain.id ), 'optionalAccess', _19 => _19.publicClient]); if (!bundlerUrl) throw new Error("Bundler url not found"); try { const { client, address: newAddress } = await createSmartAccount({ ...config, chain, bundlerUrl, paymasterUrl, publicClient, smartAccountAddress: params.address, comethSignerConfig: { ...config.comethSignerConfig, passKeyName: params.passKeyName } }); setSmartAccountClient(client); setSmartAccountAddress(newAddress); localStorage.setItem(CHAIN_STORAGE_KEY, JSON.stringify(chain)); } catch (e) { console.log(e); } }, [config, config.networksConfig[0].chain] ); const disconnectSmartAccount = _react.useCallback.call(void 0, async () => { setSmartAccountClient(null); setSmartAccountAddress(void 0); localStorage.removeItem(CHAIN_STORAGE_KEY); }, []); _react.useEffect.call(void 0, () => { if (config.smartAccountAddress) { updateSmartAccountClient({ address: config.smartAccountAddress }); } }, [config.smartAccountAddress, updateSmartAccountClient]); const value = _react.useMemo.call(void 0, () => ({ queryClient, smartAccountClient, smartAccountAddress, updateSmartAccountClient, disconnectSmartAccount, networksConfig: config.networksConfig, apikey: config.apiKey }), [ queryClient, smartAccountClient, smartAccountAddress, updateSmartAccountClient, disconnectSmartAccount, config.networksConfig ] ); return /* @__PURE__ */ React2.default.createElement(ConnectContext.Provider, { value }, children); }; // src/hooks/useAccount.ts var useAccount = () => { const context = _react.useContext.call(void 0, ConnectContext); if (context === void 0) { throw new Error("useAccount must be used within a ConnectProvider"); } const { smartAccountClient, smartAccountAddress } = context; const { chain, chainId } = _react.useMemo.call(void 0, () => ({ chain: _optionalChain([smartAccountClient, 'optionalAccess', _20 => _20.chain]), chainId: _optionalChain([smartAccountClient, 'optionalAccess', _21 => _21.chain, 'optionalAccess', _22 => _22.id]) }), [smartAccountClient] ); const isConnected = _react.useMemo.call(void 0, () => !!smartAccountClient && !!smartAccountAddress, [smartAccountClient, smartAccountAddress] ); const status = _react.useMemo.call(void 0, () => { return isConnected ? "connected" : "disconnected"; }, [isConnected]); return { address: smartAccountAddress, smartAccountClient, isConnected, isDisconnected: !isConnected, status, chain, chainId }; }; // src/hooks/useSmartAccount.ts var useSmartAccount = () => { const context = _react.useContext.call(void 0, ConnectContext); if (context === void 0) { throw new Error("Hooks must be used within a SmartAccountProvider"); } return context; }; // ../../node_modules/@tanstack/query-core/build/modern/subscribable.js var Subscribable = class { constructor() { this.listeners = /* @__PURE__ */ new Set(); this.subscribe = this.subscribe.bind(this); } subscribe(listener) { this.listeners.add(listener); this.onSubscribe(); return () => { this.listeners.delete(listener); this.onUnsubscribe(); }; } hasListeners() { return this.listeners.size > 0; } onSubscribe() { } onUnsubscribe() { } }; // ../../node_modules/@tanstack/query-core/build/modern/utils.js var isServer = typeof window === "undefined" || "Deno" in globalThis; function noop() { } function isValidTimeout(value) { return typeof value === "number" && value >= 0 && value !== Infinity; } function timeUntilStale(updatedAt, staleTime) { return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0); } function resolveStaleTime(staleTime, query) { return typeof staleTime === "function" ? staleTime(query) : staleTime; } function resolveEnabled(enabled, query) { return typeof enabled === "function" ? enabled(query) : enabled; } function hashKey(queryKey) { return JSON.stringify( queryKey, (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => { result[key] = val[key]; return result; }, {}) : val ); } function replaceEqualDeep(a, b) { if (a === b) { return a; } const array = isPlainArray(a) && isPlainArray(b); if (array || isPlainObject(a) && isPlainObject(b)) { const aItems = array ? a : Object.keys(a); const aSize = aItems.length; const bItems = array ? b : Object.keys(b); const bSize = bItems.length; const copy = array ? [] : {}; let equalItems = 0; for (let i = 0; i < bSize; i++) { const key = array ? i : bItems[i]; if ((!array && aItems.includes(key) || array) && a[key] === void 0 && b[key] === void 0) { copy[key] = void 0; equalItems++; } else { copy[key] = replaceEqualDeep(a[key], b[key]); if (copy[key] === a[key] && a[key] !== void 0) { equalItems++; } } } return aSize === bSize && equalItems === aSize ? a : copy; } return b; } function shallowEqualObjects(a, b) { if (!b || Object.keys(a).length !== Object.keys(b).length) { return false; } for (const key in a) { if (a[key] !== b[key]) { return false; } } return true; } function isPlainArray(value) { return Array.isArray(value) && value.length === Object.keys(value).length; } function isPlainObject(o) { if (!hasObjectPrototype(o)) { return false; } const ctor = o.constructor; if (ctor === void 0) { return true; } const prot = ctor.prototype; if (!hasObjectPrototype(prot)) { return false; } if (!prot.hasOwnProperty("isPrototypeOf")) { return false; } if (Object.getPrototypeOf(o) !== Object.prototype) { return false; } return true; } function hasObjectPrototype(o) { return Object.prototype.toString.call(o) === "[object Object]"; } function replaceData(prevData, data, options) { if (typeof options.structuralSharing === "function") { return options.structuralSharing(prevData, data); } else if (options.structuralSharing !== false) { if (process.env.NODE_ENV !== "production") { try { return replaceEqualDeep(prevData, data); } catch (error) { console.error( `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}` ); } } return replaceEqualDeep(prevData, data); } return data; } var skipToken = Symbol(); // ../../node_modules/@tanstack/query-core/build/modern/focusManager.js var _focused, _cleanup, _setup, _a; var FocusManager = (_a = class extends Subscribable { constructor() { super(); __privateAdd(this, _focused); __privateAdd(this, _cleanup); __privateAdd(this, _setup); __privateSet(this, _setup, (onFocus) => { if (!isServer && window.addEventListener) { const listener = () => onFocus(); window.addEventListener("visibilitychange", listener, false); return () => { window.removeEventListener("visibilitychange", listener); }; } return; }); } onSubscribe() { if (!__privateGet(this, _cleanup)) { this.setEventListener(__privateGet(this, _setup)); } } onUnsubscribe() { var _a5; if (!this.hasListeners()) { (_a5 = __privateGet(this, _cleanup)) == null ? void 0 : _a5.call(this); __privateSet(this, _cleanup, void 0); } } setEventListener(setup) { var _a5; __privateSet(this, _setup, setup); (_a5 = __privateGet(this, _cleanup)) == null ? void 0 : _a5.call(this); __privateSet(this, _cleanup, setup((focused) => { if (typeof focused === "boolean") { this.setFocused(focused); } else { this.onFocus(); } })); } setFocused(focused) { const changed = __privateGet(this, _focused) !== focused; if (changed) { __privateSet(this, _focused, focused); this.onFocus(); } } onFocus() { const isFocused = this.isFocused(); this.listeners.forEach((listener) => { listener(isFocused); }); } isFocused() { if (typeof __privateGet(this, _focused) === "boolean") { return __privateGet(this, _focused); } return _optionalChain([globalThis, 'access', _23 => _23.document, 'optionalAccess', _24 => _24.visibilityState]) !== "hidden"; } }, _focused = new WeakMap(), _cleanup = new WeakMap(), _setup = new WeakMap(), _a); var focusManager = new FocusManager(); // ../../node_modules/@tanstack/query-core/build/modern/onlineManager.js var _online, _cleanup2, _setup2, _a2; var OnlineManager = (_a2 = class extends Subscribable { constructor() { super(); __privateAdd(this, _online, true); __privateAdd(this, _cleanup2); __privateAdd(this, _setup2); __privateSet(this, _setup2, (onOnline) => { if (!isServer && window.addEventListener) { const onlineListener = () => onOnline(true); const offlineListener = () => onOnline(false); window.addEventListener("online", onlineListener, false); window.addEventListener("offline", offlineListener, false); return () => { window.removeEventListener("online", onlineListener); window.removeEventListener("offline", offlineListener); }; } return; }); } onSubscribe() { if (!__privateGet(this, _cleanup2)) { this.setEventListener(__privateGet(this, _setup2)); } } onUnsubscribe() { var _a5; if (!this.hasListeners()) { (_a5 = __privateGet(this, _cleanup2)) == null ? void 0 : _a5.call(this); __privateSet(this, _cleanup2, void 0); } } setEventListener(setup) { var _a5; __privateSet(this, _setup2, setup); (_a5 = __privateGet(this, _cleanup2)) == null ? void 0 : _a5.call(this); __privateSet(this, _cleanup2, setup(this.setOnline.bind(this))); } setOnline(online) { const changed = __privateGet(this, _online) !== online; if (changed) { __privateSet(this, _online, online); this.listeners.forEach((listener) => { listener(online); }); } } isOnline() { return __privateGet(this, _online); } }, _online = new WeakMap(), _cleanup2 = new WeakMap(), _setup2 = new WeakMap(), _a2); var onlineManager = new OnlineManager(); // ../../node_modules/@tanstack/query-core/build/modern/thenable.js function pendingThenable() { let resolve; let reject; const thenable = new Promise((_resolve, _reject) => { resolve = _resolve; reject = _reject; }); thenable.status = "pending"; thenable.catch(() => { }); function finalize(data) { Object.assign(thenable, data); delete thenable.resolve; delete thenable.reject; } thenable.resolve = (value) => { finalize({ status: "fulfilled", value }); resolve(value); }; thenable.reject = (reason) => { finalize({ status: "rejected", reason }); reject(reason); }; return thenable; } // ../../node_modules/@tanstack/query-core/build/modern/retryer.js function canFetch(networkMode) { return (_nullishCoalesce(networkMode, () => ( "online"))) === "online" ? onlineManager.isOnline() : true; } // ../../node_modules/@tanstack/query-core/build/modern/notifyManager.js function createNotifyManager() { let queue = []; let transactions = 0; let notifyFn = (callback) => { callback(); }; let batchNotifyFn = (callback) => { callback(); }; let scheduleFn = (cb) => setTimeout(cb, 0); const schedule = (callback) => { if (transactions) { queue.push(callback); } else { scheduleFn(() => { notifyFn(callback); }); } }; const flush = () => { const originalQueue = queue; queue = []; if (originalQueue.length) { scheduleFn(() => { batchNotifyFn(() => { originalQueue.forEach((callback) => { notifyFn(callback); }); }); }); } }; return { batch: (callback) => { let result; transactions++; try { result = callback(); } finally { transactions--; if (!transactions) { flush(); } } return result; }, /** * All calls to the wrapped function will be batched. */ batchCalls: (callback) => { return (...args) => { schedule(() => { callback(...args); }); }; }, schedule, /** * Use this method to set a custom notify function. * This can be used to for example wrap notifications with `React.act` while running tests. */ setNotifyFunction: (fn) => { notifyFn = fn; }, /** * Use this method to set a custom function to batch notifications together into a single tick. * By default React Query will use the batch function provided by ReactDOM or React Native. */ setBatchNotifyFunction: (fn) => { batchNotifyFn = fn; }, setScheduler: (fn) => { scheduleFn = fn; } }; } var notifyManager = createNotifyManager(); // ../../node_modules/@tanstack/query-core/build/modern/query.js function fetchState(data, options) { return { fetchFailureCount: 0, fetchFailureReason: null, fetchStatus: canFetch(options.networkMode) ? "fetching" : "paused", ...data === void 0 && { error: null, status: "pending" } }; } // ../../node_modules/@tanstack/query-core/build/modern/mutation.js function getDefaultState() { return { context: void 0, data: void 0, error: null, failureCount: 0, failureReason: null, isPaused: false, status: "idle", variables: void 0, submittedAt: 0 }; } // ../../node_modules/@tanstack/query-core/build/modern/queryObserver.js var _client, _currentQuery, _currentQueryInitialState, _currentResult, _currentResultState, _currentResultOptions, _currentThenable, _selectError, _selectFn, _selectResult, _lastQueryWithDefinedData, _staleTimeoutId, _refetchIntervalId, _currentRefetchInterval, _trackedProps, _QueryObserver_instances, executeFetch_fn, updateStaleTimeout_fn, computeRefetchInterval_fn, updateRefetchInterval_fn, updateTimers_fn, clearStaleTimeout_fn, clearRefetchInterval_fn, updateQuery_fn, notify_fn, _a3; var QueryObserver = (_a3 = class extends Subscribable { constructor(client, options) { super(); __privateAdd(this, _QueryObserver_instances); __privateAdd(this, _client); __privateAdd(this, _currentQuery); __privateAdd(this, _currentQueryInitialState); __privateAdd(this, _currentResult); __privateAdd(this, _currentResultState); __privateAdd(this, _currentResultOptions); __privateAdd(this, _currentThenable); __privateAdd(this, _selectError); __privateAdd(this, _selectFn); __privateAdd(this, _selectResult); // This property keeps track of the last query with defined data. // It will be used to pass the previous data and query to the placeholder function between renders. __privateAdd(this, _lastQueryWithDefinedData); __privateAdd(this, _staleTimeoutId); __privateAdd(this, _refetchIntervalId); __privateAdd(this, _currentRefetchInterval); __privateAdd(this, _trackedProps, /* @__PURE__ */ new Set()); this.options = options; __privateSet(this, _client, client); __privateSet(this, _selectError, null); __privateSet(this, _currentThenable, pendingThenable()); if (!this.options.experimental_prefetchInRender) { __privateGet(this, _currentThenable).reject( new Error("experimental_prefetchInRender feature flag is not enabled") ); } this.bindMethods(); this.setOptions(options); } bindMethods() { this.refetch = this.refetch.bind(this); } onSubscribe() { if (this.listeners.size === 1) { __privateGet(this, _currentQuery).addObserver(this); if (shouldFetchOnMount(__privateGet(this, _currentQuery), this.options)) { __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this); } else { this.updateResult(); } __privateMethod(this, _QueryObserver_instances, updateTimers_fn).call(this); } } onUnsubscribe() { if (!this.hasListeners()) { this.destroy(); } } shouldFetchOnReconnect() { return shouldFetchOn( __privateGet(this, _currentQuery), this.options, this.options.refetchOnReconnect ); } shouldFetchOnWindowFocus() { return shouldFetchOn( __privateGet(this, _currentQuery), this.options, this.options.refetchOnWindowFocus ); } destroy() { this.listeners = /* @__PURE__ */ new Set(); __privateMethod(this, _QueryObserver_instances, clearStaleTimeout_fn).call(this); __privateMethod(this, _QueryObserver_instances, clearRefetchInterval_fn).call(this); __privateGet(this, _currentQuery).removeObserver(this); } setOptions(options, notifyOptions) { const prevOptions = this.options; const prevQuery = __privateGet(this, _currentQuery); this.options = __privateGet(this, _client).defaultQueryOptions(options); if (this.options.enabled !== void 0 && typeof this.options.enabled !== "boolean" && typeof this.options.enabled !== "function" && typeof resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== "boolean") { throw new Error( "Expected enabled to be a boolean or a callback that returns a boolean" ); } __privateMethod(this, _QueryObserver_instances, updateQuery_fn).call(this); __privateGet(this, _currentQuery).setOptions(this.options); if (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) { __privateGet(this, _client).getQueryCache().notify({ type: "observerOptionsUpdated", query: __privateGet(this, _currentQuery), observer: this }); } const mounted = this.hasListeners(); if (mounted && shouldFetchOptionally( __privateGet(this, _currentQuery), prevQuery, this.options, prevOptions )) { __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this); } this.updateResult(notifyOptions); if (mounted && (__privateGet(this, _currentQuery) !== prevQuery || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== resolveEnabled(prevOptions.enabled, __privateGet(this, _currentQuery)) || resolveStaleTime(this.options.staleTime, __privateGet(this, _currentQuery)) !== resolveStaleTime(prevOptions.staleTime, __privateGet(this, _currentQuery)))) { __privateMethod(this, _QueryObserver_instances, updateStaleTimeout_fn).call(this); } const nextRefetchInterval = __privateMethod(this, _QueryObserver_instances, computeRefetchInterval_fn).call(this); if (mounted && (__privateGet(this, _currentQuery) !== prevQuery || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== resolveEnabled(prevOptions.enabled, __privateGet(this, _currentQuery)) || nextRefetchInterval !== __privateGet(this, _currentRefetchInterval))) { __privateMethod(this, _QueryObserver_instances, updateRefetchInterval_fn).call(this, nextRefetchInterval); } } getOptimisticResult(options) { const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), options); const result = this.createResult(query, options); if (shouldAssignObserverCurrentProperties(this, result)) { __privateSet(this, _currentResult, result); __privateSet(this, _currentResultOptions, this.options); __privateSet(this, _currentResultState, __privateGet(this, _currentQuery).state); } return result; } getCurrentResult() { return __privateGet(this, _currentResult); } trackResult(result, onPropTracked) { const trackedResult = {}; Object.keys(result).forEach((key) => { Object.defineProperty(trackedResult, key, { configurable: false, enumerable: true, get: () => { this.trackProp(key); _optionalChain([onPropTracked, 'optionalCall', _25 => _25(key)]); return result[key]; } }); }); return trackedResult; } trackProp(key) { __privateGet(this, _trackedProps).add(key); } getCurrentQuery() { return __privateGet(this, _currentQuery); } refetch({ ...options } = {}) { return this.fetch({ ...options }); } fetchOptimistic(options) { const defaultedOptions = __privateGet(this, _client).defaultQueryOptions(options); const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), defaultedOptions); return query.fetch().then(() => this.createResult(query, defaultedOptions)); } fetch(fetchOptions) { return __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this, { ...fetchOptions, cancelRefetch: _nullishCoalesce(fetchOptions.cancelRefetch, () => ( true)) }).then(() => { this.updateResult(); return __privateGet(this, _currentResult); }); } createResult(query, options) { const prevQuery = __privateGet(this, _currentQuery); const prevOptions = this.options; const prevResult = __privateGet(this, _currentResult); const prevResultState = __privateGet(this, _currentResultState); const prevResultOptions = __privateGet(this, _currentResultOptions); const queryChange = query !== prevQuery; const queryInitialState = queryChange ? query.state : __privateGet(this, _currentQueryInitialState); const { state } = query; let newState = { ...state }; let isPlaceholderData = false; let data; if (options._optimisticResults) { const mounted = this.hasListeners(); const fetchOnMount = !mounted && shouldFetchOnMount(query, options); const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions); if (fetchOnMount || fetchOptionally) { newState = { ...newState, ...fetchState(state.data, query.options) }; } if (options._optimisticResults === "isRestoring") { newState.fetchStatus = "idle"; } } let { error, errorUpdatedAt, status } = newState; if (options.select && newState.data !== void 0) { if (prevResult && newState.data === _optionalChain([prevResultState, 'optionalAccess', _26 => _26.data]) && options.select === __privateGet(this, _selectFn)) { data = __privateGet(this, _selectResult); } else { try { __privateSet(this, _selectFn, options.select); data = options.select(newState.data); data = replaceData(_optionalChain([prevResult, 'optionalAccess', _27 => _27.data]), data, options); __privateSet(this, _selectResult, data); __privateSet(this, _selectError, null); } catch (selectError) { __privateSet(this, _selectError, selectError); } } } else { data = newState.data; } if (options.placeholderData !== void 0 && data === void 0 && status === "pending") { let placeholderData; if (_optionalChain([prevResult, 'optionalAccess', _28 => _28.isPlaceholderData]) && options.placeholderData === _optionalChain([prevResultOptions, 'optionalAccess', _29 => _29.placeholderData])) { placeholderData = prevResult.data; } else { placeholderData = typeof options.placeholderData === "function" ? options.placeholderData( _optionalChain([__privateGet, 'call', _30 => _30(this, _lastQueryWithDefinedData), 'optionalAccess', _31 => _31.state, 'access', _32 => _32.data]), __privateGet(this, _lastQueryWithDefinedData) ) : options.placeholderData; if (options.select && placeholderData !== void 0) { try { placeholderData = options.select(placeholderData); __privateSet(this, _selectError, null); } catch (selectError) { __privateSet(this, _selectError, selectError); } } } if (placeholderData !== void 0) { status = "success"; data = replaceData( _optionalChain([prevResult, 'optionalAccess', _33 => _33.data]), placeholderData, options ); isPlaceholderData = true; } } if (__privateGet(this, _selectError)) { error = __privateGet(this, _selectError); data = __privateGet(this, _selectResult); errorUpdatedAt = Date.now(); status = "error"; } const isFetching = newState.fetchStatus === "fetching"; const isPending = status === "pending"; const isError = status === "error"; const isLoading = isPending && isFetching; const hasData = data !== void 0; const result = { status, fetchStatus: newState.fetchStatus, isPending, isSuccess: status === "success", isError, isInitialLoading: isLoading, isLoading, data, dataUpdatedAt: newState.dataUpdatedAt, error, errorUpdatedAt, failureCount: newState.fetchFailureCount, failureReason: newState.fetchFailureReason, errorUpdateCount: newState.errorUpdateCount, isFetched: newState.dataUpdateCount > 0 || newState.errorUpdateCount > 0, isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount, isFetching, isRefetching: isFetching && !isPending, isLoadingError: isError && !hasData, isPaused: newState.fetchStatus === "paused", isPlaceholderData, isRefetchError: isError && hasData, isStale: isStale(query, options), refetch: this.refetch, promise: __privateGet(this, _currentThenable) }; const nextResult = result; if (this.options.experimental_prefetchInRender) { const finalizeThenableIfPossible = (thenable) => { if (nextResult.status === "error") { thenable.reject(nextResult.error); } else if (nextResult.data !== void 0) { thenable.resolve(nextResult.data); } }; const recreateThenable = () => { const pending = __privateSet(this, _currentThenable, nextResult.promise = pendingThenable()); finalizeThenableIfPossible(pending); }; const prevThenable = __privateGet(this, _currentThenable); switch (prevThenable.status) { case "pending": if (query.queryHash === prevQuery.queryHash) { finalizeThenableIfPossible(prevThenable); } break; case "fulfilled": if (nextResult.status === "error" || nextResult.data !== prevThenable.value) { recreateThenable(); } break; case "rejected": if (nextResult.status !== "error" || nextResult.error !== prevThenable.reason) { recreateThenable(); } break; } } return nextResult; } updateResult(notifyOptions) { const prevResult = __privateGet(this, _currentResult); const nextResult = this.createResult(__privateGet(this, _currentQuery), this.options); __privateSet(this, _currentResultState, __privateGet(this, _currentQuery).state); __privateSet(this, _currentResultOptions, this.options); if (__privateGet(this, _currentResultState).data !== void 0) { __privateSet(this, _lastQueryWithDefinedData, __privateGet(this, _currentQuery)); } if (shallowEqualObjects(nextResult, prevResult)) { return; } __privateSet(this, _currentResult, nextResult); const defaultNotifyOptions = {}; const shouldNotifyListeners = () => { if (!prevResult) { return true; } const { notifyOnChangeProps } = this.options; const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps; if (notifyOnChangePropsValue === "all" || !notifyOnChangePropsValue && !__privateGet(this, _trackedProps).size) { return true; } const includedProps = new Set( _nullishCoalesce(notifyOnChangePropsValue, () => ( __privateGet(this, _trackedProps))) ); if (this.options.throwOnError) { includedProps.add("error"); } return Object.keys(__privateGet(this, _currentResult)).some((key) => { const typedKey = key; const changed = __privateGet(this, _currentResult)[typedKey] !== prevResult[typedKey]; return changed && includedProps.has(typedKey); }); }; if (_optionalChain([notifyOptions, 'optionalAccess', _34 => _34.listeners]) !== false && shouldNotifyListeners()) { defaultNotifyOptions.listeners = true; } __privateMethod(this, _QueryObserver_instances, notify_fn).call(this, { ...defaultNotifyOptions, ...notifyOptions }); } onQueryUpdate() { this.updateResult(); if (this.hasListeners()) { __privateMethod(this, _QueryObserver_instances, updateTimers_fn).call(this); } } }, _client = new WeakMap(), _currentQuery = new WeakMap(), _currentQueryInitialState = new WeakMap(), _currentResult = new WeakMap(), _currentResultState = new WeakMap(), _currentResultOptions = new WeakMap(), _currentThenable = new WeakMap(), _selectError = new WeakMap(), _selectFn = new WeakMap(), _selectResult = new WeakMap(), _lastQueryWithDefinedData = new WeakMap(), _staleTimeoutId = new WeakMap(), _refetchIntervalId = new WeakMap(), _currentRefetchInterval = new WeakMap(), _trackedProps = new WeakMap(), _QueryObserver_instances = new WeakSet(), executeFetch_fn = function(fetchOptions) { __privateMethod(this, _QueryObserver_instances, updateQuery_fn).call(this); let promise = __privateGet(this, _currentQuery).fetch( this.options, fetchOptions ); if (!_optionalChain([fetchOptions, 'optionalAccess', _35 => _35.throwOnError])) { promise = promise.catch(noop); } return promise; }, updateStaleTimeout_fn = function() { __privateMethod(this, _QueryObserver_instances, clearStaleTimeout_fn).call(this); const staleTime = resolveStaleTime( this.options.staleTime, __privateGet(this, _currentQuery) ); if (isServer || __privateGet(this, _currentResult).isStale || !isValidTimeout(staleTime)) { return; } const time = timeUntilStale(__privateGet(this, _currentResult).dataUpdatedAt, staleTime); const timeout = time + 1; __privateSet(this, _staleTimeoutId, setTimeout(() => { if (!__privateGet(this, _currentResult).isStale) { this.updateResult(); } }, timeout)); }, computeRefetchInterval_fn = function() { return _nullishCoalesce((typeof this.options.refetchInterval === "function" ? this.options.refetchInterval(__privateGet(this, _currentQuery)) : this.options.refetchInterval), () => ( false)); }, updateRefetchInterval_fn = function(nextInterval) { __privateMethod(this, _QueryObserver_instances, clearRefetchInterval_fn).call(this); __privateSet(this, _currentRefetchInterval, nextInterval); if (isServer || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) === false || !isValidTimeout(__privateGet(this, _currentRefetchInterval)) || __privateGet(this, _currentRefetchInterval) === 0) { return; } __privateSet(this, _refetchIntervalId, setInterval(() => { if (this.options.refetchIntervalInBackground || focusManager.isFocused()) { __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this); } }, __privateGet(this, _currentRefetchInterval))); }, updateTimers_fn = function() { __privateMethod(this, _QueryObserver_instances, updateStaleTimeout_fn).call(this); __privateMethod(this, _QueryObserver_instances, updateRefetchInterval_fn).call(this, __privateMethod(this, _QueryObserver_instances, computeRefetchInterval_fn).call(this)); }, clearStaleTimeout_fn = function() { if (__privateGet(this, _staleTimeoutId)) { clearTimeout(__privateGet(this, _staleTimeoutId)); __privateSet(this, _staleTimeoutId, void 0); } }, clearRefetchInterval_fn = function() { if (__privateGet(this, _refetchIntervalId)) { clearInterval(__privateGet(this, _refetchIntervalId)); __privateSet(this, _refetchIntervalId, void 0); } }, updateQuery_fn = function() { const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), this.options); if (query === __privateGet(this, _currentQuery)) { return; } const prevQuery = __privateGet(this, _currentQuery); __privateSet(this, _currentQuery, query); __privateSet(this, _currentQueryInitialState, query.state); if (this.hasListeners()) { _optionalChain([prevQuery, 'optionalAccess', _36 => _36.removeObserver, 'call', _37 => _37(this)]); query.addObserver(this); } }, notify_fn = function(notifyOptions) { notifyManager.batch(() => { if (notifyOptions.listeners) { this.listeners.forEach((listener) => { listener(__privateGet(this, _currentResult)); }); } __privateGet(this, _client).getQueryCache().notify({ query: __privateGet(this, _currentQuery), type: "observerResultsUpdated" }); }); }, _a3); function shouldLoadOnMount(query, options) { return resolveEnabled(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === "error" && options.retryOnMount === false); } function shouldFetchOnMount(query, options) { return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount); } function shouldFetchOn(query, options, field) { if (resolveEnabled(options.enabled, query) !== false) { const value = typeof field === "function" ? field(query) : field; return value === "always" || value !== false && isStale(query, options); } return false; } function shouldFetchOptionally(query, prevQuery, options, prevOptions) { return (query !== prevQuery || resolveEnabled(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options); } function isStale(query, options) { return resolveEnabled(options.enabled, query) !== false && query.isStaleByTime(resolveStaleTime(options.staleTime, query)); } function shouldAssignObserverCurrentProperties(observer, optimisticResult) { if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) { return true; } return false; } // ../../node_modules/@tanstack/query-core/build/modern/mutationObserver.js var _client2, _currentResult2, _currentMutation, _mutateOptions, _MutationObserver_instances, updateResult_fn, notify_fn2, _a4; var MutationObserver = (_a4 = class extends Subscribable { constructor(client, options) { super(); __privateAdd(this, _MutationObserver_instances); __privateAdd(this, _client2); __privateAdd(this, _currentResult2); __privateAdd(this, _currentMutation); __privateAdd(this, _mutateOptions); __privateSet(this, _client2, client); this.setOptions(options); this.bindMethods(); __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this); } bindMethods() { this.mutate = this.mutate.bind(this); this.reset = this.reset.bind(this); } setOptions(options) { const prevOptions = this.options; this.options = __privateGet(this, _client2).defaultMutationOptions(options); if (!shallowEqualObjects(this.options, prevOptions)) { __privateGet(this, _client2).getMutationCache().notify({ type: "observerOptionsUpdated", mutation: __privateGet(this, _currentMutation), observer: this }); } if (_optionalChain([prevOptions, 'optionalAccess', _38 => _38.mutationKey]) && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) { this.reset(); } else if (_optionalChain([__privateGet, 'call', _39 => _39(this, _currentMutation), 'optionalAccess', _40 => _40.state, 'access', _41 => _41.status]) === "pending") { __privateGet(this, _currentMutation).setOptions(this.options); } } onUnsubscribe() { if (!this.hasListeners()) { _optionalChain([__privateGet, 'call', _42 => _42(this, _currentMutation), 'optionalAccess', _43 => _43.removeObserver, 'call', _44 => _44(this)]); } } onMutationUpdate(action) { __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this); __privateMethod(this, _MutationObserver_instances, notify_fn2).call(this, action); } getCurrentResult() { return __privateGet(this, _currentResult2); } reset() { _optionalChain([__privateGet, 'call', _45 => _45(this, _currentMutation), 'optionalAccess', _46 => _46.removeObserver, 'call', _47 => _47(this)]); __privateSet(this, _currentMutation, void 0); __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this); __privateMethod(this, _MutationObserver_instances, notify_fn2).call(this); } mutate(variables, options) { __privateSet(this, _mutateOptions, options); _optionalChain([__privateGet, 'call', _48 => _48(this, _currentMutation), 'optionalAccess', _49 => _49.removeObserver, 'call', _50 => _50(this)]); __privateSet(this, _currentMutation, __privateGet(this, _client2).getMutationCache().build(__privateGet(this, _client2), this.options)); __privateGet(this, _currentMutation).addObserver(this); return __privateGet(this, _currentMutation).execute(variables); } }, _client2 = new WeakMap(), _currentResult2 = new WeakMap(), _currentMutation = new WeakMap(), _mutateOptions = new WeakMap(), _MutationObserver_instances = new WeakSet(), updateResult_fn = function() { const state = _nullishCoalesce(_optionalChain([__privateGet, 'call', _51 => _51(this, _currentMutation), 'optionalAccess', _52 => _52.state]), () => ( getDefaultState())); __privateSet(this, _currentResult2, { ...state, isPending: state.status === "pending", isSuccess: state.status === "success", isError: state.status === "error", isIdle: state.status === "idle", mutate: this.mutate, reset: this.reset }); }, notify_fn2 = function(action) { notifyManager.batch(() => { if (__privateGet(this, _mutateOptions) && this.hasListeners()) { const variables = __privateGet(this, _currentResult2).variables; const context = __privateGet(this, _currentResult2).context; if (_optionalChain([action, 'optionalAccess', _53 => _53.type]) === "success") { _optionalChain([__privateGet, 'call', _54 => _54(this, _mutateOptions), 'access', _55 => _55.onSuccess, 'optionalCall', _56 => _56(action.data, variables, context)]); _optionalChain([__privateGet, 'call', _57 => _57(this, _mutateOptions), 'access', _58 => _58.onSettled, 'optionalCall', _59 => _59(action.data, null, variables, context)]); } else if (_optionalChain([action, 'optionalAccess', _60 => _60.type]) === "error") { _optionalChain([__privateGet, 'call', _61 => _61(this, _mutateOptions), 'access', _62 => _62.onError, 'optionalCall', _63 => _63(action.error, variables, context)]); _optionalChain([__privateGet, 'call', _64 => _64(this, _mutateOptions), 'access', _65 => _65.onSettled, 'optionalCall', _66 => _66( void 0, action.error, variables, context )]); } } this.listeners.forEach((listener) => { listener(__privateGet(this, _currentResult2)); }); }); }, _a4); // ../../node_modules/@tanstack/react-query/build/modern/QueryClientProvider.js var _jsxruntime = require('react/jsx-runtime'); var QueryClientContext = React2.createContext( void 0 ); var useQueryClient = (queryClient) => { const client = React2.useContext(QueryClientContext); if (queryClient) { return queryClient; } if (!client) { throw new Error("No QueryClient set, use QueryClientProvider to set one"); } return client; }; // ../../node_modules/@tanstack/react-query/build/modern/isRestoring.js var IsRestoringContext = React3.createContext(false); var useIsRestoring = () => React3.useContext(IsRestoringContext); var IsRestoringProvider = IsRestoringContext.Provider; // ../../node_modules/@tanstack/react-query/build/modern/QueryErrorResetBoundary.js function createValue() { let isReset = false; return { clearReset: () => { isReset = false; }, reset: () => { isReset = true; }, isReset: () => { return isReset; } }; } var QueryErrorResetBoundaryContext = React4.createContext(createValue()); var useQueryErrorResetBoundary = () => React4.useContext(QueryErrorResetBoundaryContext); // ../../node_modules/@tanstack/react-query/build/modern/errorBoundaryUtils.js // ../../node_modules/@tanstack/react-query/build/modern/utils.js function shouldThrowError(throwError, params) { if (typeof throwError === "function") { return throwError(...params); } return !!throwError; } function noop2() { } // ../../node_modules/@tanstack/react-query/build/modern/errorBoundaryUtils.js var ensurePreventErrorBoundaryRetry = (options, errorResetBoundary) => { if (options.suspense || options.throwOnError || options.experimental_prefetchInRender) { if (!errorResetBoundary.isReset()) { options.retryOnMount = false; } } }; var useClearResetErrorBoundary = (errorResetBoundary) => { React5.useEffect(() => { errorResetBoundary.clearReset(); }, [errorResetBoundary]); }; var getHasError = ({ result, errorResetBoundary, throwOnError, query }) => { return result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && shouldThrowError(throwOnError, [result.error, query]); }; // ../../node_modules/@tanstack/react-query/build/modern/suspense.js var ensureSuspenseTimers = (defaultedOptions) => { const originalStaleTime = defaultedOptions.staleTime; if (defaultedOptions.suspense) { defaultedOptions.staleTime = typeof originalStaleTime === "function" ? (...args) => Math.max(originalStaleTime(...args), 1e3) : Math.max(_nullishCoalesce(originalStaleTime, () => ( 1e3)), 1e3); if (typeof defaultedOptions.gcTime === "number") { defaultedOptions.gcTime = Math.max(defaultedOptions.gcTime, 1e3); } } }; var willFetch = (result, isRestoring) => result.isLoading && result.isFetching && !isRestoring; var shouldSuspend = (defaultedOptions, result) => _optionalChain([defaultedOptions, 'optionalAccess', _67 => _67.suspense]) && result.isPending; var fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).catch(() => { errorResetBoundary.clearReset(); }); // ../../node_modules/@tanstack/react-query/build/modern/useBaseQuery.js function useBaseQuery(options, Observer, queryClient) { if (process.env.NODE_ENV !== "production") { if (typeof options !== "object" || Array.isArray(options)) { throw new Error( 'Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object' ); } } const client = useQueryClient(queryClient); const isRestoring = useIsRestoring(); const errorResetBoundary = useQueryErrorResetBoundary(); const defaultedOptions = client.defaultQueryOptions(options); _optionalChain([client, 'access', _68 => _68.getDefaultOptions, 'call', _69 => _69(), 'access', _70 => _70.queries, 'optionalAccess', _71 => _71._experimental_beforeQuery, 'optionalCall', _72 => _72( defaultedOptions )]); defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : "optimistic"; ensureSuspenseTimers(defaultedOptions); ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary); useClearResetErrorBoundary(errorResetBoundary); const isNewCacheEntry = !client.getQueryCache().get(defaultedOptions.queryHash); const [observer] = React6.useState( () => new Observer( client, defaultedOptions ) ); const result = observer.getOptimisticResult(defaultedOptions); const shouldSubscribe = !isRestoring && options.subscribed !== false; React6.useSyncExternalStore( React6.useCallback( (onStoreChange) => { const unsubscribe = shouldSubscribe ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) : no