@tanstack/query-core 5.52.3 → 5.53.1

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.
@@ -290,7 +290,12 @@ var Query = class extends import_removable.Removable {
290
290
  onError(new Error(`${this.queryHash} data is undefined`));
291
291
  return;
292
292
  }
293
- this.setData(data);
293
+ try {
294
+ this.setData(data);
295
+ } catch (error) {
296
+ onError(error);
297
+ return;
298
+ }
294
299
  (_b2 = (_a2 = __privateGet(this, _cache).config).onSuccess) == null ? void 0 : _b2.call(_a2, data, this);
295
300
  (_d = (_c2 = __privateGet(this, _cache).config).onSettled) == null ? void 0 : _d.call(
296
301
  _c2,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n noop,\n replaceData,\n resolveEnabled,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { canFetch, createRetryer, isCancelledError } from './retryer'\nimport { Removable } from './removable'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n} from './types'\nimport type { QueryCache } from './queryCache'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n cache: QueryCache\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state?: QueryState<TData, TError>\n}\n\nexport interface QueryState<TData = unknown, TError = DefaultError> {\n data: TData | undefined\n dataUpdateCount: number\n dataUpdatedAt: number\n error: TError | null\n errorUpdateCount: number\n errorUpdatedAt: number\n fetchFailureCount: number\n fetchFailureReason: TError | null\n fetchMeta: FetchMeta | null\n isInvalidated: boolean\n status: QueryStatus\n fetchStatus: FetchStatus\n}\n\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n fetchFn: () => unknown | Promise<unknown>\n fetchOptions?: FetchOptions\n signal: AbortSignal\n options: QueryOptions<TQueryFnData, TError, TData, any>\n queryKey: TQueryKey\n state: QueryState<TData, TError>\n}\n\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n onFetch: (\n context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n query: Query,\n ) => void\n}\n\nexport type FetchDirection = 'forward' | 'backward'\n\nexport interface FetchMeta {\n fetchMore?: { direction: FetchDirection }\n}\n\nexport interface FetchOptions<TData = unknown> {\n cancelRefetch?: boolean\n meta?: FetchMeta\n initialPromise?: Promise<TData>\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction<TData> {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction<TData, TError> {\n type: 'setState'\n state: Partial<QueryState<TData, TError>>\n setStateOptions?: SetStateOptions\n}\n\nexport type Action<TData, TError> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction<TData, TError>\n | SuccessAction<TData>\n\nexport interface SetStateOptions {\n meta?: any\n}\n\n// CLASS\n\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state: QueryState<TData, TError>\n isFetchingOptimistic?: boolean\n\n #initialState: QueryState<TData, TError>\n #revertState?: QueryState<TData, TError>\n #cache: QueryCache\n #retryer?: Retryer<TData>\n observers: Array<QueryObserver<any, any, any, any, any>>\n #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#cache = config.cache\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n get promise(): Promise<TData> | undefined {\n return this.#retryer?.promise\n }\n\n setOptions(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n this.updateGcTime(this.options.gcTime)\n }\n\n protected optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n setState(\n state: Partial<QueryState<TData, TError>>,\n setStateOptions?: SetStateOptions,\n ): void {\n this.#dispatch({ type: 'setState', state, setStateOptions })\n }\n\n cancel(options?: CancelOptions): Promise<void> {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n reset(): void {\n this.destroy()\n this.setState(this.#initialState)\n }\n\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveEnabled(observer.options.enabled, this) !== false,\n )\n }\n\n isDisabled(): boolean {\n return this.getObserversCount() > 0 && !this.isActive()\n }\n\n isStale(): boolean {\n if (this.state.isInvalidated) {\n return true\n }\n\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined\n }\n\n isStaleByTime(staleTime = 0): boolean {\n return (\n this.state.isInvalidated ||\n this.state.data === undefined ||\n !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n )\n }\n\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n addObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n removeObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (this.observers.includes(observer)) {\n this.observers = this.observers.filter((x) => x !== observer)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (this.#abortSignalConsumed) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n getObserversCount(): number {\n return this.observers.length\n }\n\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n fetch(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n fetchOptions?: FetchOptions<TQueryFnData>,\n ): Promise<TData> {\n if (this.state.fetchStatus !== 'idle') {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#retryer.promise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: unknown) => {\n Object.defineProperty(object, 'signal', {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<TQueryKey>,\n 'signal'\n > = {\n queryKey: this.queryKey,\n meta: this.meta,\n }\n\n addSignalProperty(queryFnContext)\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn as QueryFunction<any>,\n queryFnContext as QueryFunctionContext<TQueryKey>,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext as QueryFunctionContext<TQueryKey>)\n }\n\n // Trigger behavior hook\n const context: OmitKeyof<\n FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n\n this.options.behavior?.onFetch(\n context as FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n this as unknown as Query,\n )\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n const onError = (error: TError | { silent?: boolean }) => {\n // Optimistically update state if needed\n if (!(isCancelledError(error) && error.silent)) {\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n }\n\n if (!isCancelledError(error)) {\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query<any, any, any, any>,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query<any, any, any, any>,\n )\n }\n\n if (!this.isFetchingOptimistic) {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n this.isFetchingOptimistic = false\n }\n\n // Try to fetch the data\n this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise<TData>\n | undefined,\n fn: context.fetchFn as () => Promise<TData>,\n abort: abortController.abort.bind(abortController),\n onSuccess: (data) => {\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n onError(new Error(`${this.queryHash} data is undefined`) as any)\n return\n }\n\n this.setData(data)\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query<any, any, any, any>,\n )\n\n if (!this.isFetchingOptimistic) {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n this.isFetchingOptimistic = false\n },\n onError,\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n })\n\n return this.#retryer.start()\n }\n\n #dispatch(action: Action<TData, TError>): void {\n const reducer = (\n state: QueryState<TData, TError>,\n ): QueryState<TData, TError> => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success':\n return {\n ...state,\n data: action.data,\n dataUpdateCount: state.dataUpdateCount + 1,\n dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success',\n ...(!action.manual && {\n fetchStatus: 'idle',\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n case 'error':\n const error = action.error\n\n if (isCancelledError(error) && error.revert && this.#revertState) {\n return { ...this.#revertState, fetchStatus: 'idle' }\n }\n\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n this.observers.forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): QueryState<TData, TError> {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction<TData>)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? (options.initialDataUpdatedAt as () => number | undefined)()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? 'success' : 'pending',\n fetchStatus: 'idle',\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAMO;AACP,2BAA8B;AAC9B,qBAA0D;AAC1D,uBAA0B;AAT1B;AA0JO,IAAM,QAAN,cAKG,2BAAU;AAAA,EAelB,YAAY,QAA6D;AACvE,UAAM;AAyWR;AAlXA;AACA;AACA;AACA;AAEA;AACA;AAKE,uBAAK,sBAAuB;AAC5B,uBAAK,iBAAkB,OAAO;AAC9B,SAAK,WAAW,OAAO,OAAO;AAC9B,SAAK,YAAY,CAAC;AAClB,uBAAK,QAAS,OAAO;AACrB,SAAK,WAAW,OAAO;AACvB,SAAK,YAAY,OAAO;AACxB,uBAAK,eAAgB,gBAAgB,KAAK,OAAO;AACjD,SAAK,QAAQ,OAAO,SAAS,mBAAK;AAClC,S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,UAAU,YAAY;AAAA,IAC9B,aAAa;AAAA,EACf;AACF;","names":["_a","_b","_c"]}
1
+ {"version":3,"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n noop,\n replaceData,\n resolveEnabled,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { canFetch, createRetryer, isCancelledError } from './retryer'\nimport { Removable } from './removable'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n} from './types'\nimport type { QueryCache } from './queryCache'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n cache: QueryCache\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state?: QueryState<TData, TError>\n}\n\nexport interface QueryState<TData = unknown, TError = DefaultError> {\n data: TData | undefined\n dataUpdateCount: number\n dataUpdatedAt: number\n error: TError | null\n errorUpdateCount: number\n errorUpdatedAt: number\n fetchFailureCount: number\n fetchFailureReason: TError | null\n fetchMeta: FetchMeta | null\n isInvalidated: boolean\n status: QueryStatus\n fetchStatus: FetchStatus\n}\n\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n fetchFn: () => unknown | Promise<unknown>\n fetchOptions?: FetchOptions\n signal: AbortSignal\n options: QueryOptions<TQueryFnData, TError, TData, any>\n queryKey: TQueryKey\n state: QueryState<TData, TError>\n}\n\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n onFetch: (\n context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n query: Query,\n ) => void\n}\n\nexport type FetchDirection = 'forward' | 'backward'\n\nexport interface FetchMeta {\n fetchMore?: { direction: FetchDirection }\n}\n\nexport interface FetchOptions<TData = unknown> {\n cancelRefetch?: boolean\n meta?: FetchMeta\n initialPromise?: Promise<TData>\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction<TData> {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction<TData, TError> {\n type: 'setState'\n state: Partial<QueryState<TData, TError>>\n setStateOptions?: SetStateOptions\n}\n\nexport type Action<TData, TError> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction<TData, TError>\n | SuccessAction<TData>\n\nexport interface SetStateOptions {\n meta?: any\n}\n\n// CLASS\n\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state: QueryState<TData, TError>\n isFetchingOptimistic?: boolean\n\n #initialState: QueryState<TData, TError>\n #revertState?: QueryState<TData, TError>\n #cache: QueryCache\n #retryer?: Retryer<TData>\n observers: Array<QueryObserver<any, any, any, any, any>>\n #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#cache = config.cache\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n get promise(): Promise<TData> | undefined {\n return this.#retryer?.promise\n }\n\n setOptions(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n this.updateGcTime(this.options.gcTime)\n }\n\n protected optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n setState(\n state: Partial<QueryState<TData, TError>>,\n setStateOptions?: SetStateOptions,\n ): void {\n this.#dispatch({ type: 'setState', state, setStateOptions })\n }\n\n cancel(options?: CancelOptions): Promise<void> {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n reset(): void {\n this.destroy()\n this.setState(this.#initialState)\n }\n\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveEnabled(observer.options.enabled, this) !== false,\n )\n }\n\n isDisabled(): boolean {\n return this.getObserversCount() > 0 && !this.isActive()\n }\n\n isStale(): boolean {\n if (this.state.isInvalidated) {\n return true\n }\n\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined\n }\n\n isStaleByTime(staleTime = 0): boolean {\n return (\n this.state.isInvalidated ||\n this.state.data === undefined ||\n !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n )\n }\n\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n addObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n removeObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (this.observers.includes(observer)) {\n this.observers = this.observers.filter((x) => x !== observer)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (this.#abortSignalConsumed) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n getObserversCount(): number {\n return this.observers.length\n }\n\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n fetch(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n fetchOptions?: FetchOptions<TQueryFnData>,\n ): Promise<TData> {\n if (this.state.fetchStatus !== 'idle') {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#retryer.promise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: unknown) => {\n Object.defineProperty(object, 'signal', {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<TQueryKey>,\n 'signal'\n > = {\n queryKey: this.queryKey,\n meta: this.meta,\n }\n\n addSignalProperty(queryFnContext)\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn as QueryFunction<any>,\n queryFnContext as QueryFunctionContext<TQueryKey>,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext as QueryFunctionContext<TQueryKey>)\n }\n\n // Trigger behavior hook\n const context: OmitKeyof<\n FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n\n this.options.behavior?.onFetch(\n context as FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n this as unknown as Query,\n )\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n const onError = (error: TError | { silent?: boolean }) => {\n // Optimistically update state if needed\n if (!(isCancelledError(error) && error.silent)) {\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n }\n\n if (!isCancelledError(error)) {\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query<any, any, any, any>,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query<any, any, any, any>,\n )\n }\n\n if (!this.isFetchingOptimistic) {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n this.isFetchingOptimistic = false\n }\n\n // Try to fetch the data\n this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise<TData>\n | undefined,\n fn: context.fetchFn as () => Promise<TData>,\n abort: abortController.abort.bind(abortController),\n onSuccess: (data) => {\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n onError(new Error(`${this.queryHash} data is undefined`) as any)\n return\n }\n\n try {\n this.setData(data)\n } catch (error) {\n onError(error as TError)\n return\n }\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query<any, any, any, any>,\n )\n\n if (!this.isFetchingOptimistic) {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n this.isFetchingOptimistic = false\n },\n onError,\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n })\n\n return this.#retryer.start()\n }\n\n #dispatch(action: Action<TData, TError>): void {\n const reducer = (\n state: QueryState<TData, TError>,\n ): QueryState<TData, TError> => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success':\n return {\n ...state,\n data: action.data,\n dataUpdateCount: state.dataUpdateCount + 1,\n dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success',\n ...(!action.manual && {\n fetchStatus: 'idle',\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n case 'error':\n const error = action.error\n\n if (isCancelledError(error) && error.revert && this.#revertState) {\n return { ...this.#revertState, fetchStatus: 'idle' }\n }\n\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n this.observers.forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): QueryState<TData, TError> {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction<TData>)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? (options.initialDataUpdatedAt as () => number | undefined)()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? 'success' : 'pending',\n fetchStatus: 'idle',\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAMO;AACP,2BAA8B;AAC9B,qBAA0D;AAC1D,uBAA0B;AAT1B;AA0JO,IAAM,QAAN,cAKG,2BAAU;AAAA,EAelB,YAAY,QAA6D;AACvE,UAAM;AA8WR;AAvXA;AACA;AACA;AACA;AAEA;AACA;AAKE,uBAAK,sBAAuB;AAC5B,uBAAK,iBAAkB,OAAO;AAC9B,SAAK,WAAW,OAAO,OAAO;AAC9B,SAAK,YAAY,CAAC;AAClB,uBAAK,QAAS,OAAO;AACrB,SAAK,WAAW,OAAO;AACvB,SAAK,YAAY,OAAO;AACxB,uBAAK,eAAgB,gBAAgB,KAAK,OAAO;AACjD,SAAK,QAAQ,OAAO,SAAS,mBAAK;AAClC,SAAK,WAAW;AAAA,EAClB;AAAA,EACA,IAAI,OAA8B;AAChC,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EAEA,IAAI,UAAsC;AAhM5C;AAiMI,YAAO,wBAAK,cAAL,mBAAe;AAAA,EACxB;AAAA,EAEA,WACE,SACM;AACN,SAAK,UAAU,EAAE,GAAG,mBAAK,kBAAiB,GAAG,QAAQ;AAErD,SAAK,aAAa,KAAK,QAAQ,MAAM;AAAA,EACvC;AAAA,EAEU,iBAAiB;AACzB,QAAI,CAAC,KAAK,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A,UACH,GAAG,OAAO;AAAA,QACZ;AAAA,IACJ;AAAA,EACF;AAEA,OAAK,QAAQ,QAAQ,KAAK,KAAK;AAE/B,qCAAc,MAAM,MAAM;AACxB,SAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,eAAS,cAAc;AAAA,IACzB,CAAC;AAED,uBAAK,QAAO,OAAO,EAAE,OAAO,MAAM,MAAM,WAAW,OAAO,CAAC;AAAA,EAC7D,CAAC;AACH;AAGK,SAAS,WAMd,MACA,SACA;AACA,SAAO;AAAA,IACL,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,iBAAa,yBAAS,QAAQ,WAAW,IAAI,aAAa;AAAA,IAC1D,GAAI,SAAS,UACV;AAAA,MACC,OAAO;AAAA,MACP,QAAQ;AAAA,IACV;AAAA,EACJ;AACF;AAEA,SAAS,gBAMP,SAC2B;AAC3B,QAAM,OACJ,OAAO,QAAQ,gBAAgB,aAC1B,QAAQ,YAA2C,IACpD,QAAQ;AAEd,QAAM,UAAU,SAAS;AAEzB,QAAM,uBAAuB,UACzB,OAAO,QAAQ,yBAAyB,aACrC,QAAQ,qBAAkD,IAC3D,QAAQ,uBACV;AAEJ,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB;AAAA,IACjB,eAAe,UAAW,wBAAwB,KAAK,IAAI,IAAK;AAAA,IAChE,OAAO;AAAA,IACP,kBAAkB;AAAA,IAClB,gBAAgB;AAAA,IAChB,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,WAAW;AAAA,IACX,eAAe;AAAA,IACf,QAAQ,UAAU,YAAY;AAAA,IAC9B,aAAa;AAAA,EACf;AACF;","names":["_a","_b","_c"]}
@@ -256,7 +256,12 @@ var Query = class extends Removable {
256
256
  onError(new Error(`${this.queryHash} data is undefined`));
257
257
  return;
258
258
  }
259
- this.setData(data);
259
+ try {
260
+ this.setData(data);
261
+ } catch (error) {
262
+ onError(error);
263
+ return;
264
+ }
260
265
  (_b2 = (_a2 = __privateGet(this, _cache).config).onSuccess) == null ? void 0 : _b2.call(_a2, data, this);
261
266
  (_d = (_c2 = __privateGet(this, _cache).config).onSettled) == null ? void 0 : _d.call(
262
267
  _c2,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n noop,\n replaceData,\n resolveEnabled,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { canFetch, createRetryer, isCancelledError } from './retryer'\nimport { Removable } from './removable'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n} from './types'\nimport type { QueryCache } from './queryCache'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n cache: QueryCache\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state?: QueryState<TData, TError>\n}\n\nexport interface QueryState<TData = unknown, TError = DefaultError> {\n data: TData | undefined\n dataUpdateCount: number\n dataUpdatedAt: number\n error: TError | null\n errorUpdateCount: number\n errorUpdatedAt: number\n fetchFailureCount: number\n fetchFailureReason: TError | null\n fetchMeta: FetchMeta | null\n isInvalidated: boolean\n status: QueryStatus\n fetchStatus: FetchStatus\n}\n\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n fetchFn: () => unknown | Promise<unknown>\n fetchOptions?: FetchOptions\n signal: AbortSignal\n options: QueryOptions<TQueryFnData, TError, TData, any>\n queryKey: TQueryKey\n state: QueryState<TData, TError>\n}\n\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n onFetch: (\n context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n query: Query,\n ) => void\n}\n\nexport type FetchDirection = 'forward' | 'backward'\n\nexport interface FetchMeta {\n fetchMore?: { direction: FetchDirection }\n}\n\nexport interface FetchOptions<TData = unknown> {\n cancelRefetch?: boolean\n meta?: FetchMeta\n initialPromise?: Promise<TData>\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction<TData> {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction<TData, TError> {\n type: 'setState'\n state: Partial<QueryState<TData, TError>>\n setStateOptions?: SetStateOptions\n}\n\nexport type Action<TData, TError> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction<TData, TError>\n | SuccessAction<TData>\n\nexport interface SetStateOptions {\n meta?: any\n}\n\n// CLASS\n\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state: QueryState<TData, TError>\n isFetchingOptimistic?: boolean\n\n #initialState: QueryState<TData, TError>\n #revertState?: QueryState<TData, TError>\n #cache: QueryCache\n #retryer?: Retryer<TData>\n observers: Array<QueryObserver<any, any, any, any, any>>\n #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#cache = config.cache\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n get promise(): Promise<TData> | undefined {\n return this.#retryer?.promise\n }\n\n setOptions(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n this.updateGcTime(this.options.gcTime)\n }\n\n protected optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n setState(\n state: Partial<QueryState<TData, TError>>,\n setStateOptions?: SetStateOptions,\n ): void {\n this.#dispatch({ type: 'setState', state, setStateOptions })\n }\n\n cancel(options?: CancelOptions): Promise<void> {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n reset(): void {\n this.destroy()\n this.setState(this.#initialState)\n }\n\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveEnabled(observer.options.enabled, this) !== false,\n )\n }\n\n isDisabled(): boolean {\n return this.getObserversCount() > 0 && !this.isActive()\n }\n\n isStale(): boolean {\n if (this.state.isInvalidated) {\n return true\n }\n\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined\n }\n\n isStaleByTime(staleTime = 0): boolean {\n return (\n this.state.isInvalidated ||\n this.state.data === undefined ||\n !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n )\n }\n\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n addObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n removeObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (this.observers.includes(observer)) {\n this.observers = this.observers.filter((x) => x !== observer)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (this.#abortSignalConsumed) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n getObserversCount(): number {\n return this.observers.length\n }\n\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n fetch(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n fetchOptions?: FetchOptions<TQueryFnData>,\n ): Promise<TData> {\n if (this.state.fetchStatus !== 'idle') {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#retryer.promise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: unknown) => {\n Object.defineProperty(object, 'signal', {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<TQueryKey>,\n 'signal'\n > = {\n queryKey: this.queryKey,\n meta: this.meta,\n }\n\n addSignalProperty(queryFnContext)\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn as QueryFunction<any>,\n queryFnContext as QueryFunctionContext<TQueryKey>,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext as QueryFunctionContext<TQueryKey>)\n }\n\n // Trigger behavior hook\n const context: OmitKeyof<\n FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n\n this.options.behavior?.onFetch(\n context as FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n this as unknown as Query,\n )\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n const onError = (error: TError | { silent?: boolean }) => {\n // Optimistically update state if needed\n if (!(isCancelledError(error) && error.silent)) {\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n }\n\n if (!isCancelledError(error)) {\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query<any, any, any, any>,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query<any, any, any, any>,\n )\n }\n\n if (!this.isFetchingOptimistic) {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n this.isFetchingOptimistic = false\n }\n\n // Try to fetch the data\n this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise<TData>\n | undefined,\n fn: context.fetchFn as () => Promise<TData>,\n abort: abortController.abort.bind(abortController),\n onSuccess: (data) => {\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n onError(new Error(`${this.queryHash} data is undefined`) as any)\n return\n }\n\n this.setData(data)\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query<any, any, any, any>,\n )\n\n if (!this.isFetchingOptimistic) {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n this.isFetchingOptimistic = false\n },\n onError,\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n })\n\n return this.#retryer.start()\n }\n\n #dispatch(action: Action<TData, TError>): void {\n const reducer = (\n state: QueryState<TData, TError>,\n ): QueryState<TData, TError> => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success':\n return {\n ...state,\n data: action.data,\n dataUpdateCount: state.dataUpdateCount + 1,\n dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success',\n ...(!action.manual && {\n fetchStatus: 'idle',\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n case 'error':\n const error = action.error\n\n if (isCancelledError(error) && error.revert && this.#revertState) {\n return { ...this.#revertState, fetchStatus: 'idle' }\n }\n\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n this.observers.forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): QueryState<TData, TError> {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction<TData>)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? (options.initialDataUpdatedAt as () => number | undefined)()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? 'success' : 'pending',\n fetchStatus: 'idle',\n }\n}\n"],"mappings":";;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB;AAC9B,SAAS,UAAU,eAAe,wBAAwB;AAC1D,SAAS,iBAAiB;AAT1B;AA0JO,IAAM,QAAN,cAKG,UAAU;AAAA,EAelB,YAAY,QAA6D;AACvE,UAAM;AAyWR;AAlXA;AACA;AACA;AACA;AAEA;AACA;AAKE,uBAAK,sBAAuB;AAC5B,uBAAK,iBAAkB,OAAO;AAC9B,SAAK,WAAW,OAAO,OAAO;AAC9B,SAAK,YAAY,CAAC;AAClB,uBAAK,QAAS,OAAO;AACrB,SAAK,WAAW,OAAO;AACvB,SAAK,YAAY,OAAO;AACxB,uBAAK,eAAgB,gBAAgB,KAAK,OAAO;AACjD,SAAK,QAAQ,OAAO,SAAS,mBAAK;AAClC,SAAK,WAAW;AAAA,EAClB;AAAA,EACA,IAAI,OAA8B;AAChC,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EAEA,IAAI,UAAsC;AAhM5C;AAiMI,YAAO,wBAAK,cAAL,mBAAe;AAAA,EACxB;AAAA,EAEA,WACE,SACM;AACN,SAAK,UAAU,EAAE,GAAG,mBAAK,kBAAiB,GAAG,QAAQ;AAErD,SAAK,aAAa,KAAK,QAAQ,MAAM;AAAA,EACvC;AAAA,EAEU,i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ACF;AAEA,OAAK,QAAQ,QAAQ,KAAK,KAAK;AAE/B,gBAAc,MAAM,MAAM;AACxB,SAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,eAAS,cAAc;AAAA,IACzB,CAAC;AAED,uBAAK,QAAO,OAAO,EAAE,OAAO,MAAM,MAAM,WAAW,OAAO,CAAC;AAAA,EAC7D,CAAC;AACH;AAGK,SAAS,WAMd,MACA,SACA;AACA,SAAO;AAAA,IACL,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,aAAa,SAAS,QAAQ,WAAW,IAAI,aAAa;AAAA,IAC1D,GAAI,SAAS,UACV;AAAA,MACC,OAAO;AAAA,MACP,QAAQ;AAAA,IACV;AAAA,EACJ;AACF;AAEA,SAAS,gBAMP,SAC2B;AAC3B,QAAM,OACJ,OAAO,QAAQ,gBAAgB,aAC1B,QAAQ,YAA2C,IACpD,QAAQ;AAEd,QAAM,UAAU,SAAS;AAEzB,QAAM,uBAAuB,UACzB,OAAO,QAAQ,yBAAyB,aACrC,QAAQ,qBAAkD,IAC3D,QAAQ,uBACV;AAEJ,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB;AAAA,IACjB,eAAe,UAAW,wBAAwB,KAAK,IAAI,IAAK;AAAA,IAChE,OAAO;AAAA,IACP,kBAAkB;AAAA,IAClB,gBAAgB;AAAA,IAChB,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,WAAW;AAAA,IACX,eAAe;AAAA,IACf,QAAQ,UAAU,YAAY;AAAA,IAC9B,aAAa;AAAA,EACf;AACF;","names":["_a","_b","_c"]}
1
+ {"version":3,"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n noop,\n replaceData,\n resolveEnabled,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { canFetch, createRetryer, isCancelledError } from './retryer'\nimport { Removable } from './removable'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n} from './types'\nimport type { QueryCache } from './queryCache'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n cache: QueryCache\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state?: QueryState<TData, TError>\n}\n\nexport interface QueryState<TData = unknown, TError = DefaultError> {\n data: TData | undefined\n dataUpdateCount: number\n dataUpdatedAt: number\n error: TError | null\n errorUpdateCount: number\n errorUpdatedAt: number\n fetchFailureCount: number\n fetchFailureReason: TError | null\n fetchMeta: FetchMeta | null\n isInvalidated: boolean\n status: QueryStatus\n fetchStatus: FetchStatus\n}\n\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n fetchFn: () => unknown | Promise<unknown>\n fetchOptions?: FetchOptions\n signal: AbortSignal\n options: QueryOptions<TQueryFnData, TError, TData, any>\n queryKey: TQueryKey\n state: QueryState<TData, TError>\n}\n\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n onFetch: (\n context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n query: Query,\n ) => void\n}\n\nexport type FetchDirection = 'forward' | 'backward'\n\nexport interface FetchMeta {\n fetchMore?: { direction: FetchDirection }\n}\n\nexport interface FetchOptions<TData = unknown> {\n cancelRefetch?: boolean\n meta?: FetchMeta\n initialPromise?: Promise<TData>\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction<TData> {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction<TData, TError> {\n type: 'setState'\n state: Partial<QueryState<TData, TError>>\n setStateOptions?: SetStateOptions\n}\n\nexport type Action<TData, TError> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction<TData, TError>\n | SuccessAction<TData>\n\nexport interface SetStateOptions {\n meta?: any\n}\n\n// CLASS\n\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state: QueryState<TData, TError>\n isFetchingOptimistic?: boolean\n\n #initialState: QueryState<TData, TError>\n #revertState?: QueryState<TData, TError>\n #cache: QueryCache\n #retryer?: Retryer<TData>\n observers: Array<QueryObserver<any, any, any, any, any>>\n #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#cache = config.cache\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n get promise(): Promise<TData> | undefined {\n return this.#retryer?.promise\n }\n\n setOptions(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n this.updateGcTime(this.options.gcTime)\n }\n\n protected optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n setState(\n state: Partial<QueryState<TData, TError>>,\n setStateOptions?: SetStateOptions,\n ): void {\n this.#dispatch({ type: 'setState', state, setStateOptions })\n }\n\n cancel(options?: CancelOptions): Promise<void> {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n reset(): void {\n this.destroy()\n this.setState(this.#initialState)\n }\n\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveEnabled(observer.options.enabled, this) !== false,\n )\n }\n\n isDisabled(): boolean {\n return this.getObserversCount() > 0 && !this.isActive()\n }\n\n isStale(): boolean {\n if (this.state.isInvalidated) {\n return true\n }\n\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined\n }\n\n isStaleByTime(staleTime = 0): boolean {\n return (\n this.state.isInvalidated ||\n this.state.data === undefined ||\n !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n )\n }\n\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n addObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n removeObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (this.observers.includes(observer)) {\n this.observers = this.observers.filter((x) => x !== observer)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (this.#abortSignalConsumed) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n getObserversCount(): number {\n return this.observers.length\n }\n\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n fetch(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n fetchOptions?: FetchOptions<TQueryFnData>,\n ): Promise<TData> {\n if (this.state.fetchStatus !== 'idle') {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#retryer.promise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: unknown) => {\n Object.defineProperty(object, 'signal', {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<TQueryKey>,\n 'signal'\n > = {\n queryKey: this.queryKey,\n meta: this.meta,\n }\n\n addSignalProperty(queryFnContext)\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn as QueryFunction<any>,\n queryFnContext as QueryFunctionContext<TQueryKey>,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext as QueryFunctionContext<TQueryKey>)\n }\n\n // Trigger behavior hook\n const context: OmitKeyof<\n FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n\n this.options.behavior?.onFetch(\n context as FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n this as unknown as Query,\n )\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n const onError = (error: TError | { silent?: boolean }) => {\n // Optimistically update state if needed\n if (!(isCancelledError(error) && error.silent)) {\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n }\n\n if (!isCancelledError(error)) {\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query<any, any, any, any>,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query<any, any, any, any>,\n )\n }\n\n if (!this.isFetchingOptimistic) {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n this.isFetchingOptimistic = false\n }\n\n // Try to fetch the data\n this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise<TData>\n | undefined,\n fn: context.fetchFn as () => Promise<TData>,\n abort: abortController.abort.bind(abortController),\n onSuccess: (data) => {\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n onError(new Error(`${this.queryHash} data is undefined`) as any)\n return\n }\n\n try {\n this.setData(data)\n } catch (error) {\n onError(error as TError)\n return\n }\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query<any, any, any, any>,\n )\n\n if (!this.isFetchingOptimistic) {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n this.isFetchingOptimistic = false\n },\n onError,\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n })\n\n return this.#retryer.start()\n }\n\n #dispatch(action: Action<TData, TError>): void {\n const reducer = (\n state: QueryState<TData, TError>,\n ): QueryState<TData, TError> => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success':\n return {\n ...state,\n data: action.data,\n dataUpdateCount: state.dataUpdateCount + 1,\n dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success',\n ...(!action.manual && {\n fetchStatus: 'idle',\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n case 'error':\n const error = action.error\n\n if (isCancelledError(error) && error.revert && this.#revertState) {\n return { ...this.#revertState, fetchStatus: 'idle' }\n }\n\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n this.observers.forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): QueryState<TData, TError> {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction<TData>)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? (options.initialDataUpdatedAt as () => number | undefined)()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData 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;AAAA,IACL,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,aAAa,SAAS,QAAQ,WAAW,IAAI,aAAa;AAAA,IAC1D,GAAI,SAAS,UACV;AAAA,MACC,OAAO;AAAA,MACP,QAAQ;AAAA,IACV;AAAA,EACJ;AACF;AAEA,SAAS,gBAMP,SAC2B;AAC3B,QAAM,OACJ,OAAO,QAAQ,gBAAgB,aAC1B,QAAQ,YAA2C,IACpD,QAAQ;AAEd,QAAM,UAAU,SAAS;AAEzB,QAAM,uBAAuB,UACzB,OAAO,QAAQ,yBAAyB,aACrC,QAAQ,qBAAkD,IAC3D,QAAQ,uBACV;AAEJ,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB;AAAA,IACjB,eAAe,UAAW,wBAAwB,KAAK,IAAI,IAAK;AAAA,IAChE,OAAO;AAAA,IACP,kBAAkB;AAAA,IAClB,gBAAgB;AAAA,IAChB,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,WAAW;AAAA,IACX,eAAe;AAAA,IACf,QAAQ,UAAU,YAAY;AAAA,IAC9B,aAAa;AAAA,EACf;AACF;","names":["_a","_b","_c"]}
@@ -223,6 +223,17 @@ function replaceData(prevData, data, options) {
223
223
  if (typeof options.structuralSharing === "function") {
224
224
  return options.structuralSharing(prevData, data);
225
225
  } else if (options.structuralSharing !== false) {
226
+ if (process.env.NODE_ENV !== "production") {
227
+ try {
228
+ JSON.stringify(prevData);
229
+ JSON.stringify(data);
230
+ } catch (error) {
231
+ console.error(
232
+ `StructuralSharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`
233
+ );
234
+ throw new Error("Data is not serializable");
235
+ }
236
+ }
226
237
  return replaceEqualDeep(prevData, data);
227
238
  }
228
239
  return data;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["import type {\n DefaultError,\n Enabled,\n FetchStatus,\n MutationKey,\n MutationStatus,\n QueryFunction,\n QueryKey,\n QueryOptions,\n StaleTime,\n} from './types'\nimport type { Mutation } from './mutation'\nimport type { FetchOptions, Query } from './query'\n\n// TYPES\n\nexport interface QueryFilters {\n /**\n * Filter to active queries, inactive queries or all queries\n */\n type?: QueryTypeFilter\n /**\n * Match query key exactly\n */\n exact?: boolean\n /**\n * Include queries matching this predicate function\n */\n predicate?: (query: Query) => boolean\n /**\n * Include queries matching this query key\n */\n queryKey?: QueryKey\n /**\n * Include or exclude stale queries\n */\n stale?: boolean\n /**\n * Include queries matching their fetchStatus\n */\n fetchStatus?: FetchStatus\n}\n\nexport interface MutationFilters {\n /**\n * Match mutation key exactly\n */\n exact?: boolean\n /**\n * Include mutations matching this predicate function\n */\n predicate?: (mutation: Mutation<any, any, any>) => boolean\n /**\n * Include mutations matching this mutation key\n */\n mutationKey?: MutationKey\n /**\n * Filter by mutation status\n */\n status?: MutationStatus\n}\n\nexport type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)\n\nexport type QueryTypeFilter = 'all' | 'active' | 'inactive'\n\n// UTILS\n\nexport const isServer = typeof window === 'undefined' || 'Deno' in globalThis\n\nexport function noop(): undefined {\n return undefined\n}\n\nexport function functionalUpdate<TInput, TOutput>(\n updater: Updater<TInput, TOutput>,\n input: TInput,\n): TOutput {\n return typeof updater === 'function'\n ? (updater as (_: TInput) => TOutput)(input)\n : updater\n}\n\nexport function isValidTimeout(value: unknown): value is number {\n return typeof value === 'number' && value >= 0 && value !== Infinity\n}\n\nexport function timeUntilStale(updatedAt: number, staleTime?: number): number {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)\n}\n\nexport function resolveStaleTime<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n staleTime: undefined | StaleTime<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): number | undefined {\n return typeof staleTime === 'function' ? staleTime(query) : staleTime\n}\n\nexport function resolveEnabled<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n enabled: undefined | Enabled<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): boolean | undefined {\n return typeof enabled === 'function' ? enabled(query) : enabled\n}\n\nexport function matchQuery(\n filters: QueryFilters,\n query: Query<any, any, any, any>,\n): boolean {\n const {\n type = 'all',\n exact,\n fetchStatus,\n predicate,\n queryKey,\n stale,\n } = filters\n\n if (queryKey) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false\n }\n }\n\n if (type !== 'all') {\n const isActive = query.isActive()\n if (type === 'active' && !isActive) {\n return false\n }\n if (type === 'inactive' && isActive) {\n return false\n }\n }\n\n if (typeof stale === 'boolean' && query.isStale() !== stale) {\n return false\n }\n\n if (fetchStatus && fetchStatus !== query.state.fetchStatus) {\n return false\n }\n\n if (predicate && !predicate(query)) {\n return false\n }\n\n return true\n}\n\nexport function matchMutation(\n filters: MutationFilters,\n mutation: Mutation<any, any>,\n): boolean {\n const { exact, status, predicate, mutationKey } = filters\n if (mutationKey) {\n if (!mutation.options.mutationKey) {\n return false\n }\n if (exact) {\n if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {\n return false\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false\n }\n }\n\n if (status && mutation.state.status !== status) {\n return false\n }\n\n if (predicate && !predicate(mutation)) {\n return false\n }\n\n return true\n}\n\nexport function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(\n queryKey: TQueryKey,\n options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,\n): string {\n const hashFn = options?.queryKeyHashFn || hashKey\n return hashFn(queryKey)\n}\n\n/**\n * Default query & mutation keys hash function.\n * Hashes the value into a stable hash.\n */\nexport function hashKey(queryKey: QueryKey | MutationKey): string {\n return JSON.stringify(queryKey, (_, val) =>\n isPlainObject(val)\n ? Object.keys(val)\n .sort()\n .reduce((result, key) => {\n result[key] = val[key]\n return result\n }, {} as any)\n : val,\n )\n}\n\n/**\n * Checks if key `b` partially matches with key `a`.\n */\nexport function partialMatchKey(a: QueryKey, b: QueryKey): boolean\nexport function partialMatchKey(a: any, b: any): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n return !Object.keys(b).some((key) => !partialMatchKey(a[key], b[key]))\n }\n\n return false\n}\n\n/**\n * This function returns `a` if `b` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between JSON values for example.\n */\nexport function replaceEqualDeep<T>(a: unknown, b: T): T\nexport function replaceEqualDeep(a: any, b: any): any {\n if (a === b) {\n return a\n }\n\n const array = isPlainArray(a) && isPlainArray(b)\n\n if (array || (isPlainObject(a) && isPlainObject(b))) {\n const aItems = array ? a : Object.keys(a)\n const aSize = aItems.length\n const bItems = array ? b : Object.keys(b)\n const bSize = bItems.length\n const copy: any = array ? [] : {}\n\n let equalItems = 0\n\n for (let i = 0; i < bSize; i++) {\n const key = array ? i : bItems[i]\n if (\n ((!array && aItems.includes(key)) || array) &&\n a[key] === undefined &&\n b[key] === undefined\n ) {\n copy[key] = undefined\n equalItems++\n } else {\n copy[key] = replaceEqualDeep(a[key], b[key])\n if (copy[key] === a[key] && a[key] !== undefined) {\n equalItems++\n }\n }\n }\n\n return aSize === bSize && equalItems === aSize ? a : copy\n }\n\n return b\n}\n\n/**\n * Shallow compare objects.\n */\nexport function shallowEqualObjects<T extends Record<string, any>>(\n a: T,\n b: T | undefined,\n): boolean {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false\n }\n\n for (const key in a) {\n if (a[key] !== b[key]) {\n return false\n }\n }\n\n return true\n}\n\nexport function isPlainArray(value: unknown) {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\nexport function isPlainObject(o: any): o is Object {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has no constructor\n const ctor = o.constructor\n if (ctor === undefined) {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Handles Objects created by Object.create(<arbitrary prototype>)\n if (Object.getPrototypeOf(o) !== Object.prototype) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\nexport function sleep(timeout: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, timeout)\n })\n}\n\nexport function replaceData<\n TData,\n TOptions extends QueryOptions<any, any, any, any>,\n>(prevData: TData | undefined, data: TData, options: TOptions): TData {\n if (typeof options.structuralSharing === 'function') {\n return options.structuralSharing(prevData, data) as TData\n } else if (options.structuralSharing !== false) {\n // Structurally share data between prev and new data if needed\n return replaceEqualDeep(prevData, data)\n }\n return data\n}\n\nexport function keepPreviousData<T>(\n previousData: T | undefined,\n): T | undefined {\n return previousData\n}\n\nexport function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [...items, item]\n return max && newItems.length > max ? newItems.slice(1) : newItems\n}\n\nexport function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [item, ...items]\n return max && newItems.length > max ? newItems.slice(0, -1) : newItems\n}\n\nexport const skipToken = Symbol()\nexport type SkipToken = typeof skipToken\n\nexport function ensureQueryFn<\n TQueryFnData = unknown,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: {\n queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken\n queryHash?: string\n },\n fetchOptions?: FetchOptions<TQueryFnData>,\n): QueryFunction<TQueryFnData, TQueryKey> {\n if (process.env.NODE_ENV !== 'production') {\n if (options.queryFn === skipToken) {\n console.error(\n `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,\n )\n }\n }\n\n // if we attempt to retry a fetch that was triggered from an initialPromise\n // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise\n // if an observer has already mounted, we will be able to retry with that queryFn\n if (!options.queryFn && fetchOptions?.initialPromise) {\n return () => fetchOptions.initialPromise!\n }\n\n if (!options.queryFn || options.queryFn === skipToken) {\n return () =>\n Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))\n }\n\n return options.queryFn\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoEO,IAAM,WAAW,OAAO,WAAW,eAAe,UAAU;AAE5D,SAAS,OAAkB;AAChC,SAAO;AACT;AAEO,SAAS,iBACd,SACA,OACS;AACT,SAAO,OAAO,YAAY,aACrB,QAAmC,KAAK,IACzC;AACN;AAEO,SAAS,eAAe,OAAiC;AAC9D,SAAO,OAAO,UAAU,YAAY,SAAS,KAAK,UAAU;AAC9D;AAEO,SAAS,eAAe,WAAmB,WAA4B;AAC5E,SAAO,KAAK,IAAI,aAAa,aAAa,KAAK,KAAK,IAAI,GAAG,CAAC;AAC9D;AAEO,SAAS,iBAMd,WACA,OACoB;AACpB,SAAO,OAAO,cAAc,aAAa,UAAU,KAAK,IAAI;AAC9D;AAEO,SAAS,eAMd,SACA,OACqB;AACrB,SAAO,OAAO,YAAY,aAAa,QAAQ,KAAK,IAAI;AAC1D;AAEO,SAAS,WACd,SACA,OACS;AACT,QAAM;AAAA,IACJ,OAAO;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IACA;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d,UAA6B,MAAa,SAA0B;AACpE,MAAI,OAAO,QAAQ,sBAAsB,YAAY;AACnD,WAAO,QAAQ,kBAAkB,UAAU,IAAI;AAAA,EACjD,WAAW,QAAQ,sBAAsB,OAAO;AAE9C,WAAO,iBAAiB,UAAU,IAAI;AAAA,EACxC;AACA,SAAO;AACT;AAEO,SAAS,iBACd,cACe;AACf,SAAO;AACT;AAEO,SAAS,SAAY,OAAiB,MAAS,MAAM,GAAa;AACvE,QAAM,WAAW,CAAC,GAAG,OAAO,IAAI;AAChC,SAAO,OAAO,SAAS,SAAS,MAAM,SAAS,MAAM,CAAC,IAAI;AAC5D;AAEO,SAAS,WAAc,OAAiB,MAAS,MAAM,GAAa;AACzE,QAAM,WAAW,CAAC,MAAM,GAAG,KAAK;AAChC,SAAO,OAAO,SAAS,SAAS,MAAM,SAAS,MAAM,GAAG,EAAE,IAAI;AAChE;AAEO,IAAM,YAAY,OAAO;AAGzB,SAAS,cAId,SAIA,cACwC;AACxC,MAAI,QAAQ,IAAI,aAAa,cAAc;AACzC,QAAI,QAAQ,YAAY,WAAW;AACjC,cAAQ;AAAA,QACN,yGAAyG,QAAQ,SAAS;AAAA,MAC5H;AAAA,IACF;AAAA,EACF;AAKA,MAAI,CAAC,QAAQ,YAAW,6CAAc,iBAAgB;AACpD,WAAO,MAAM,aAAa;AAAA,EAC5B;AAEA,MAAI,CAAC,QAAQ,WAAW,QAAQ,YAAY,WAAW;AACrD,WAAO,MACL,QAAQ,OAAO,IAAI,MAAM,qBAAqB,QAAQ,SAAS,GAAG,CAAC;AAAA,EACvE;AAEA,SAAO,QAAQ;AACjB;","names":[]}
1
+ {"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["import type {\n DefaultError,\n Enabled,\n FetchStatus,\n MutationKey,\n MutationStatus,\n QueryFunction,\n QueryKey,\n QueryOptions,\n StaleTime,\n} from './types'\nimport type { Mutation } from './mutation'\nimport type { FetchOptions, Query } from './query'\n\n// TYPES\n\nexport interface QueryFilters {\n /**\n * Filter to active queries, inactive queries or all queries\n */\n type?: QueryTypeFilter\n /**\n * Match query key exactly\n */\n exact?: boolean\n /**\n * Include queries matching this predicate function\n */\n predicate?: (query: Query) => boolean\n /**\n * Include queries matching this query key\n */\n queryKey?: QueryKey\n /**\n * Include or exclude stale queries\n */\n stale?: boolean\n /**\n * Include queries matching their fetchStatus\n */\n fetchStatus?: FetchStatus\n}\n\nexport interface MutationFilters {\n /**\n * Match mutation key exactly\n */\n exact?: boolean\n /**\n * Include mutations matching this predicate function\n */\n predicate?: (mutation: Mutation<any, any, any>) => boolean\n /**\n * Include mutations matching this mutation key\n */\n mutationKey?: MutationKey\n /**\n * Filter by mutation status\n */\n status?: MutationStatus\n}\n\nexport type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)\n\nexport type QueryTypeFilter = 'all' | 'active' | 'inactive'\n\n// UTILS\n\nexport const isServer = typeof window === 'undefined' || 'Deno' in globalThis\n\nexport function noop(): undefined {\n return undefined\n}\n\nexport function functionalUpdate<TInput, TOutput>(\n updater: Updater<TInput, TOutput>,\n input: TInput,\n): TOutput {\n return typeof updater === 'function'\n ? (updater as (_: TInput) => TOutput)(input)\n : updater\n}\n\nexport function isValidTimeout(value: unknown): value is number {\n return typeof value === 'number' && value >= 0 && value !== Infinity\n}\n\nexport function timeUntilStale(updatedAt: number, staleTime?: number): number {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)\n}\n\nexport function resolveStaleTime<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n staleTime: undefined | StaleTime<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): number | undefined {\n return typeof staleTime === 'function' ? staleTime(query) : staleTime\n}\n\nexport function resolveEnabled<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n enabled: undefined | Enabled<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): boolean | undefined {\n return typeof enabled === 'function' ? enabled(query) : enabled\n}\n\nexport function matchQuery(\n filters: QueryFilters,\n query: Query<any, any, any, any>,\n): boolean {\n const {\n type = 'all',\n exact,\n fetchStatus,\n predicate,\n queryKey,\n stale,\n } = filters\n\n if (queryKey) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false\n }\n }\n\n if (type !== 'all') {\n const isActive = query.isActive()\n if (type === 'active' && !isActive) {\n return false\n }\n if (type === 'inactive' && isActive) {\n return false\n }\n }\n\n if (typeof stale === 'boolean' && query.isStale() !== stale) {\n return false\n }\n\n if (fetchStatus && fetchStatus !== query.state.fetchStatus) {\n return false\n }\n\n if (predicate && !predicate(query)) {\n return false\n }\n\n return true\n}\n\nexport function matchMutation(\n filters: MutationFilters,\n mutation: Mutation<any, any>,\n): boolean {\n const { exact, status, predicate, mutationKey } = filters\n if (mutationKey) {\n if (!mutation.options.mutationKey) {\n return false\n }\n if (exact) {\n if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {\n return false\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false\n }\n }\n\n if (status && mutation.state.status !== status) {\n return false\n }\n\n if (predicate && !predicate(mutation)) {\n return false\n }\n\n return true\n}\n\nexport function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(\n queryKey: TQueryKey,\n options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,\n): string {\n const hashFn = options?.queryKeyHashFn || hashKey\n return hashFn(queryKey)\n}\n\n/**\n * Default query & mutation keys hash function.\n * Hashes the value into a stable hash.\n */\nexport function hashKey(queryKey: QueryKey | MutationKey): string {\n return JSON.stringify(queryKey, (_, val) =>\n isPlainObject(val)\n ? Object.keys(val)\n .sort()\n .reduce((result, key) => {\n result[key] = val[key]\n return result\n }, {} as any)\n : val,\n )\n}\n\n/**\n * Checks if key `b` partially matches with key `a`.\n */\nexport function partialMatchKey(a: QueryKey, b: QueryKey): boolean\nexport function partialMatchKey(a: any, b: any): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n return !Object.keys(b).some((key) => !partialMatchKey(a[key], b[key]))\n }\n\n return false\n}\n\n/**\n * This function returns `a` if `b` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between JSON values for example.\n */\nexport function replaceEqualDeep<T>(a: unknown, b: T): T\nexport function replaceEqualDeep(a: any, b: any): any {\n if (a === b) {\n return a\n }\n\n const array = isPlainArray(a) && isPlainArray(b)\n\n if (array || (isPlainObject(a) && isPlainObject(b))) {\n const aItems = array ? a : Object.keys(a)\n const aSize = aItems.length\n const bItems = array ? b : Object.keys(b)\n const bSize = bItems.length\n const copy: any = array ? [] : {}\n\n let equalItems = 0\n\n for (let i = 0; i < bSize; i++) {\n const key = array ? i : bItems[i]\n if (\n ((!array && aItems.includes(key)) || array) &&\n a[key] === undefined &&\n b[key] === undefined\n ) {\n copy[key] = undefined\n equalItems++\n } else {\n copy[key] = replaceEqualDeep(a[key], b[key])\n if (copy[key] === a[key] && a[key] !== undefined) {\n equalItems++\n }\n }\n }\n\n return aSize === bSize && equalItems === aSize ? a : copy\n }\n\n return b\n}\n\n/**\n * Shallow compare objects.\n */\nexport function shallowEqualObjects<T extends Record<string, any>>(\n a: T,\n b: T | undefined,\n): boolean {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false\n }\n\n for (const key in a) {\n if (a[key] !== b[key]) {\n return false\n }\n }\n\n return true\n}\n\nexport function isPlainArray(value: unknown) {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\nexport function isPlainObject(o: any): o is Object {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has no constructor\n const ctor = o.constructor\n if (ctor === undefined) {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Handles Objects created by Object.create(<arbitrary prototype>)\n if (Object.getPrototypeOf(o) !== Object.prototype) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\nexport function sleep(timeout: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, timeout)\n })\n}\n\nexport function replaceData<\n TData,\n TOptions extends QueryOptions<any, any, any, any>,\n>(prevData: TData | undefined, data: TData, options: TOptions): TData {\n if (typeof options.structuralSharing === 'function') {\n return options.structuralSharing(prevData, data) as TData\n } else if (options.structuralSharing !== false) {\n if (process.env.NODE_ENV !== 'production') {\n try {\n JSON.stringify(prevData)\n JSON.stringify(data)\n } catch (error) {\n console.error(\n `StructuralSharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`,\n )\n\n throw new Error('Data is not serializable')\n }\n }\n\n // Structurally share data between prev and new data if needed\n return replaceEqualDeep(prevData, data)\n }\n return data\n}\n\nexport function keepPreviousData<T>(\n previousData: T | undefined,\n): T | undefined {\n return previousData\n}\n\nexport function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [...items, item]\n return max && newItems.length > max ? newItems.slice(1) : newItems\n}\n\nexport function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [item, ...items]\n return max && newItems.length > max ? newItems.slice(0, -1) : newItems\n}\n\nexport const skipToken = Symbol()\nexport type SkipToken = typeof skipToken\n\nexport function ensureQueryFn<\n TQueryFnData = unknown,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: {\n queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken\n queryHash?: string\n },\n fetchOptions?: FetchOptions<TQueryFnData>,\n): QueryFunction<TQueryFnData, TQueryKey> {\n if (process.env.NODE_ENV !== 'production') {\n if (options.queryFn === skipToken) {\n console.error(\n `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,\n )\n }\n }\n\n // if we attempt to retry a fetch that was triggered from an initialPromise\n // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise\n // if an observer has already mounted, we will be able to retry with that queryFn\n if (!options.queryFn && fetchOptions?.initialPromise) {\n return () => fetchOptions.initialPromise!\n }\n\n if (!options.queryFn || options.queryFn === skipToken) {\n return () =>\n Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))\n }\n\n return options.queryFn\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoEO,IAAM,WAAW,OAAO,WAAW,eAAe,UAAU;AAE5D,SAAS,OAAkB;AAChC,SAAO;AACT;AAEO,SAAS,iBACd,SACA,OACS;AACT,SAAO,OAAO,YAAY,aACrB,QAAmC,KAAK,IACzC;AACN;AAEO,SAAS,eAAe,OAAiC;AAC9D,SAAO,OAAO,UAAU,YAAY,SAAS,KAAK,UAAU;AAC9D;AAEO,SAAS,eAAe,WAAmB,WAA4B;AAC5E,SAAO,KAAK,IAAI,aAAa,aAAa,KAAK,KAAK,IAAI,GAAG,CAAC;AAC9D;AAEO,SAAS,iBAMd,WACA,OACoB;AACpB,SAAO,OAAO,cAAc,aAAa,UAAU,KAAK,IAAI;AAC9D;AAEO,SAAS,eAMd,SACA,OACqB;AACrB,SAAO,OAAO,YAAY,aAAa,QAAQ,KAAK,IAAI;AAC1D;AAEO,SAAS,W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AAO,MACL,QAAQ,OAAO,IAAI,MAAM,qBAAqB,QAAQ,SAAS,GAAG,CAAC;AAAA,EACvE;AAEA,SAAO,QAAQ;AACjB;","names":[]}
@@ -179,6 +179,17 @@ function replaceData(prevData, data, options) {
179
179
  if (typeof options.structuralSharing === "function") {
180
180
  return options.structuralSharing(prevData, data);
181
181
  } else if (options.structuralSharing !== false) {
182
+ if (process.env.NODE_ENV !== "production") {
183
+ try {
184
+ JSON.stringify(prevData);
185
+ JSON.stringify(data);
186
+ } catch (error) {
187
+ console.error(
188
+ `StructuralSharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`
189
+ );
190
+ throw new Error("Data is not serializable");
191
+ }
192
+ }
182
193
  return replaceEqualDeep(prevData, data);
183
194
  }
184
195
  return data;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["import type {\n DefaultError,\n Enabled,\n FetchStatus,\n MutationKey,\n MutationStatus,\n QueryFunction,\n QueryKey,\n QueryOptions,\n StaleTime,\n} from './types'\nimport type { Mutation } from './mutation'\nimport type { FetchOptions, Query } from './query'\n\n// TYPES\n\nexport interface QueryFilters {\n /**\n * Filter to active queries, inactive queries or all queries\n */\n type?: QueryTypeFilter\n /**\n * Match query key exactly\n */\n exact?: boolean\n /**\n * Include queries matching this predicate function\n */\n predicate?: (query: Query) => boolean\n /**\n * Include queries matching this query key\n */\n queryKey?: QueryKey\n /**\n * Include or exclude stale queries\n */\n stale?: boolean\n /**\n * Include queries matching their fetchStatus\n */\n fetchStatus?: FetchStatus\n}\n\nexport interface MutationFilters {\n /**\n * Match mutation key exactly\n */\n exact?: boolean\n /**\n * Include mutations matching this predicate function\n */\n predicate?: (mutation: Mutation<any, any, any>) => boolean\n /**\n * Include mutations matching this mutation key\n */\n mutationKey?: MutationKey\n /**\n * Filter by mutation status\n */\n status?: MutationStatus\n}\n\nexport type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)\n\nexport type QueryTypeFilter = 'all' | 'active' | 'inactive'\n\n// UTILS\n\nexport const isServer = typeof window === 'undefined' || 'Deno' in globalThis\n\nexport function noop(): undefined {\n return undefined\n}\n\nexport function functionalUpdate<TInput, TOutput>(\n updater: Updater<TInput, TOutput>,\n input: TInput,\n): TOutput {\n return typeof updater === 'function'\n ? (updater as (_: TInput) => TOutput)(input)\n : updater\n}\n\nexport function isValidTimeout(value: unknown): value is number {\n return typeof value === 'number' && value >= 0 && value !== Infinity\n}\n\nexport function timeUntilStale(updatedAt: number, staleTime?: number): number {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)\n}\n\nexport function resolveStaleTime<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n staleTime: undefined | StaleTime<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): number | undefined {\n return typeof staleTime === 'function' ? staleTime(query) : staleTime\n}\n\nexport function resolveEnabled<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n enabled: undefined | Enabled<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): boolean | undefined {\n return typeof enabled === 'function' ? enabled(query) : enabled\n}\n\nexport function matchQuery(\n filters: QueryFilters,\n query: Query<any, any, any, any>,\n): boolean {\n const {\n type = 'all',\n exact,\n fetchStatus,\n predicate,\n queryKey,\n stale,\n } = filters\n\n if (queryKey) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false\n }\n }\n\n if (type !== 'all') {\n const isActive = query.isActive()\n if (type === 'active' && !isActive) {\n return false\n }\n if (type === 'inactive' && isActive) {\n return false\n }\n }\n\n if (typeof stale === 'boolean' && query.isStale() !== stale) {\n return false\n }\n\n if (fetchStatus && fetchStatus !== query.state.fetchStatus) {\n return false\n }\n\n if (predicate && !predicate(query)) {\n return false\n }\n\n return true\n}\n\nexport function matchMutation(\n filters: MutationFilters,\n mutation: Mutation<any, any>,\n): boolean {\n const { exact, status, predicate, mutationKey } = filters\n if (mutationKey) {\n if (!mutation.options.mutationKey) {\n return false\n }\n if (exact) {\n if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {\n return false\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false\n }\n }\n\n if (status && mutation.state.status !== status) {\n return false\n }\n\n if (predicate && !predicate(mutation)) {\n return false\n }\n\n return true\n}\n\nexport function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(\n queryKey: TQueryKey,\n options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,\n): string {\n const hashFn = options?.queryKeyHashFn || hashKey\n return hashFn(queryKey)\n}\n\n/**\n * Default query & mutation keys hash function.\n * Hashes the value into a stable hash.\n */\nexport function hashKey(queryKey: QueryKey | MutationKey): string {\n return JSON.stringify(queryKey, (_, val) =>\n isPlainObject(val)\n ? Object.keys(val)\n .sort()\n .reduce((result, key) => {\n result[key] = val[key]\n return result\n }, {} as any)\n : val,\n )\n}\n\n/**\n * Checks if key `b` partially matches with key `a`.\n */\nexport function partialMatchKey(a: QueryKey, b: QueryKey): boolean\nexport function partialMatchKey(a: any, b: any): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n return !Object.keys(b).some((key) => !partialMatchKey(a[key], b[key]))\n }\n\n return false\n}\n\n/**\n * This function returns `a` if `b` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between JSON values for example.\n */\nexport function replaceEqualDeep<T>(a: unknown, b: T): T\nexport function replaceEqualDeep(a: any, b: any): any {\n if (a === b) {\n return a\n }\n\n const array = isPlainArray(a) && isPlainArray(b)\n\n if (array || (isPlainObject(a) && isPlainObject(b))) {\n const aItems = array ? a : Object.keys(a)\n const aSize = aItems.length\n const bItems = array ? b : Object.keys(b)\n const bSize = bItems.length\n const copy: any = array ? [] : {}\n\n let equalItems = 0\n\n for (let i = 0; i < bSize; i++) {\n const key = array ? i : bItems[i]\n if (\n ((!array && aItems.includes(key)) || array) &&\n a[key] === undefined &&\n b[key] === undefined\n ) {\n copy[key] = undefined\n equalItems++\n } else {\n copy[key] = replaceEqualDeep(a[key], b[key])\n if (copy[key] === a[key] && a[key] !== undefined) {\n equalItems++\n }\n }\n }\n\n return aSize === bSize && equalItems === aSize ? a : copy\n }\n\n return b\n}\n\n/**\n * Shallow compare objects.\n */\nexport function shallowEqualObjects<T extends Record<string, any>>(\n a: T,\n b: T | undefined,\n): boolean {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false\n }\n\n for (const key in a) {\n if (a[key] !== b[key]) {\n return false\n }\n }\n\n return true\n}\n\nexport function isPlainArray(value: unknown) {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\nexport function isPlainObject(o: any): o is Object {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has no constructor\n const ctor = o.constructor\n if (ctor === undefined) {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Handles Objects created by Object.create(<arbitrary prototype>)\n if (Object.getPrototypeOf(o) !== Object.prototype) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\nexport function sleep(timeout: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, timeout)\n })\n}\n\nexport function replaceData<\n TData,\n TOptions extends QueryOptions<any, any, any, any>,\n>(prevData: TData | undefined, data: TData, options: TOptions): TData {\n if (typeof options.structuralSharing === 'function') {\n return options.structuralSharing(prevData, data) as TData\n } else if (options.structuralSharing !== false) {\n // Structurally share data between prev and new data if needed\n return replaceEqualDeep(prevData, data)\n }\n return data\n}\n\nexport function keepPreviousData<T>(\n previousData: T | undefined,\n): T | undefined {\n return previousData\n}\n\nexport function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [...items, item]\n return max && newItems.length > max ? newItems.slice(1) : newItems\n}\n\nexport function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [item, ...items]\n return max && newItems.length > max ? newItems.slice(0, -1) : newItems\n}\n\nexport const skipToken = Symbol()\nexport type SkipToken = typeof skipToken\n\nexport function ensureQueryFn<\n TQueryFnData = unknown,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: {\n queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken\n queryHash?: string\n },\n fetchOptions?: FetchOptions<TQueryFnData>,\n): QueryFunction<TQueryFnData, TQueryKey> {\n if (process.env.NODE_ENV !== 'production') {\n if (options.queryFn === skipToken) {\n console.error(\n `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,\n )\n }\n }\n\n // if we attempt to retry a fetch that was triggered from an initialPromise\n // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise\n // if an observer has already mounted, we will be able to retry with that queryFn\n if (!options.queryFn && fetchOptions?.initialPromise) {\n return () => fetchOptions.initialPromise!\n }\n\n if (!options.queryFn || options.queryFn === skipToken) {\n return () =>\n Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))\n }\n\n return options.queryFn\n}\n"],"mappings":";;;AAoEO,IAAM,WAAW,OAAO,WAAW,eAAe,UAAU;AAE5D,SAAS,OAAkB;AAChC,SAAO;AACT;AAEO,SAAS,iBACd,SACA,OACS;AACT,SAAO,OAAO,YAAY,aACrB,QAAmC,KAAK,IACzC;AACN;AAEO,S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YAAW,6CAAc,iBAAgB;AACpD,WAAO,MAAM,aAAa;AAAA,EAC5B;AAEA,MAAI,CAAC,QAAQ,WAAW,QAAQ,YAAY,WAAW;AACrD,WAAO,MACL,QAAQ,OAAO,IAAI,MAAM,qBAAqB,QAAQ,SAAS,GAAG,CAAC;AAAA,EACvE;AAEA,SAAO,QAAQ;AACjB;","names":[]}
1
+ {"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["import type {\n DefaultError,\n Enabled,\n FetchStatus,\n MutationKey,\n MutationStatus,\n QueryFunction,\n QueryKey,\n QueryOptions,\n StaleTime,\n} from './types'\nimport type { Mutation } from './mutation'\nimport type { FetchOptions, Query } from './query'\n\n// TYPES\n\nexport interface QueryFilters {\n /**\n * Filter to active queries, inactive queries or all queries\n */\n type?: QueryTypeFilter\n /**\n * Match query key exactly\n */\n exact?: boolean\n /**\n * Include queries matching this predicate function\n */\n predicate?: (query: Query) => boolean\n /**\n * Include queries matching this query key\n */\n queryKey?: QueryKey\n /**\n * Include or exclude stale queries\n */\n stale?: boolean\n /**\n * Include queries matching their fetchStatus\n */\n fetchStatus?: FetchStatus\n}\n\nexport interface MutationFilters {\n /**\n * Match mutation key exactly\n */\n exact?: boolean\n /**\n * Include mutations matching this predicate function\n */\n predicate?: (mutation: Mutation<any, any, any>) => boolean\n /**\n * Include mutations matching this mutation key\n */\n mutationKey?: MutationKey\n /**\n * Filter by mutation status\n */\n status?: MutationStatus\n}\n\nexport type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)\n\nexport type QueryTypeFilter = 'all' | 'active' | 'inactive'\n\n// UTILS\n\nexport const isServer = typeof window === 'undefined' || 'Deno' in globalThis\n\nexport function noop(): undefined {\n return undefined\n}\n\nexport function functionalUpdate<TInput, TOutput>(\n updater: Updater<TInput, TOutput>,\n input: TInput,\n): TOutput {\n return typeof updater === 'function'\n ? (updater as (_: TInput) => TOutput)(input)\n : updater\n}\n\nexport function isValidTimeout(value: unknown): value is number {\n return typeof value === 'number' && value >= 0 && value !== Infinity\n}\n\nexport function timeUntilStale(updatedAt: number, staleTime?: number): number {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)\n}\n\nexport function resolveStaleTime<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n staleTime: undefined | StaleTime<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): number | undefined {\n return typeof staleTime === 'function' ? staleTime(query) : staleTime\n}\n\nexport function resolveEnabled<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n enabled: undefined | Enabled<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): boolean | undefined {\n return typeof enabled === 'function' ? enabled(query) : enabled\n}\n\nexport function matchQuery(\n filters: QueryFilters,\n query: Query<any, any, any, any>,\n): boolean {\n const {\n type = 'all',\n exact,\n fetchStatus,\n predicate,\n queryKey,\n stale,\n } = filters\n\n if (queryKey) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false\n }\n }\n\n if (type !== 'all') {\n const isActive = query.isActive()\n if (type === 'active' && !isActive) {\n return false\n }\n if (type === 'inactive' && isActive) {\n return false\n }\n }\n\n if (typeof stale === 'boolean' && query.isStale() !== stale) {\n return false\n }\n\n if (fetchStatus && fetchStatus !== query.state.fetchStatus) {\n return false\n }\n\n if (predicate && !predicate(query)) {\n return false\n }\n\n return true\n}\n\nexport function matchMutation(\n filters: MutationFilters,\n mutation: Mutation<any, any>,\n): boolean {\n const { exact, status, predicate, mutationKey } = filters\n if (mutationKey) {\n if (!mutation.options.mutationKey) {\n return false\n }\n if (exact) {\n if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {\n return false\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false\n }\n }\n\n if (status && mutation.state.status !== status) {\n return false\n }\n\n if (predicate && !predicate(mutation)) {\n return false\n }\n\n return true\n}\n\nexport function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(\n queryKey: TQueryKey,\n options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,\n): string {\n const hashFn = options?.queryKeyHashFn || hashKey\n return hashFn(queryKey)\n}\n\n/**\n * Default query & mutation keys hash function.\n * Hashes the value into a stable hash.\n */\nexport function hashKey(queryKey: QueryKey | MutationKey): string {\n return JSON.stringify(queryKey, (_, val) =>\n isPlainObject(val)\n ? Object.keys(val)\n .sort()\n .reduce((result, key) => {\n result[key] = val[key]\n return result\n }, {} as any)\n : val,\n )\n}\n\n/**\n * Checks if key `b` partially matches with key `a`.\n */\nexport function partialMatchKey(a: QueryKey, b: QueryKey): boolean\nexport function partialMatchKey(a: any, b: any): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n return !Object.keys(b).some((key) => !partialMatchKey(a[key], b[key]))\n }\n\n return false\n}\n\n/**\n * This function returns `a` if `b` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between JSON values for example.\n */\nexport function replaceEqualDeep<T>(a: unknown, b: T): T\nexport function replaceEqualDeep(a: any, b: any): any {\n if (a === b) {\n return a\n }\n\n const array = isPlainArray(a) && isPlainArray(b)\n\n if (array || (isPlainObject(a) && isPlainObject(b))) {\n const aItems = array ? a : Object.keys(a)\n const aSize = aItems.length\n const bItems = array ? b : Object.keys(b)\n const bSize = bItems.length\n const copy: any = array ? [] : {}\n\n let equalItems = 0\n\n for (let i = 0; i < bSize; i++) {\n const key = array ? i : bItems[i]\n if (\n ((!array && aItems.includes(key)) || array) &&\n a[key] === undefined &&\n b[key] === undefined\n ) {\n copy[key] = undefined\n equalItems++\n } else {\n copy[key] = replaceEqualDeep(a[key], b[key])\n if (copy[key] === a[key] && a[key] !== undefined) {\n equalItems++\n }\n }\n }\n\n return aSize === bSize && equalItems === aSize ? a : copy\n }\n\n return b\n}\n\n/**\n * Shallow compare objects.\n */\nexport function shallowEqualObjects<T extends Record<string, any>>(\n a: T,\n b: T | undefined,\n): boolean {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false\n }\n\n for (const key in a) {\n if (a[key] !== b[key]) {\n return false\n }\n }\n\n return true\n}\n\nexport function isPlainArray(value: unknown) {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\nexport function isPlainObject(o: any): o is Object {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has no constructor\n const ctor = o.constructor\n if (ctor === undefined) {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Handles Objects created by Object.create(<arbitrary prototype>)\n if (Object.getPrototypeOf(o) !== Object.prototype) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\nexport function sleep(timeout: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, timeout)\n })\n}\n\nexport function replaceData<\n TData,\n TOptions extends QueryOptions<any, any, any, any>,\n>(prevData: TData | undefined, data: TData, options: TOptions): TData {\n if (typeof options.structuralSharing === 'function') {\n return options.structuralSharing(prevData, data) as TData\n } else if (options.structuralSharing !== false) {\n if (process.env.NODE_ENV !== 'production') {\n try {\n JSON.stringify(prevData)\n JSON.stringify(data)\n } catch (error) {\n console.error(\n `StructuralSharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`,\n )\n\n throw new Error('Data is not serializable')\n }\n }\n\n // Structurally share data between prev and new data if needed\n return replaceEqualDeep(prevData, data)\n }\n return data\n}\n\nexport function keepPreviousData<T>(\n previousData: T | undefined,\n): T | undefined {\n return previousData\n}\n\nexport function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [...items, item]\n return max && newItems.length > max ? newItems.slice(1) : newItems\n}\n\nexport function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [item, ...items]\n return max && newItems.length > max ? newItems.slice(0, -1) : newItems\n}\n\nexport const skipToken = Symbol()\nexport type SkipToken = typeof skipToken\n\nexport function ensureQueryFn<\n TQueryFnData = unknown,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: {\n queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken\n queryHash?: string\n },\n fetchOptions?: FetchOptions<TQueryFnData>,\n): QueryFunction<TQueryFnData, TQueryKey> {\n if (process.env.NODE_ENV !== 'production') {\n if (options.queryFn === skipToken) {\n console.error(\n `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,\n )\n }\n }\n\n // if we attempt to retry a fetch that was triggered from an initialPromise\n // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise\n // if an observer has already mounted, we will be able to retry with that queryFn\n if (!options.queryFn && fetchOptions?.initialPromise) {\n return () => fetchOptions.initialPromise!\n }\n\n if (!options.queryFn || options.queryFn === skipToken) {\n return () =>\n Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))\n }\n\n return options.queryFn\n}\n"],"mappings":";;;AAoEO,IAAM,WAAW,OAAO,WAAW,eAAe,UAAU;AAE5D,SAAS,OAAkB;AAChC,SAAO;AACT;AAEO,SAAS,iBACd,SACA,OACS;AACT,SAAO,OAAO,YAAY,aACrB,QAAmC,KAAK,IACzC;AACN;AAEO,SAAS,eAAe,OAAiC;AAC9D,SAAO,OAAO,UAAU,YAAY,SAAS,KAAK,UAAU;AAC9D;AAEO,SAAS,eAAe,WAAm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I,aAAa,cAAc;AACzC,QAAI,QAAQ,YAAY,WAAW;AACjC,cAAQ;AAAA,QACN,yGAAyG,QAAQ,SAAS;AAAA,MAC5H;AAAA,IACF;AAAA,EACF;AAKA,MAAI,CAAC,QAAQ,YAAW,6CAAc,iBAAgB;AACpD,WAAO,MAAM,aAAa;AAAA,EAC5B;AAEA,MAAI,CAAC,QAAQ,WAAW,QAAQ,YAAY,WAAW;AACrD,WAAO,MACL,QAAQ,OAAO,IAAI,MAAM,qBAAqB,QAAQ,SAAS,GAAG,CAAC;AAAA,EACvE;AAEA,SAAO,QAAQ;AACjB;","names":[]}
@@ -257,7 +257,12 @@ var Query = class extends import_removable.Removable {
257
257
  onError(new Error(`${this.queryHash} data is undefined`));
258
258
  return;
259
259
  }
260
- this.setData(data);
260
+ try {
261
+ this.setData(data);
262
+ } catch (error) {
263
+ onError(error);
264
+ return;
265
+ }
261
266
  this.#cache.config.onSuccess?.(data, this);
262
267
  this.#cache.config.onSettled?.(
263
268
  data,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n noop,\n replaceData,\n resolveEnabled,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { canFetch, createRetryer, isCancelledError } from './retryer'\nimport { Removable } from './removable'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n} from './types'\nimport type { QueryCache } from './queryCache'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n cache: QueryCache\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state?: QueryState<TData, TError>\n}\n\nexport interface QueryState<TData = unknown, TError = DefaultError> {\n data: TData | undefined\n dataUpdateCount: number\n dataUpdatedAt: number\n error: TError | null\n errorUpdateCount: number\n errorUpdatedAt: number\n fetchFailureCount: number\n fetchFailureReason: TError | null\n fetchMeta: FetchMeta | null\n isInvalidated: boolean\n status: QueryStatus\n fetchStatus: FetchStatus\n}\n\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n fetchFn: () => unknown | Promise<unknown>\n fetchOptions?: FetchOptions\n signal: AbortSignal\n options: QueryOptions<TQueryFnData, TError, TData, any>\n queryKey: TQueryKey\n state: QueryState<TData, TError>\n}\n\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n onFetch: (\n context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n query: Query,\n ) => void\n}\n\nexport type FetchDirection = 'forward' | 'backward'\n\nexport interface FetchMeta {\n fetchMore?: { direction: FetchDirection }\n}\n\nexport interface FetchOptions<TData = unknown> {\n cancelRefetch?: boolean\n meta?: FetchMeta\n initialPromise?: Promise<TData>\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction<TData> {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction<TData, TError> {\n type: 'setState'\n state: Partial<QueryState<TData, TError>>\n setStateOptions?: SetStateOptions\n}\n\nexport type Action<TData, TError> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction<TData, TError>\n | SuccessAction<TData>\n\nexport interface SetStateOptions {\n meta?: any\n}\n\n// CLASS\n\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state: QueryState<TData, TError>\n isFetchingOptimistic?: boolean\n\n #initialState: QueryState<TData, TError>\n #revertState?: QueryState<TData, TError>\n #cache: QueryCache\n #retryer?: Retryer<TData>\n observers: Array<QueryObserver<any, any, any, any, any>>\n #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#cache = config.cache\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n get promise(): Promise<TData> | undefined {\n return this.#retryer?.promise\n }\n\n setOptions(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n this.updateGcTime(this.options.gcTime)\n }\n\n protected optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n setState(\n state: Partial<QueryState<TData, TError>>,\n setStateOptions?: SetStateOptions,\n ): void {\n this.#dispatch({ type: 'setState', state, setStateOptions })\n }\n\n cancel(options?: CancelOptions): Promise<void> {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n reset(): void {\n this.destroy()\n this.setState(this.#initialState)\n }\n\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveEnabled(observer.options.enabled, this) !== false,\n )\n }\n\n isDisabled(): boolean {\n return this.getObserversCount() > 0 && !this.isActive()\n }\n\n isStale(): boolean {\n if (this.state.isInvalidated) {\n return true\n }\n\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined\n }\n\n isStaleByTime(staleTime = 0): boolean {\n return (\n this.state.isInvalidated ||\n this.state.data === undefined ||\n !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n )\n }\n\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n addObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n removeObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (this.observers.includes(observer)) {\n this.observers = this.observers.filter((x) => x !== observer)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (this.#abortSignalConsumed) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n getObserversCount(): number {\n return this.observers.length\n }\n\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n fetch(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n fetchOptions?: FetchOptions<TQueryFnData>,\n ): Promise<TData> {\n if (this.state.fetchStatus !== 'idle') {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#retryer.promise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: unknown) => {\n Object.defineProperty(object, 'signal', {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<TQueryKey>,\n 'signal'\n > = {\n queryKey: this.queryKey,\n meta: this.meta,\n }\n\n addSignalProperty(queryFnContext)\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn as QueryFunction<any>,\n queryFnContext as QueryFunctionContext<TQueryKey>,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext as QueryFunctionContext<TQueryKey>)\n }\n\n // Trigger behavior hook\n const context: OmitKeyof<\n FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n\n this.options.behavior?.onFetch(\n context as FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n this as unknown as Query,\n )\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n const onError = (error: TError | { silent?: boolean }) => {\n // Optimistically update state if needed\n if (!(isCancelledError(error) && error.silent)) {\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n }\n\n if (!isCancelledError(error)) {\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query<any, any, any, any>,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query<any, any, any, any>,\n )\n }\n\n if (!this.isFetchingOptimistic) {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n this.isFetchingOptimistic = false\n }\n\n // Try to fetch the data\n this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise<TData>\n | undefined,\n fn: context.fetchFn as () => Promise<TData>,\n abort: abortController.abort.bind(abortController),\n onSuccess: (data) => {\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n onError(new Error(`${this.queryHash} data is undefined`) as any)\n return\n }\n\n this.setData(data)\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query<any, any, any, any>,\n )\n\n if (!this.isFetchingOptimistic) {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n this.isFetchingOptimistic = false\n },\n onError,\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n })\n\n return this.#retryer.start()\n }\n\n #dispatch(action: Action<TData, TError>): void {\n const reducer = (\n state: QueryState<TData, TError>,\n ): QueryState<TData, TError> => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success':\n return {\n ...state,\n data: action.data,\n dataUpdateCount: state.dataUpdateCount + 1,\n dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success',\n ...(!action.manual && {\n fetchStatus: 'idle',\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n case 'error':\n const error = action.error\n\n if (isCancelledError(error) && error.revert && this.#revertState) {\n return { ...this.#revertState, fetchStatus: 'idle' }\n }\n\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n this.observers.forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): QueryState<TData, TError> {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction<TData>)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? (options.initialDataUpdatedAt as () => number | undefined)()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? 'success' : 'pending',\n fetchStatus: 'idle',\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAMO;AACP,2BAA8B;AAC9B,qBAA0D;AAC1D,uBAA0B;AAiJnB,IAAM,QAAN,cAKG,2BAAU;AAAA,EAOlB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EAEA,YAAY,QAA6D;AACvE,UAAM;AAEN,SAAK,uBAAuB;AAC5B,SAAK,kBAAkB,OAAO;AAC9B,SAAK,WAAW,OAAO,OAAO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jB;AAAA,QACF,KAAK;AACH,iBAAO;AAAA,YACL,GAAG;AAAA,YACH,GAAG,OAAO;AAAA,UACZ;AAAA,MACJ;AAAA,IACF;AAEA,SAAK,QAAQ,QAAQ,KAAK,KAAK;AAE/B,uCAAc,MAAM,MAAM;AACxB,WAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,iBAAS,cAAc;AAAA,MACzB,CAAC;AAED,WAAK,OAAO,OAAO,EAAE,OAAO,MAAM,MAAM,WAAW,OAAO,CAAC;AAAA,IAC7D,CAAC;AAAA,EACH;AACF;AAEO,SAAS,WAMd,MACA,SACA;AACA,SAAO;AAAA,IACL,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,iBAAa,yBAAS,QAAQ,WAAW,IAAI,aAAa;AAAA,IAC1D,GAAI,SAAS,UACV;AAAA,MACC,OAAO;AAAA,MACP,QAAQ;AAAA,IACV;AAAA,EACJ;AACF;AAEA,SAAS,gBAMP,SAC2B;AAC3B,QAAM,OACJ,OAAO,QAAQ,gBAAgB,aAC1B,QAAQ,YAA2C,IACpD,QAAQ;AAEd,QAAM,UAAU,SAAS;AAEzB,QAAM,uBAAuB,UACzB,OAAO,QAAQ,yBAAyB,aACrC,QAAQ,qBAAkD,IAC3D,QAAQ,uBACV;AAEJ,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB;AAAA,IACjB,eAAe,UAAW,wBAAwB,KAAK,IAAI,IAAK;AAAA,IAChE,OAAO;AAAA,IACP,kBAAkB;AAAA,IAClB,gBAAgB;AAAA,IAChB,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,WAAW;AAAA,IACX,eAAe;AAAA,IACf,QAAQ,UAAU,YAAY;AAAA,IAC9B,aAAa;AAAA,EACf;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n noop,\n replaceData,\n resolveEnabled,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { canFetch, createRetryer, isCancelledError } from './retryer'\nimport { Removable } from './removable'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n} from './types'\nimport type { QueryCache } from './queryCache'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n cache: QueryCache\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state?: QueryState<TData, TError>\n}\n\nexport interface QueryState<TData = unknown, TError = DefaultError> {\n data: TData | undefined\n dataUpdateCount: number\n dataUpdatedAt: number\n error: TError | null\n errorUpdateCount: number\n errorUpdatedAt: number\n fetchFailureCount: number\n fetchFailureReason: TError | null\n fetchMeta: FetchMeta | null\n isInvalidated: boolean\n status: QueryStatus\n fetchStatus: FetchStatus\n}\n\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n fetchFn: () => unknown | Promise<unknown>\n fetchOptions?: FetchOptions\n signal: AbortSignal\n options: QueryOptions<TQueryFnData, TError, TData, any>\n queryKey: TQueryKey\n state: QueryState<TData, TError>\n}\n\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n onFetch: (\n context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n query: Query,\n ) => void\n}\n\nexport type FetchDirection = 'forward' | 'backward'\n\nexport interface FetchMeta {\n fetchMore?: { direction: FetchDirection }\n}\n\nexport interface FetchOptions<TData = unknown> {\n cancelRefetch?: boolean\n meta?: FetchMeta\n initialPromise?: Promise<TData>\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction<TData> {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction<TData, TError> {\n type: 'setState'\n state: Partial<QueryState<TData, TError>>\n setStateOptions?: SetStateOptions\n}\n\nexport type Action<TData, TError> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction<TData, TError>\n | SuccessAction<TData>\n\nexport interface SetStateOptions {\n meta?: any\n}\n\n// CLASS\n\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state: QueryState<TData, TError>\n isFetchingOptimistic?: boolean\n\n #initialState: QueryState<TData, TError>\n #revertState?: QueryState<TData, TError>\n #cache: QueryCache\n #retryer?: Retryer<TData>\n observers: Array<QueryObserver<any, any, any, any, any>>\n #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#cache = config.cache\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n get promise(): Promise<TData> | undefined {\n return this.#retryer?.promise\n }\n\n setOptions(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n this.updateGcTime(this.options.gcTime)\n }\n\n protected optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n setState(\n state: Partial<QueryState<TData, TError>>,\n setStateOptions?: SetStateOptions,\n ): void {\n this.#dispatch({ type: 'setState', state, setStateOptions })\n }\n\n cancel(options?: CancelOptions): Promise<void> {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n reset(): void {\n this.destroy()\n this.setState(this.#initialState)\n }\n\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveEnabled(observer.options.enabled, this) !== false,\n )\n }\n\n isDisabled(): boolean {\n return this.getObserversCount() > 0 && !this.isActive()\n }\n\n isStale(): boolean {\n if (this.state.isInvalidated) {\n return true\n }\n\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined\n }\n\n isStaleByTime(staleTime = 0): boolean {\n return (\n this.state.isInvalidated ||\n this.state.data === undefined ||\n !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n )\n }\n\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n addObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n removeObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (this.observers.includes(observer)) {\n this.observers = this.observers.filter((x) => x !== observer)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (this.#abortSignalConsumed) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n getObserversCount(): number {\n return this.observers.length\n }\n\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n fetch(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n fetchOptions?: FetchOptions<TQueryFnData>,\n ): Promise<TData> {\n if (this.state.fetchStatus !== 'idle') {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#retryer.promise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: unknown) => {\n Object.defineProperty(object, 'signal', {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<TQueryKey>,\n 'signal'\n > = {\n queryKey: this.queryKey,\n meta: this.meta,\n }\n\n addSignalProperty(queryFnContext)\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn as QueryFunction<any>,\n queryFnContext as QueryFunctionContext<TQueryKey>,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext as QueryFunctionContext<TQueryKey>)\n }\n\n // Trigger behavior hook\n const context: OmitKeyof<\n FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n\n this.options.behavior?.onFetch(\n context as FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n this as unknown as Query,\n )\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n const onError = (error: TError | { silent?: boolean }) => {\n // Optimistically update state if needed\n if (!(isCancelledError(error) && error.silent)) {\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n }\n\n if (!isCancelledError(error)) {\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query<any, any, any, any>,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query<any, any, any, any>,\n )\n }\n\n if (!this.isFetchingOptimistic) {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n this.isFetchingOptimistic = false\n }\n\n // Try to fetch the data\n this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise<TData>\n | undefined,\n fn: context.fetchFn as () => Promise<TData>,\n abort: abortController.abort.bind(abortController),\n onSuccess: (data) => {\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n onError(new Error(`${this.queryHash} data is undefined`) as any)\n return\n }\n\n try {\n this.setData(data)\n } catch (error) {\n onError(error as TError)\n return\n }\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query<any, any, any, any>,\n )\n\n if (!this.isFetchingOptimistic) {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n this.isFetchingOptimistic = false\n },\n onError,\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n })\n\n return this.#retryer.start()\n }\n\n #dispatch(action: Action<TData, TError>): void {\n const reducer = (\n state: QueryState<TData, TError>,\n ): QueryState<TData, TError> => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success':\n return {\n ...state,\n data: action.data,\n dataUpdateCount: state.dataUpdateCount + 1,\n dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success',\n ...(!action.manual && {\n fetchStatus: 'idle',\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n case 'error':\n const error = action.error\n\n if (isCancelledError(error) && error.revert && this.#revertState) {\n return { ...this.#revertState, fetchStatus: 'idle' }\n }\n\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n this.observers.forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): QueryState<TData, TError> {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction<TData>)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? (options.initialDataUpdatedAt as () => number | undefined)()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? 'success' : 'pending',\n fetchStatus: 'idle',\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAMO;AACP,2BAA8B;AAC9B,qBAA0D;AAC1D,uBAA0B;AAiJnB,IAAM,QAAN,cAKG,2BAAU;AAAA,EAOlB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EAEA,YAAY,QAA6D;AACvE,UAAM;AAEN,SAAK,uBAAuB;AAC5B,SAAK,kBAAkB,OAAO;AAC9B,SAAK,WAAW,OAAO,OAAO;AAC9B,SAAK,YAAY,CAAC;AAClB,SAAK,SAAS,OAAO;AACrB,SAAK,WAAW,OAAO;AACvB,SAAK,YAAY,OAAO;AACxB,SAAK,gBAAgB,gBAAgB,KAAK,OAAO;AACjD,SAAK,QAAQ,OAAO,SAAS,KAAK;AAClC,SAAK,WAAW;AAAA,EAClB;AAAA,EACA,IAAI,OAA8B;AAChC,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EAEA,IAAI,UAAsC;AACxC,WAAO,KAAK,UAAU;AAAA,EACxB;AAAA,EAEA,WACE,SACM;AACN,SAAK,UAAU,EAAE,GAAG,KAAK,iBAAiB,GAAG,QAAQ;AAErD,SAAK,aAAa,KAAK,QAAQ,MAAM;AAAA,EACvC;AAAA,EAEU,iBAAiB;AACzB,QAAI,CAAC,KAAK,UAAU,UAAU,KAAK,MAAM,gBAAgB,QAAQ;AAC/D,WAAK,OAAO,OAAO,IAAI;AAAA,IACzB;AAAA,EACF;AAAA,EAEA,QACE,SACA,SACO;AACP,UAAM,WAAO,0BAAY,KAAK,MAAM,MAAM,SAAS,KAAK,OAAO;AAG/D,SAAK,UAAU;AAAA,MACb;AAAA,MACA,MAAM;AAAA,MACN,eA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AEd,QAAM,UAAU,SAAS;AAEzB,QAAM,uBAAuB,UACzB,OAAO,QAAQ,yBAAyB,aACrC,QAAQ,qBAAkD,IAC3D,QAAQ,uBACV;AAEJ,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB;AAAA,IACjB,eAAe,UAAW,wBAAwB,KAAK,IAAI,IAAK;AAAA,IAChE,OAAO;AAAA,IACP,kBAAkB;AAAA,IAClB,gBAAgB;AAAA,IAChB,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,WAAW;AAAA,IACX,eAAe;AAAA,IACf,QAAQ,UAAU,YAAY;AAAA,IAC9B,aAAa;AAAA,EACf;AACF;","names":[]}
@@ -238,7 +238,12 @@ var Query = class extends Removable {
238
238
  onError(new Error(`${this.queryHash} data is undefined`));
239
239
  return;
240
240
  }
241
- this.setData(data);
241
+ try {
242
+ this.setData(data);
243
+ } catch (error) {
244
+ onError(error);
245
+ return;
246
+ }
242
247
  this.#cache.config.onSuccess?.(data, this);
243
248
  this.#cache.config.onSettled?.(
244
249
  data,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n noop,\n replaceData,\n resolveEnabled,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { canFetch, createRetryer, isCancelledError } from './retryer'\nimport { Removable } from './removable'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n} from './types'\nimport type { QueryCache } from './queryCache'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n cache: QueryCache\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state?: QueryState<TData, TError>\n}\n\nexport interface QueryState<TData = unknown, TError = DefaultError> {\n data: TData | undefined\n dataUpdateCount: number\n dataUpdatedAt: number\n error: TError | null\n errorUpdateCount: number\n errorUpdatedAt: number\n fetchFailureCount: number\n fetchFailureReason: TError | null\n fetchMeta: FetchMeta | null\n isInvalidated: boolean\n status: QueryStatus\n fetchStatus: FetchStatus\n}\n\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n fetchFn: () => unknown | Promise<unknown>\n fetchOptions?: FetchOptions\n signal: AbortSignal\n options: QueryOptions<TQueryFnData, TError, TData, any>\n queryKey: TQueryKey\n state: QueryState<TData, TError>\n}\n\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n onFetch: (\n context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n query: Query,\n ) => void\n}\n\nexport type FetchDirection = 'forward' | 'backward'\n\nexport interface FetchMeta {\n fetchMore?: { direction: FetchDirection }\n}\n\nexport interface FetchOptions<TData = unknown> {\n cancelRefetch?: boolean\n meta?: FetchMeta\n initialPromise?: Promise<TData>\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction<TData> {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction<TData, TError> {\n type: 'setState'\n state: Partial<QueryState<TData, TError>>\n setStateOptions?: SetStateOptions\n}\n\nexport type Action<TData, TError> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction<TData, TError>\n | SuccessAction<TData>\n\nexport interface SetStateOptions {\n meta?: any\n}\n\n// CLASS\n\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state: QueryState<TData, TError>\n isFetchingOptimistic?: boolean\n\n #initialState: QueryState<TData, TError>\n #revertState?: QueryState<TData, TError>\n #cache: QueryCache\n #retryer?: Retryer<TData>\n observers: Array<QueryObserver<any, any, any, any, any>>\n #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#cache = config.cache\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n get promise(): Promise<TData> | undefined {\n return this.#retryer?.promise\n }\n\n setOptions(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n this.updateGcTime(this.options.gcTime)\n }\n\n protected optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n setState(\n state: Partial<QueryState<TData, TError>>,\n setStateOptions?: SetStateOptions,\n ): void {\n this.#dispatch({ type: 'setState', state, setStateOptions })\n }\n\n cancel(options?: CancelOptions): Promise<void> {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n reset(): void {\n this.destroy()\n this.setState(this.#initialState)\n }\n\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveEnabled(observer.options.enabled, this) !== false,\n )\n }\n\n isDisabled(): boolean {\n return this.getObserversCount() > 0 && !this.isActive()\n }\n\n isStale(): boolean {\n if (this.state.isInvalidated) {\n return true\n }\n\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined\n }\n\n isStaleByTime(staleTime = 0): boolean {\n return (\n this.state.isInvalidated ||\n this.state.data === undefined ||\n !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n )\n }\n\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n addObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n removeObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (this.observers.includes(observer)) {\n this.observers = this.observers.filter((x) => x !== observer)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (this.#abortSignalConsumed) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n getObserversCount(): number {\n return this.observers.length\n }\n\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n fetch(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n fetchOptions?: FetchOptions<TQueryFnData>,\n ): Promise<TData> {\n if (this.state.fetchStatus !== 'idle') {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#retryer.promise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: unknown) => {\n Object.defineProperty(object, 'signal', {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<TQueryKey>,\n 'signal'\n > = {\n queryKey: this.queryKey,\n meta: this.meta,\n }\n\n addSignalProperty(queryFnContext)\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn as QueryFunction<any>,\n queryFnContext as QueryFunctionContext<TQueryKey>,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext as QueryFunctionContext<TQueryKey>)\n }\n\n // Trigger behavior hook\n const context: OmitKeyof<\n FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n\n this.options.behavior?.onFetch(\n context as FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n this as unknown as Query,\n )\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n const onError = (error: TError | { silent?: boolean }) => {\n // Optimistically update state if needed\n if (!(isCancelledError(error) && error.silent)) {\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n }\n\n if (!isCancelledError(error)) {\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query<any, any, any, any>,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query<any, any, any, any>,\n )\n }\n\n if (!this.isFetchingOptimistic) {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n this.isFetchingOptimistic = false\n }\n\n // Try to fetch the data\n this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise<TData>\n | undefined,\n fn: context.fetchFn as () => Promise<TData>,\n abort: abortController.abort.bind(abortController),\n onSuccess: (data) => {\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n onError(new Error(`${this.queryHash} data is undefined`) as any)\n return\n }\n\n this.setData(data)\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query<any, any, any, any>,\n )\n\n if (!this.isFetchingOptimistic) {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n this.isFetchingOptimistic = false\n },\n onError,\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n })\n\n return this.#retryer.start()\n }\n\n #dispatch(action: Action<TData, TError>): void {\n const reducer = (\n state: QueryState<TData, TError>,\n ): QueryState<TData, TError> => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success':\n return {\n ...state,\n data: action.data,\n dataUpdateCount: state.dataUpdateCount + 1,\n dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success',\n ...(!action.manual && {\n fetchStatus: 'idle',\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n case 'error':\n const error = action.error\n\n if (isCancelledError(error) && error.revert && this.#revertState) {\n return { ...this.#revertState, fetchStatus: 'idle' }\n }\n\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n this.observers.forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): QueryState<TData, TError> {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction<TData>)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? (options.initialDataUpdatedAt as () => number | undefined)()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? 'success' : 'pending',\n fetchStatus: 'idle',\n }\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB;AAC9B,SAAS,UAAU,eAAe,wBAAwB;AAC1D,SAAS,iBAAiB;AAiJnB,IAAM,QAAN,cAKG,UAAU;AAAA,EAOlB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EAEA,YAAY,QAA6D;AACvE,UAAM;AAEN,SAAK,uBAAuB;AAC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;AAAA,YACL,GAAG;AAAA,YACH,eAAe;AAAA,UACjB;AAAA,QACF,KAAK;AACH,iBAAO;AAAA,YACL,GAAG;AAAA,YACH,GAAG,OAAO;AAAA,UACZ;AAAA,MACJ;AAAA,IACF;AAEA,SAAK,QAAQ,QAAQ,KAAK,KAAK;AAE/B,kBAAc,MAAM,MAAM;AACxB,WAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,iBAAS,cAAc;AAAA,MACzB,CAAC;AAED,WAAK,OAAO,OAAO,EAAE,OAAO,MAAM,MAAM,WAAW,OAAO,CAAC;AAAA,IAC7D,CAAC;AAAA,EACH;AACF;AAEO,SAAS,WAMd,MACA,SACA;AACA,SAAO;AAAA,IACL,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,aAAa,SAAS,QAAQ,WAAW,IAAI,aAAa;AAAA,IAC1D,GAAI,SAAS,UACV;AAAA,MACC,OAAO;AAAA,MACP,QAAQ;AAAA,IACV;AAAA,EACJ;AACF;AAEA,SAAS,gBAMP,SAC2B;AAC3B,QAAM,OACJ,OAAO,QAAQ,gBAAgB,aAC1B,QAAQ,YAA2C,IACpD,QAAQ;AAEd,QAAM,UAAU,SAAS;AAEzB,QAAM,uBAAuB,UACzB,OAAO,QAAQ,yBAAyB,aACrC,QAAQ,qBAAkD,IAC3D,QAAQ,uBACV;AAEJ,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB;AAAA,IACjB,eAAe,UAAW,wBAAwB,KAAK,IAAI,IAAK;AAAA,IAChE,OAAO;AAAA,IACP,kBAAkB;AAAA,IAClB,gBAAgB;AAAA,IAChB,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,WAAW;AAAA,IACX,eAAe;AAAA,IACf,QAAQ,UAAU,YAAY;AAAA,IAC9B,aAAa;AAAA,EACf;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n noop,\n replaceData,\n resolveEnabled,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { canFetch, createRetryer, isCancelledError } from './retryer'\nimport { Removable } from './removable'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n} from './types'\nimport type { QueryCache } from './queryCache'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n cache: QueryCache\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state?: QueryState<TData, TError>\n}\n\nexport interface QueryState<TData = unknown, TError = DefaultError> {\n data: TData | undefined\n dataUpdateCount: number\n dataUpdatedAt: number\n error: TError | null\n errorUpdateCount: number\n errorUpdatedAt: number\n fetchFailureCount: number\n fetchFailureReason: TError | null\n fetchMeta: FetchMeta | null\n isInvalidated: boolean\n status: QueryStatus\n fetchStatus: FetchStatus\n}\n\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n fetchFn: () => unknown | Promise<unknown>\n fetchOptions?: FetchOptions\n signal: AbortSignal\n options: QueryOptions<TQueryFnData, TError, TData, any>\n queryKey: TQueryKey\n state: QueryState<TData, TError>\n}\n\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n onFetch: (\n context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n query: Query,\n ) => void\n}\n\nexport type FetchDirection = 'forward' | 'backward'\n\nexport interface FetchMeta {\n fetchMore?: { direction: FetchDirection }\n}\n\nexport interface FetchOptions<TData = unknown> {\n cancelRefetch?: boolean\n meta?: FetchMeta\n initialPromise?: Promise<TData>\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction<TData> {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction<TData, TError> {\n type: 'setState'\n state: Partial<QueryState<TData, TError>>\n setStateOptions?: SetStateOptions\n}\n\nexport type Action<TData, TError> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction<TData, TError>\n | SuccessAction<TData>\n\nexport interface SetStateOptions {\n meta?: any\n}\n\n// CLASS\n\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state: QueryState<TData, TError>\n isFetchingOptimistic?: boolean\n\n #initialState: QueryState<TData, TError>\n #revertState?: QueryState<TData, TError>\n #cache: QueryCache\n #retryer?: Retryer<TData>\n observers: Array<QueryObserver<any, any, any, any, any>>\n #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#cache = config.cache\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n get promise(): Promise<TData> | undefined {\n return this.#retryer?.promise\n }\n\n setOptions(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n this.updateGcTime(this.options.gcTime)\n }\n\n protected optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n setState(\n state: Partial<QueryState<TData, TError>>,\n setStateOptions?: SetStateOptions,\n ): void {\n this.#dispatch({ type: 'setState', state, setStateOptions })\n }\n\n cancel(options?: CancelOptions): Promise<void> {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n reset(): void {\n this.destroy()\n this.setState(this.#initialState)\n }\n\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveEnabled(observer.options.enabled, this) !== false,\n )\n }\n\n isDisabled(): boolean {\n return this.getObserversCount() > 0 && !this.isActive()\n }\n\n isStale(): boolean {\n if (this.state.isInvalidated) {\n return true\n }\n\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined\n }\n\n isStaleByTime(staleTime = 0): boolean {\n return (\n this.state.isInvalidated ||\n this.state.data === undefined ||\n !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n )\n }\n\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n addObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n removeObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (this.observers.includes(observer)) {\n this.observers = this.observers.filter((x) => x !== observer)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (this.#abortSignalConsumed) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n getObserversCount(): number {\n return this.observers.length\n }\n\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n fetch(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n fetchOptions?: FetchOptions<TQueryFnData>,\n ): Promise<TData> {\n if (this.state.fetchStatus !== 'idle') {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#retryer.promise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: unknown) => {\n Object.defineProperty(object, 'signal', {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<TQueryKey>,\n 'signal'\n > = {\n queryKey: this.queryKey,\n meta: this.meta,\n }\n\n addSignalProperty(queryFnContext)\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn as QueryFunction<any>,\n queryFnContext as QueryFunctionContext<TQueryKey>,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext as QueryFunctionContext<TQueryKey>)\n }\n\n // Trigger behavior hook\n const context: OmitKeyof<\n FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n\n this.options.behavior?.onFetch(\n context as FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n this as unknown as Query,\n )\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n const onError = (error: TError | { silent?: boolean }) => {\n // Optimistically update state if needed\n if (!(isCancelledError(error) && error.silent)) {\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n }\n\n if (!isCancelledError(error)) {\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query<any, any, any, any>,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query<any, any, any, any>,\n )\n }\n\n if (!this.isFetchingOptimistic) {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n this.isFetchingOptimistic = false\n }\n\n // Try to fetch the data\n this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise<TData>\n | undefined,\n fn: context.fetchFn as () => Promise<TData>,\n abort: abortController.abort.bind(abortController),\n onSuccess: (data) => {\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n onError(new Error(`${this.queryHash} data is undefined`) as any)\n return\n }\n\n try {\n this.setData(data)\n } catch (error) {\n onError(error as TError)\n return\n }\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query<any, any, any, any>,\n )\n\n if (!this.isFetchingOptimistic) {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n this.isFetchingOptimistic = false\n },\n onError,\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n })\n\n return this.#retryer.start()\n }\n\n #dispatch(action: Action<TData, TError>): void {\n const reducer = (\n state: QueryState<TData, TError>,\n ): QueryState<TData, TError> => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success':\n return {\n ...state,\n data: action.data,\n dataUpdateCount: state.dataUpdateCount + 1,\n dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success',\n ...(!action.manual && {\n fetchStatus: 'idle',\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n case 'error':\n const error = action.error\n\n if (isCancelledError(error) && error.revert && this.#revertState) {\n return { ...this.#revertState, fetchStatus: 'idle' }\n }\n\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n this.observers.forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): QueryState<TData, TError> {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction<TData>)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? (options.initialDataUpdatedAt as () => number | undefined)()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? 'success' : 'pending',\n fetchStatus: 'idle',\n }\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB;AAC9B,SAAS,UAAU,eAAe,wBAAwB;AAC1D,SAAS,iBAAiB;AAiJnB,IAAM,QAAN,cAKG,UAAU;AAAA,EAOlB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EAEA,YAAY,QAA6D;AACvE,UAAM;AAEN,SAAK,uBAAuB;AAC5B,SAAK,kBAAkB,OAAO;AAC9B,SAAK,WAAW,OAAO,OAAO;AAC9B,SAAK,YAAY,CAAC;AAClB,SAAK,SAAS,OAAO;AACrB,SAAK,WAAW,OAAO;AACvB,SAAK,YAAY,OAAO;AACxB,SAAK,gBAAgB,gBAAgB,KAAK,OAAO;AACjD,SAAK,QAAQ,OAAO,SAAS,KAAK;AAClC,SAAK,WAAW;AAAA,EAClB;AAAA,EACA,IAAI,OAA8B;AAChC,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EAEA,IAAI,UAAsC;AACxC,WAAO,KAAK,UAAU;AAAA,EACxB;AAAA,EAEA,WACE,SACM;AACN,SAAK,UAAU,EAAE,GAAG,KAAK,iBAAiB,GAAG,QAAQ;AAErD,SAAK,aAAa,KAAK,QAAQ,MAAM;AAAA,EACvC;AAAA,EAEU,iBAAiB;AACzB,QAAI,CAAC,KAAK,UAAU,UAAU,KAAK,MAAM,gBAAgB,QAAQ;AAC/D,WAAK,OAAO,OAAO,IAAI;AAAA,IACzB;AAAA,EACF;AAAA,EAEA,QACE,SACA,SACO;AACP,UAAM,OAAO,YAAY,KAAK,MAAM,MAAM,SAAS,KAAK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AO,QAAQ,gBAAgB,aAC1B,QAAQ,YAA2C,IACpD,QAAQ;AAEd,QAAM,UAAU,SAAS;AAEzB,QAAM,uBAAuB,UACzB,OAAO,QAAQ,yBAAyB,aACrC,QAAQ,qBAAkD,IAC3D,QAAQ,uBACV;AAEJ,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB;AAAA,IACjB,eAAe,UAAW,wBAAwB,KAAK,IAAI,IAAK;AAAA,IAChE,OAAO;AAAA,IACP,kBAAkB;AAAA,IAClB,gBAAgB;AAAA,IAChB,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,WAAW;AAAA,IACX,eAAe;AAAA,IACf,QAAQ,UAAU,YAAY;AAAA,IAC9B,aAAa;AAAA,EACf;AACF;","names":[]}
@@ -223,6 +223,17 @@ function replaceData(prevData, data, options) {
223
223
  if (typeof options.structuralSharing === "function") {
224
224
  return options.structuralSharing(prevData, data);
225
225
  } else if (options.structuralSharing !== false) {
226
+ if (process.env.NODE_ENV !== "production") {
227
+ try {
228
+ JSON.stringify(prevData);
229
+ JSON.stringify(data);
230
+ } catch (error) {
231
+ console.error(
232
+ `StructuralSharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`
233
+ );
234
+ throw new Error("Data is not serializable");
235
+ }
236
+ }
226
237
  return replaceEqualDeep(prevData, data);
227
238
  }
228
239
  return data;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["import type {\n DefaultError,\n Enabled,\n FetchStatus,\n MutationKey,\n MutationStatus,\n QueryFunction,\n QueryKey,\n QueryOptions,\n StaleTime,\n} from './types'\nimport type { Mutation } from './mutation'\nimport type { FetchOptions, Query } from './query'\n\n// TYPES\n\nexport interface QueryFilters {\n /**\n * Filter to active queries, inactive queries or all queries\n */\n type?: QueryTypeFilter\n /**\n * Match query key exactly\n */\n exact?: boolean\n /**\n * Include queries matching this predicate function\n */\n predicate?: (query: Query) => boolean\n /**\n * Include queries matching this query key\n */\n queryKey?: QueryKey\n /**\n * Include or exclude stale queries\n */\n stale?: boolean\n /**\n * Include queries matching their fetchStatus\n */\n fetchStatus?: FetchStatus\n}\n\nexport interface MutationFilters {\n /**\n * Match mutation key exactly\n */\n exact?: boolean\n /**\n * Include mutations matching this predicate function\n */\n predicate?: (mutation: Mutation<any, any, any>) => boolean\n /**\n * Include mutations matching this mutation key\n */\n mutationKey?: MutationKey\n /**\n * Filter by mutation status\n */\n status?: MutationStatus\n}\n\nexport type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)\n\nexport type QueryTypeFilter = 'all' | 'active' | 'inactive'\n\n// UTILS\n\nexport const isServer = typeof window === 'undefined' || 'Deno' in globalThis\n\nexport function noop(): undefined {\n return undefined\n}\n\nexport function functionalUpdate<TInput, TOutput>(\n updater: Updater<TInput, TOutput>,\n input: TInput,\n): TOutput {\n return typeof updater === 'function'\n ? (updater as (_: TInput) => TOutput)(input)\n : updater\n}\n\nexport function isValidTimeout(value: unknown): value is number {\n return typeof value === 'number' && value >= 0 && value !== Infinity\n}\n\nexport function timeUntilStale(updatedAt: number, staleTime?: number): number {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)\n}\n\nexport function resolveStaleTime<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n staleTime: undefined | StaleTime<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): number | undefined {\n return typeof staleTime === 'function' ? staleTime(query) : staleTime\n}\n\nexport function resolveEnabled<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n enabled: undefined | Enabled<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): boolean | undefined {\n return typeof enabled === 'function' ? enabled(query) : enabled\n}\n\nexport function matchQuery(\n filters: QueryFilters,\n query: Query<any, any, any, any>,\n): boolean {\n const {\n type = 'all',\n exact,\n fetchStatus,\n predicate,\n queryKey,\n stale,\n } = filters\n\n if (queryKey) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false\n }\n }\n\n if (type !== 'all') {\n const isActive = query.isActive()\n if (type === 'active' && !isActive) {\n return false\n }\n if (type === 'inactive' && isActive) {\n return false\n }\n }\n\n if (typeof stale === 'boolean' && query.isStale() !== stale) {\n return false\n }\n\n if (fetchStatus && fetchStatus !== query.state.fetchStatus) {\n return false\n }\n\n if (predicate && !predicate(query)) {\n return false\n }\n\n return true\n}\n\nexport function matchMutation(\n filters: MutationFilters,\n mutation: Mutation<any, any>,\n): boolean {\n const { exact, status, predicate, mutationKey } = filters\n if (mutationKey) {\n if (!mutation.options.mutationKey) {\n return false\n }\n if (exact) {\n if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {\n return false\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false\n }\n }\n\n if (status && mutation.state.status !== status) {\n return false\n }\n\n if (predicate && !predicate(mutation)) {\n return false\n }\n\n return true\n}\n\nexport function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(\n queryKey: TQueryKey,\n options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,\n): string {\n const hashFn = options?.queryKeyHashFn || hashKey\n return hashFn(queryKey)\n}\n\n/**\n * Default query & mutation keys hash function.\n * Hashes the value into a stable hash.\n */\nexport function hashKey(queryKey: QueryKey | MutationKey): string {\n return JSON.stringify(queryKey, (_, val) =>\n isPlainObject(val)\n ? Object.keys(val)\n .sort()\n .reduce((result, key) => {\n result[key] = val[key]\n return result\n }, {} as any)\n : val,\n )\n}\n\n/**\n * Checks if key `b` partially matches with key `a`.\n */\nexport function partialMatchKey(a: QueryKey, b: QueryKey): boolean\nexport function partialMatchKey(a: any, b: any): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n return !Object.keys(b).some((key) => !partialMatchKey(a[key], b[key]))\n }\n\n return false\n}\n\n/**\n * This function returns `a` if `b` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between JSON values for example.\n */\nexport function replaceEqualDeep<T>(a: unknown, b: T): T\nexport function replaceEqualDeep(a: any, b: any): any {\n if (a === b) {\n return a\n }\n\n const array = isPlainArray(a) && isPlainArray(b)\n\n if (array || (isPlainObject(a) && isPlainObject(b))) {\n const aItems = array ? a : Object.keys(a)\n const aSize = aItems.length\n const bItems = array ? b : Object.keys(b)\n const bSize = bItems.length\n const copy: any = array ? [] : {}\n\n let equalItems = 0\n\n for (let i = 0; i < bSize; i++) {\n const key = array ? i : bItems[i]\n if (\n ((!array && aItems.includes(key)) || array) &&\n a[key] === undefined &&\n b[key] === undefined\n ) {\n copy[key] = undefined\n equalItems++\n } else {\n copy[key] = replaceEqualDeep(a[key], b[key])\n if (copy[key] === a[key] && a[key] !== undefined) {\n equalItems++\n }\n }\n }\n\n return aSize === bSize && equalItems === aSize ? a : copy\n }\n\n return b\n}\n\n/**\n * Shallow compare objects.\n */\nexport function shallowEqualObjects<T extends Record<string, any>>(\n a: T,\n b: T | undefined,\n): boolean {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false\n }\n\n for (const key in a) {\n if (a[key] !== b[key]) {\n return false\n }\n }\n\n return true\n}\n\nexport function isPlainArray(value: unknown) {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\nexport function isPlainObject(o: any): o is Object {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has no constructor\n const ctor = o.constructor\n if (ctor === undefined) {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Handles Objects created by Object.create(<arbitrary prototype>)\n if (Object.getPrototypeOf(o) !== Object.prototype) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\nexport function sleep(timeout: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, timeout)\n })\n}\n\nexport function replaceData<\n TData,\n TOptions extends QueryOptions<any, any, any, any>,\n>(prevData: TData | undefined, data: TData, options: TOptions): TData {\n if (typeof options.structuralSharing === 'function') {\n return options.structuralSharing(prevData, data) as TData\n } else if (options.structuralSharing !== false) {\n // Structurally share data between prev and new data if needed\n return replaceEqualDeep(prevData, data)\n }\n return data\n}\n\nexport function keepPreviousData<T>(\n previousData: T | undefined,\n): T | undefined {\n return previousData\n}\n\nexport function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [...items, item]\n return max && newItems.length > max ? newItems.slice(1) : newItems\n}\n\nexport function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [item, ...items]\n return max && newItems.length > max ? newItems.slice(0, -1) : newItems\n}\n\nexport const skipToken = Symbol()\nexport type SkipToken = typeof skipToken\n\nexport function ensureQueryFn<\n TQueryFnData = unknown,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: {\n queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken\n queryHash?: string\n },\n fetchOptions?: FetchOptions<TQueryFnData>,\n): QueryFunction<TQueryFnData, TQueryKey> {\n if (process.env.NODE_ENV !== 'production') {\n if (options.queryFn === skipToken) {\n console.error(\n `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,\n )\n }\n }\n\n // if we attempt to retry a fetch that was triggered from an initialPromise\n // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise\n // if an observer has already mounted, we will be able to retry with that queryFn\n if (!options.queryFn && fetchOptions?.initialPromise) {\n return () => fetchOptions.initialPromise!\n }\n\n if (!options.queryFn || options.queryFn === skipToken) {\n return () =>\n Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))\n }\n\n return options.queryFn\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoEO,IAAM,WAAW,OAAO,WAAW,eAAe,UAAU;AAE5D,SAAS,OAAkB;AAChC,SAAO;AACT;AAEO,SAAS,iBACd,SACA,OACS;AACT,SAAO,OAAO,YAAY,aACrB,QAAmC,KAAK,IACzC;AACN;AAEO,SAAS,eAAe,OAAiC;AAC9D,SAAO,OAAO,UAAU,YAAY,SAAS,KAAK,UAAU;AAC9D;AAEO,SAAS,eAAe,WAAmB,WAA4B;AAC5E,SAAO,KAAK,IAAI,aAAa,aAAa,KAAK,KAAK,IAAI,GAAG,CAAC;AAC9D;AAEO,SAAS,iBAMd,WACA,OACoB;AACpB,SAAO,OAAO,cAAc,aAAa,UAAU,KAAK,IAAI;AAC9D;AAEO,SAAS,eAMd,SACA,OACqB;AACrB,SAAO,OAAO,YAAY,aAAa,QAAQ,KAAK,IAAI;AAC1D;AAEO,SAAS,WACd,SACA,OACS;AACT,QAAM;AAAA,IACJ,OAAO;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,MAAI,UAAU;AACZ,QAAI,OAAO;AACT,UAAI,MAAM,cAAc,sBAAsB,UAAU,MAAM,OAAO,GAAG;AACtE,eAAO;AAAA,MACT;AAAA,IACF,WAAW,CAAC,gBAAgB,MAAM,UAAU,QAAQ,GAAG;AACrD,aAAO;AAAA,IACT;AAAA,EACF;AAEA,MA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AEO,SAAS,SAAY,OAAiB,MAAS,MAAM,GAAa;AACvE,QAAM,WAAW,CAAC,GAAG,OAAO,IAAI;AAChC,SAAO,OAAO,SAAS,SAAS,MAAM,SAAS,MAAM,CAAC,IAAI;AAC5D;AAEO,SAAS,WAAc,OAAiB,MAAS,MAAM,GAAa;AACzE,QAAM,WAAW,CAAC,MAAM,GAAG,KAAK;AAChC,SAAO,OAAO,SAAS,SAAS,MAAM,SAAS,MAAM,GAAG,EAAE,IAAI;AAChE;AAEO,IAAM,YAAY,OAAO;AAGzB,SAAS,cAId,SAIA,cACwC;AACxC,MAAI,QAAQ,IAAI,aAAa,cAAc;AACzC,QAAI,QAAQ,YAAY,WAAW;AACjC,cAAQ;AAAA,QACN,yGAAyG,QAAQ,SAAS;AAAA,MAC5H;AAAA,IACF;AAAA,EACF;AAKA,MAAI,CAAC,QAAQ,WAAW,cAAc,gBAAgB;AACpD,WAAO,MAAM,aAAa;AAAA,EAC5B;AAEA,MAAI,CAAC,QAAQ,WAAW,QAAQ,YAAY,WAAW;AACrD,WAAO,MACL,QAAQ,OAAO,IAAI,MAAM,qBAAqB,QAAQ,SAAS,GAAG,CAAC;AAAA,EACvE;AAEA,SAAO,QAAQ;AACjB;","names":[]}
1
+ {"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["import type {\n DefaultError,\n Enabled,\n FetchStatus,\n MutationKey,\n MutationStatus,\n QueryFunction,\n QueryKey,\n QueryOptions,\n StaleTime,\n} from './types'\nimport type { Mutation } from './mutation'\nimport type { FetchOptions, Query } from './query'\n\n// TYPES\n\nexport interface QueryFilters {\n /**\n * Filter to active queries, inactive queries or all queries\n */\n type?: QueryTypeFilter\n /**\n * Match query key exactly\n */\n exact?: boolean\n /**\n * Include queries matching this predicate function\n */\n predicate?: (query: Query) => boolean\n /**\n * Include queries matching this query key\n */\n queryKey?: QueryKey\n /**\n * Include or exclude stale queries\n */\n stale?: boolean\n /**\n * Include queries matching their fetchStatus\n */\n fetchStatus?: FetchStatus\n}\n\nexport interface MutationFilters {\n /**\n * Match mutation key exactly\n */\n exact?: boolean\n /**\n * Include mutations matching this predicate function\n */\n predicate?: (mutation: Mutation<any, any, any>) => boolean\n /**\n * Include mutations matching this mutation key\n */\n mutationKey?: MutationKey\n /**\n * Filter by mutation status\n */\n status?: MutationStatus\n}\n\nexport type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)\n\nexport type QueryTypeFilter = 'all' | 'active' | 'inactive'\n\n// UTILS\n\nexport const isServer = typeof window === 'undefined' || 'Deno' in globalThis\n\nexport function noop(): undefined {\n return undefined\n}\n\nexport function functionalUpdate<TInput, TOutput>(\n updater: Updater<TInput, TOutput>,\n input: TInput,\n): TOutput {\n return typeof updater === 'function'\n ? (updater as (_: TInput) => TOutput)(input)\n : updater\n}\n\nexport function isValidTimeout(value: unknown): value is number {\n return typeof value === 'number' && value >= 0 && value !== Infinity\n}\n\nexport function timeUntilStale(updatedAt: number, staleTime?: number): number {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)\n}\n\nexport function resolveStaleTime<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n staleTime: undefined | StaleTime<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): number | undefined {\n return typeof staleTime === 'function' ? staleTime(query) : staleTime\n}\n\nexport function resolveEnabled<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n enabled: undefined | Enabled<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): boolean | undefined {\n return typeof enabled === 'function' ? enabled(query) : enabled\n}\n\nexport function matchQuery(\n filters: QueryFilters,\n query: Query<any, any, any, any>,\n): boolean {\n const {\n type = 'all',\n exact,\n fetchStatus,\n predicate,\n queryKey,\n stale,\n } = filters\n\n if (queryKey) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false\n }\n }\n\n if (type !== 'all') {\n const isActive = query.isActive()\n if (type === 'active' && !isActive) {\n return false\n }\n if (type === 'inactive' && isActive) {\n return false\n }\n }\n\n if (typeof stale === 'boolean' && query.isStale() !== stale) {\n return false\n }\n\n if (fetchStatus && fetchStatus !== query.state.fetchStatus) {\n return false\n }\n\n if (predicate && !predicate(query)) {\n return false\n }\n\n return true\n}\n\nexport function matchMutation(\n filters: MutationFilters,\n mutation: Mutation<any, any>,\n): boolean {\n const { exact, status, predicate, mutationKey } = filters\n if (mutationKey) {\n if (!mutation.options.mutationKey) {\n return false\n }\n if (exact) {\n if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {\n return false\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false\n }\n }\n\n if (status && mutation.state.status !== status) {\n return false\n }\n\n if (predicate && !predicate(mutation)) {\n return false\n }\n\n return true\n}\n\nexport function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(\n queryKey: TQueryKey,\n options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,\n): string {\n const hashFn = options?.queryKeyHashFn || hashKey\n return hashFn(queryKey)\n}\n\n/**\n * Default query & mutation keys hash function.\n * Hashes the value into a stable hash.\n */\nexport function hashKey(queryKey: QueryKey | MutationKey): string {\n return JSON.stringify(queryKey, (_, val) =>\n isPlainObject(val)\n ? Object.keys(val)\n .sort()\n .reduce((result, key) => {\n result[key] = val[key]\n return result\n }, {} as any)\n : val,\n )\n}\n\n/**\n * Checks if key `b` partially matches with key `a`.\n */\nexport function partialMatchKey(a: QueryKey, b: QueryKey): boolean\nexport function partialMatchKey(a: any, b: any): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n return !Object.keys(b).some((key) => !partialMatchKey(a[key], b[key]))\n }\n\n return false\n}\n\n/**\n * This function returns `a` if `b` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between JSON values for example.\n */\nexport function replaceEqualDeep<T>(a: unknown, b: T): T\nexport function replaceEqualDeep(a: any, b: any): any {\n if (a === b) {\n return a\n }\n\n const array = isPlainArray(a) && isPlainArray(b)\n\n if (array || (isPlainObject(a) && isPlainObject(b))) {\n const aItems = array ? a : Object.keys(a)\n const aSize = aItems.length\n const bItems = array ? b : Object.keys(b)\n const bSize = bItems.length\n const copy: any = array ? [] : {}\n\n let equalItems = 0\n\n for (let i = 0; i < bSize; i++) {\n const key = array ? i : bItems[i]\n if (\n ((!array && aItems.includes(key)) || array) &&\n a[key] === undefined &&\n b[key] === undefined\n ) {\n copy[key] = undefined\n equalItems++\n } else {\n copy[key] = replaceEqualDeep(a[key], b[key])\n if (copy[key] === a[key] && a[key] !== undefined) {\n equalItems++\n }\n }\n }\n\n return aSize === bSize && equalItems === aSize ? a : copy\n }\n\n return b\n}\n\n/**\n * Shallow compare objects.\n */\nexport function shallowEqualObjects<T extends Record<string, any>>(\n a: T,\n b: T | undefined,\n): boolean {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false\n }\n\n for (const key in a) {\n if (a[key] !== b[key]) {\n return false\n }\n }\n\n return true\n}\n\nexport function isPlainArray(value: unknown) {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\nexport function isPlainObject(o: any): o is Object {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has no constructor\n const ctor = o.constructor\n if (ctor === undefined) {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Handles Objects created by Object.create(<arbitrary prototype>)\n if (Object.getPrototypeOf(o) !== Object.prototype) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\nexport function sleep(timeout: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, timeout)\n })\n}\n\nexport function replaceData<\n TData,\n TOptions extends QueryOptions<any, any, any, any>,\n>(prevData: TData | undefined, data: TData, options: TOptions): TData {\n if (typeof options.structuralSharing === 'function') {\n return options.structuralSharing(prevData, data) as TData\n } else if (options.structuralSharing !== false) {\n if (process.env.NODE_ENV !== 'production') {\n try {\n JSON.stringify(prevData)\n JSON.stringify(data)\n } catch (error) {\n console.error(\n `StructuralSharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`,\n )\n\n throw new Error('Data is not serializable')\n }\n }\n\n // Structurally share data between prev and new data if needed\n return replaceEqualDeep(prevData, data)\n }\n return data\n}\n\nexport function keepPreviousData<T>(\n previousData: T | undefined,\n): T | undefined {\n return previousData\n}\n\nexport function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [...items, item]\n return max && newItems.length > max ? newItems.slice(1) : newItems\n}\n\nexport function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [item, ...items]\n return max && newItems.length > max ? newItems.slice(0, -1) : newItems\n}\n\nexport const skipToken = Symbol()\nexport type SkipToken = typeof skipToken\n\nexport function ensureQueryFn<\n TQueryFnData = unknown,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: {\n queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken\n queryHash?: string\n },\n fetchOptions?: FetchOptions<TQueryFnData>,\n): QueryFunction<TQueryFnData, TQueryKey> {\n if (process.env.NODE_ENV !== 'production') {\n if (options.queryFn === skipToken) {\n console.error(\n `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,\n )\n }\n }\n\n // if we attempt to retry a fetch that was triggered from an initialPromise\n // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise\n // if an observer has already mounted, we will be able to retry with that queryFn\n if (!options.queryFn && fetchOptions?.initialPromise) {\n return () => fetchOptions.initialPromise!\n }\n\n if (!options.queryFn || options.queryFn === skipToken) {\n return () =>\n Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))\n }\n\n return options.queryFn\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoEO,IAAM,WAAW,OAAO,WAAW,eAAe,UAAU;AAE5D,SAAS,OAAkB;AAChC,SAAO;AACT;AAEO,SAAS,iBACd,SACA,OACS;AACT,SAAO,OAAO,YAAY,aACrB,QAAmC,KAAK,IACzC;AACN;AAEO,SAAS,eAAe,OAAiC;AAC9D,SAAO,OAAO,UAAU,YAAY,SAAS,KAAK,UAAU;AAC9D;AAEO,SAAS,eAAe,WAAmB,WAA4B;AAC5E,SAAO,KAAK,IAAI,aAAa,aAAa,KAAK,KAAK,IAAI,GAAG,CAAC;AAC9D;AAEO,SAAS,iBAMd,WACA,OACoB;AACpB,SAAO,OAAO,cAAc,aAAa,UAAU,KAAK,IAAI;AAC9D;AAEO,SAAS,eAMd,SACA,OACqB;AACrB,SAAO,OAAO,YAAY,aAAa,QAAQ,KAAK,IAAI;AAC1D;AAEO,SAAS,WACd,SACA,OACS;AACT,QAAM;AAAA,IACJ,OAAO;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,MAAI,UAAU;AACZ,QAAI,OAAO;AACT,UAAI,MAAM,cAAc,sBAAsB,UAAU,MAAM,OAAO,GAAG;AACtE,eAAO;AAAA,MACT;AAAA,IACF,WAAW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,IAAI,aAAa,cAAc;AACzC,UAAI;AACF,aAAK,UAAU,QAAQ;AACvB,aAAK,UAAU,IAAI;AAAA,MACrB,SAAS,OAAO;AACd,gBAAQ;AAAA,UACN,yJAAyJ,QAAQ,SAAS,MAAM,KAAK;AAAA,QACvL;AAEA,cAAM,IAAI,MAAM,0BAA0B;AAAA,MAC5C;AAAA,IACF;AAGA,WAAO,iBAAiB,UAAU,IAAI;AAAA,EACxC;AACA,SAAO;AACT;AAEO,SAAS,iBACd,cACe;AACf,SAAO;AACT;AAEO,SAAS,SAAY,OAAiB,MAAS,MAAM,GAAa;AACvE,QAAM,WAAW,CAAC,GAAG,OAAO,IAAI;AAChC,SAAO,OAAO,SAAS,SAAS,MAAM,SAAS,MAAM,CAAC,IAAI;AAC5D;AAEO,SAAS,WAAc,OAAiB,MAAS,MAAM,GAAa;AACzE,QAAM,WAAW,CAAC,MAAM,GAAG,KAAK;AAChC,SAAO,OAAO,SAAS,SAAS,MAAM,SAAS,MAAM,GAAG,EAAE,IAAI;AAChE;AAEO,IAAM,YAAY,OAAO;AAGzB,SAAS,cAId,SAIA,cACwC;AACxC,MAAI,QAAQ,IAAI,aAAa,cAAc;AACzC,QAAI,QAAQ,YAAY,WAAW;AACjC,cAAQ;AAAA,QACN,yGAAyG,QAAQ,SAAS;AAAA,MAC5H;AAAA,IACF;AAAA,EACF;AAKA,MAAI,CAAC,QAAQ,WAAW,cAAc,gBAAgB;AACpD,WAAO,MAAM,aAAa;AAAA,EAC5B;AAEA,MAAI,CAAC,QAAQ,WAAW,QAAQ,YAAY,WAAW;AACrD,WAAO,MACL,QAAQ,OAAO,IAAI,MAAM,qBAAqB,QAAQ,SAAS,GAAG,CAAC;AAAA,EACvE;AAEA,SAAO,QAAQ;AACjB;","names":[]}
@@ -177,6 +177,17 @@ function replaceData(prevData, data, options) {
177
177
  if (typeof options.structuralSharing === "function") {
178
178
  return options.structuralSharing(prevData, data);
179
179
  } else if (options.structuralSharing !== false) {
180
+ if (process.env.NODE_ENV !== "production") {
181
+ try {
182
+ JSON.stringify(prevData);
183
+ JSON.stringify(data);
184
+ } catch (error) {
185
+ console.error(
186
+ `StructuralSharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`
187
+ );
188
+ throw new Error("Data is not serializable");
189
+ }
190
+ }
180
191
  return replaceEqualDeep(prevData, data);
181
192
  }
182
193
  return data;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["import type {\n DefaultError,\n Enabled,\n FetchStatus,\n MutationKey,\n MutationStatus,\n QueryFunction,\n QueryKey,\n QueryOptions,\n StaleTime,\n} from './types'\nimport type { Mutation } from './mutation'\nimport type { FetchOptions, Query } from './query'\n\n// TYPES\n\nexport interface QueryFilters {\n /**\n * Filter to active queries, inactive queries or all queries\n */\n type?: QueryTypeFilter\n /**\n * Match query key exactly\n */\n exact?: boolean\n /**\n * Include queries matching this predicate function\n */\n predicate?: (query: Query) => boolean\n /**\n * Include queries matching this query key\n */\n queryKey?: QueryKey\n /**\n * Include or exclude stale queries\n */\n stale?: boolean\n /**\n * Include queries matching their fetchStatus\n */\n fetchStatus?: FetchStatus\n}\n\nexport interface MutationFilters {\n /**\n * Match mutation key exactly\n */\n exact?: boolean\n /**\n * Include mutations matching this predicate function\n */\n predicate?: (mutation: Mutation<any, any, any>) => boolean\n /**\n * Include mutations matching this mutation key\n */\n mutationKey?: MutationKey\n /**\n * Filter by mutation status\n */\n status?: MutationStatus\n}\n\nexport type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)\n\nexport type QueryTypeFilter = 'all' | 'active' | 'inactive'\n\n// UTILS\n\nexport const isServer = typeof window === 'undefined' || 'Deno' in globalThis\n\nexport function noop(): undefined {\n return undefined\n}\n\nexport function functionalUpdate<TInput, TOutput>(\n updater: Updater<TInput, TOutput>,\n input: TInput,\n): TOutput {\n return typeof updater === 'function'\n ? (updater as (_: TInput) => TOutput)(input)\n : updater\n}\n\nexport function isValidTimeout(value: unknown): value is number {\n return typeof value === 'number' && value >= 0 && value !== Infinity\n}\n\nexport function timeUntilStale(updatedAt: number, staleTime?: number): number {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)\n}\n\nexport function resolveStaleTime<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n staleTime: undefined | StaleTime<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): number | undefined {\n return typeof staleTime === 'function' ? staleTime(query) : staleTime\n}\n\nexport function resolveEnabled<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n enabled: undefined | Enabled<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): boolean | undefined {\n return typeof enabled === 'function' ? enabled(query) : enabled\n}\n\nexport function matchQuery(\n filters: QueryFilters,\n query: Query<any, any, any, any>,\n): boolean {\n const {\n type = 'all',\n exact,\n fetchStatus,\n predicate,\n queryKey,\n stale,\n } = filters\n\n if (queryKey) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false\n }\n }\n\n if (type !== 'all') {\n const isActive = query.isActive()\n if (type === 'active' && !isActive) {\n return false\n }\n if (type === 'inactive' && isActive) {\n return false\n }\n }\n\n if (typeof stale === 'boolean' && query.isStale() !== stale) {\n return false\n }\n\n if (fetchStatus && fetchStatus !== query.state.fetchStatus) {\n return false\n }\n\n if (predicate && !predicate(query)) {\n return false\n }\n\n return true\n}\n\nexport function matchMutation(\n filters: MutationFilters,\n mutation: Mutation<any, any>,\n): boolean {\n const { exact, status, predicate, mutationKey } = filters\n if (mutationKey) {\n if (!mutation.options.mutationKey) {\n return false\n }\n if (exact) {\n if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {\n return false\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false\n }\n }\n\n if (status && mutation.state.status !== status) {\n return false\n }\n\n if (predicate && !predicate(mutation)) {\n return false\n }\n\n return true\n}\n\nexport function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(\n queryKey: TQueryKey,\n options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,\n): string {\n const hashFn = options?.queryKeyHashFn || hashKey\n return hashFn(queryKey)\n}\n\n/**\n * Default query & mutation keys hash function.\n * Hashes the value into a stable hash.\n */\nexport function hashKey(queryKey: QueryKey | MutationKey): string {\n return JSON.stringify(queryKey, (_, val) =>\n isPlainObject(val)\n ? Object.keys(val)\n .sort()\n .reduce((result, key) => {\n result[key] = val[key]\n return result\n }, {} as any)\n : val,\n )\n}\n\n/**\n * Checks if key `b` partially matches with key `a`.\n */\nexport function partialMatchKey(a: QueryKey, b: QueryKey): boolean\nexport function partialMatchKey(a: any, b: any): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n return !Object.keys(b).some((key) => !partialMatchKey(a[key], b[key]))\n }\n\n return false\n}\n\n/**\n * This function returns `a` if `b` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between JSON values for example.\n */\nexport function replaceEqualDeep<T>(a: unknown, b: T): T\nexport function replaceEqualDeep(a: any, b: any): any {\n if (a === b) {\n return a\n }\n\n const array = isPlainArray(a) && isPlainArray(b)\n\n if (array || (isPlainObject(a) && isPlainObject(b))) {\n const aItems = array ? a : Object.keys(a)\n const aSize = aItems.length\n const bItems = array ? b : Object.keys(b)\n const bSize = bItems.length\n const copy: any = array ? [] : {}\n\n let equalItems = 0\n\n for (let i = 0; i < bSize; i++) {\n const key = array ? i : bItems[i]\n if (\n ((!array && aItems.includes(key)) || array) &&\n a[key] === undefined &&\n b[key] === undefined\n ) {\n copy[key] = undefined\n equalItems++\n } else {\n copy[key] = replaceEqualDeep(a[key], b[key])\n if (copy[key] === a[key] && a[key] !== undefined) {\n equalItems++\n }\n }\n }\n\n return aSize === bSize && equalItems === aSize ? a : copy\n }\n\n return b\n}\n\n/**\n * Shallow compare objects.\n */\nexport function shallowEqualObjects<T extends Record<string, any>>(\n a: T,\n b: T | undefined,\n): boolean {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false\n }\n\n for (const key in a) {\n if (a[key] !== b[key]) {\n return false\n }\n }\n\n return true\n}\n\nexport function isPlainArray(value: unknown) {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\nexport function isPlainObject(o: any): o is Object {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has no constructor\n const ctor = o.constructor\n if (ctor === undefined) {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Handles Objects created by Object.create(<arbitrary prototype>)\n if (Object.getPrototypeOf(o) !== Object.prototype) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\nexport function sleep(timeout: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, timeout)\n })\n}\n\nexport function replaceData<\n TData,\n TOptions extends QueryOptions<any, any, any, any>,\n>(prevData: TData | undefined, data: TData, options: TOptions): TData {\n if (typeof options.structuralSharing === 'function') {\n return options.structuralSharing(prevData, data) as TData\n } else if (options.structuralSharing !== false) {\n // Structurally share data between prev and new data if needed\n return replaceEqualDeep(prevData, data)\n }\n return data\n}\n\nexport function keepPreviousData<T>(\n previousData: T | undefined,\n): T | undefined {\n return previousData\n}\n\nexport function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [...items, item]\n return max && newItems.length > max ? newItems.slice(1) : newItems\n}\n\nexport function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [item, ...items]\n return max && newItems.length > max ? newItems.slice(0, -1) : newItems\n}\n\nexport const skipToken = Symbol()\nexport type SkipToken = typeof skipToken\n\nexport function ensureQueryFn<\n TQueryFnData = unknown,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: {\n queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken\n queryHash?: string\n },\n fetchOptions?: FetchOptions<TQueryFnData>,\n): QueryFunction<TQueryFnData, TQueryKey> {\n if (process.env.NODE_ENV !== 'production') {\n if (options.queryFn === skipToken) {\n console.error(\n `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,\n )\n }\n }\n\n // if we attempt to retry a fetch that was triggered from an initialPromise\n // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise\n // if an observer has already mounted, we will be able to retry with that queryFn\n if (!options.queryFn && fetchOptions?.initialPromise) {\n return () => fetchOptions.initialPromise!\n }\n\n if (!options.queryFn || options.queryFn === skipToken) {\n return () =>\n Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))\n }\n\n return options.queryFn\n}\n"],"mappings":";AAoEO,IAAM,WAAW,OAAO,WAAW,eAAe,UAAU;AAE5D,SAAS,OAAkB;AAChC,SAAO;AACT;AAEO,SAAS,iBACd,SACA,OACS;AACT,SAAO,OAAO,YAAY,aACrB,QAAmC,KAAK,IACzC;AACN;AAEO,SAAS,eAAe,OAAiC;AAC9D,SAAO,OAAO,UAAU,YAAY,SAAS,KAAK,UAAU;AAC9D;AAEO,SAAS,eAAe,WAAmB,WAA4B;AAC5E,SAAO,KAAK,IAAI,aAAa,aAAa,KAAK,KAAK,IAAI,GAAG,CAAC;AAC9D;AAEO,SAAS,iBAMd,WACA,OACoB;AACpB,SAAO,OAAO,cAAc,aAAa,UAAU,K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src/utils.ts"],"sourcesContent":["import type {\n DefaultError,\n Enabled,\n FetchStatus,\n MutationKey,\n MutationStatus,\n QueryFunction,\n QueryKey,\n QueryOptions,\n StaleTime,\n} from './types'\nimport type { Mutation } from './mutation'\nimport type { FetchOptions, Query } from './query'\n\n// TYPES\n\nexport interface QueryFilters {\n /**\n * Filter to active queries, inactive queries or all queries\n */\n type?: QueryTypeFilter\n /**\n * Match query key exactly\n */\n exact?: boolean\n /**\n * Include queries matching this predicate function\n */\n predicate?: (query: Query) => boolean\n /**\n * Include queries matching this query key\n */\n queryKey?: QueryKey\n /**\n * Include or exclude stale queries\n */\n stale?: boolean\n /**\n * Include queries matching their fetchStatus\n */\n fetchStatus?: FetchStatus\n}\n\nexport interface MutationFilters {\n /**\n * Match mutation key exactly\n */\n exact?: boolean\n /**\n * Include mutations matching this predicate function\n */\n predicate?: (mutation: Mutation<any, any, any>) => boolean\n /**\n * Include mutations matching this mutation key\n */\n mutationKey?: MutationKey\n /**\n * Filter by mutation status\n */\n status?: MutationStatus\n}\n\nexport type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)\n\nexport type QueryTypeFilter = 'all' | 'active' | 'inactive'\n\n// UTILS\n\nexport const isServer = typeof window === 'undefined' || 'Deno' in globalThis\n\nexport function noop(): undefined {\n return undefined\n}\n\nexport function functionalUpdate<TInput, TOutput>(\n updater: Updater<TInput, TOutput>,\n input: TInput,\n): TOutput {\n return typeof updater === 'function'\n ? (updater as (_: TInput) => TOutput)(input)\n : updater\n}\n\nexport function isValidTimeout(value: unknown): value is number {\n return typeof value === 'number' && value >= 0 && value !== Infinity\n}\n\nexport function timeUntilStale(updatedAt: number, staleTime?: number): number {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)\n}\n\nexport function resolveStaleTime<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n staleTime: undefined | StaleTime<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): number | undefined {\n return typeof staleTime === 'function' ? staleTime(query) : staleTime\n}\n\nexport function resolveEnabled<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n enabled: undefined | Enabled<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): boolean | undefined {\n return typeof enabled === 'function' ? enabled(query) : enabled\n}\n\nexport function matchQuery(\n filters: QueryFilters,\n query: Query<any, any, any, any>,\n): boolean {\n const {\n type = 'all',\n exact,\n fetchStatus,\n predicate,\n queryKey,\n stale,\n } = filters\n\n if (queryKey) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false\n }\n }\n\n if (type !== 'all') {\n const isActive = query.isActive()\n if (type === 'active' && !isActive) {\n return false\n }\n if (type === 'inactive' && isActive) {\n return false\n }\n }\n\n if (typeof stale === 'boolean' && query.isStale() !== stale) {\n return false\n }\n\n if (fetchStatus && fetchStatus !== query.state.fetchStatus) {\n return false\n }\n\n if (predicate && !predicate(query)) {\n return false\n }\n\n return true\n}\n\nexport function matchMutation(\n filters: MutationFilters,\n mutation: Mutation<any, any>,\n): boolean {\n const { exact, status, predicate, mutationKey } = filters\n if (mutationKey) {\n if (!mutation.options.mutationKey) {\n return false\n }\n if (exact) {\n if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {\n return false\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false\n }\n }\n\n if (status && mutation.state.status !== status) {\n return false\n }\n\n if (predicate && !predicate(mutation)) {\n return false\n }\n\n return true\n}\n\nexport function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(\n queryKey: TQueryKey,\n options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,\n): string {\n const hashFn = options?.queryKeyHashFn || hashKey\n return hashFn(queryKey)\n}\n\n/**\n * Default query & mutation keys hash function.\n * Hashes the value into a stable hash.\n */\nexport function hashKey(queryKey: QueryKey | MutationKey): string {\n return JSON.stringify(queryKey, (_, val) =>\n isPlainObject(val)\n ? Object.keys(val)\n .sort()\n .reduce((result, key) => {\n result[key] = val[key]\n return result\n }, {} as any)\n : val,\n )\n}\n\n/**\n * Checks if key `b` partially matches with key `a`.\n */\nexport function partialMatchKey(a: QueryKey, b: QueryKey): boolean\nexport function partialMatchKey(a: any, b: any): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n return !Object.keys(b).some((key) => !partialMatchKey(a[key], b[key]))\n }\n\n return false\n}\n\n/**\n * This function returns `a` if `b` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between JSON values for example.\n */\nexport function replaceEqualDeep<T>(a: unknown, b: T): T\nexport function replaceEqualDeep(a: any, b: any): any {\n if (a === b) {\n return a\n }\n\n const array = isPlainArray(a) && isPlainArray(b)\n\n if (array || (isPlainObject(a) && isPlainObject(b))) {\n const aItems = array ? a : Object.keys(a)\n const aSize = aItems.length\n const bItems = array ? b : Object.keys(b)\n const bSize = bItems.length\n const copy: any = array ? [] : {}\n\n let equalItems = 0\n\n for (let i = 0; i < bSize; i++) {\n const key = array ? i : bItems[i]\n if (\n ((!array && aItems.includes(key)) || array) &&\n a[key] === undefined &&\n b[key] === undefined\n ) {\n copy[key] = undefined\n equalItems++\n } else {\n copy[key] = replaceEqualDeep(a[key], b[key])\n if (copy[key] === a[key] && a[key] !== undefined) {\n equalItems++\n }\n }\n }\n\n return aSize === bSize && equalItems === aSize ? a : copy\n }\n\n return b\n}\n\n/**\n * Shallow compare objects.\n */\nexport function shallowEqualObjects<T extends Record<string, any>>(\n a: T,\n b: T | undefined,\n): boolean {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false\n }\n\n for (const key in a) {\n if (a[key] !== b[key]) {\n return false\n }\n }\n\n return true\n}\n\nexport function isPlainArray(value: unknown) {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\nexport function isPlainObject(o: any): o is Object {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has no constructor\n const ctor = o.constructor\n if (ctor === undefined) {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Handles Objects created by Object.create(<arbitrary prototype>)\n if (Object.getPrototypeOf(o) !== Object.prototype) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\nexport function sleep(timeout: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, timeout)\n })\n}\n\nexport function replaceData<\n TData,\n TOptions extends QueryOptions<any, any, any, any>,\n>(prevData: TData | undefined, data: TData, options: TOptions): TData {\n if (typeof options.structuralSharing === 'function') {\n return options.structuralSharing(prevData, data) as TData\n } else if (options.structuralSharing !== false) {\n if (process.env.NODE_ENV !== 'production') {\n try {\n JSON.stringify(prevData)\n JSON.stringify(data)\n } catch (error) {\n console.error(\n `StructuralSharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`,\n )\n\n throw new Error('Data is not serializable')\n }\n }\n\n // Structurally share data between prev and new data if needed\n return replaceEqualDeep(prevData, data)\n }\n return data\n}\n\nexport function keepPreviousData<T>(\n previousData: T | undefined,\n): T | undefined {\n return previousData\n}\n\nexport function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [...items, item]\n return max && newItems.length > max ? newItems.slice(1) : newItems\n}\n\nexport function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [item, ...items]\n return max && newItems.length > max ? newItems.slice(0, -1) : newItems\n}\n\nexport const skipToken = Symbol()\nexport type SkipToken = typeof skipToken\n\nexport function ensureQueryFn<\n TQueryFnData = unknown,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: {\n queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken\n queryHash?: string\n },\n fetchOptions?: FetchOptions<TQueryFnData>,\n): QueryFunction<TQueryFnData, TQueryKey> {\n if (process.env.NODE_ENV !== 'production') {\n if (options.queryFn === skipToken) {\n console.error(\n `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,\n )\n }\n }\n\n // if we attempt to retry a fetch that was triggered from an initialPromise\n // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise\n // if an observer has already mounted, we will be able to retry with that queryFn\n if (!options.queryFn && fetchOptions?.initialPromise) {\n return () => fetchOptions.initialPromise!\n }\n\n if (!options.queryFn || options.queryFn === skipToken) {\n return () =>\n Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))\n }\n\n return options.queryFn\n}\n"],"mappings":";AAoEO,IAAM,WAAW,OAAO,WAAW,eAAe,UAAU;AAE5D,SAAS,OAAkB;AAChC,SAAO;AACT;AAEO,SAAS,iBACd,SACA,OACS;AACT,SAAO,OAAO,YAAY,aACrB,QAAmC,KAAK,IACzC;AACN;AAEO,SAAS,eAAe,OAAiC;AAC9D,SAAO,OAAO,UAAU,YAAY,SAAS,KAAK,UAAU;AAC9D;AAEO,SAAS,eAAe,WAAmB,WAA4B;AAC5E,SAAO,KAAK,IAAI,aAAa,aAAa,KAAK,KAAK,IAAI,GAAG,CAAC;AAC9D;AAEO,SAAS,iBAMd,WACA,OACoB;AACpB,SAAO,OAAO,cAAc,aAAa,UAAU,KAAK,IAAI;AAC9D;AAEO,SAAS,eAMd,SACA,OACqB;AACrB,SAAO,OAAO,YAAY,aAAa,QAAQ,KAAK,IAAI;AAC1D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AAW;AACrD,WAAO,MACL,QAAQ,OAAO,IAAI,MAAM,qBAAqB,QAAQ,SAAS,GAAG,CAAC;AAAA,EACvE;AAEA,SAAO,QAAQ;AACjB;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/query-core",
3
- "version": "5.52.3",
3
+ "version": "5.53.1",
4
4
  "description": "The framework agnostic core that powers TanStack Query",
5
5
  "author": "tannerlinsley",
6
6
  "license": "MIT",
@@ -965,4 +965,53 @@ describe('query', () => {
965
965
  await sleep(60) // let it resolve
966
966
  expect(spy).toHaveBeenCalledWith('1 - 2')
967
967
  })
968
+
969
+ it('should have an error status when queryFn data is not serializable', async () => {
970
+ const consoleMock = vi.spyOn(console, 'error')
971
+
972
+ consoleMock.mockImplementation(() => undefined)
973
+
974
+ const key = queryKey()
975
+
976
+ const queryFn = vi.fn()
977
+
978
+ queryFn.mockImplementation(async () => {
979
+ await sleep(10)
980
+
981
+ const data: Array<{
982
+ id: number
983
+ name: string
984
+ link: null | { id: number; name: string; link: unknown }
985
+ }> = Array.from({ length: 5 })
986
+ .fill(null)
987
+ .map((_, index) => ({
988
+ id: index,
989
+ name: `name-${index}`,
990
+ link: null,
991
+ }))
992
+
993
+ if (data[0] && data[1]) {
994
+ data[0].link = data[1]
995
+ data[1].link = data[0]
996
+ }
997
+
998
+ return data
999
+ })
1000
+
1001
+ await queryClient.prefetchQuery({ queryKey: key, queryFn })
1002
+
1003
+ const query = queryCache.find({ queryKey: key })!
1004
+
1005
+ expect(queryFn).toHaveBeenCalledTimes(1)
1006
+
1007
+ expect(consoleMock).toHaveBeenCalledWith(
1008
+ expect.stringContaining(
1009
+ 'StructuralSharing requires data to be JSON serializable',
1010
+ ),
1011
+ )
1012
+
1013
+ expect(query.state.status).toBe('error')
1014
+
1015
+ consoleMock.mockRestore()
1016
+ })
968
1017
  })
package/src/query.ts CHANGED
@@ -499,7 +499,12 @@ export class Query<
499
499
  return
500
500
  }
501
501
 
502
- this.setData(data)
502
+ try {
503
+ this.setData(data)
504
+ } catch (error) {
505
+ onError(error as TError)
506
+ return
507
+ }
503
508
 
504
509
  // Notify cache callback
505
510
  this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
package/src/utils.ts CHANGED
@@ -353,6 +353,19 @@ export function replaceData<
353
353
  if (typeof options.structuralSharing === 'function') {
354
354
  return options.structuralSharing(prevData, data) as TData
355
355
  } else if (options.structuralSharing !== false) {
356
+ if (process.env.NODE_ENV !== 'production') {
357
+ try {
358
+ JSON.stringify(prevData)
359
+ JSON.stringify(data)
360
+ } catch (error) {
361
+ console.error(
362
+ `StructuralSharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`,
363
+ )
364
+
365
+ throw new Error('Data is not serializable')
366
+ }
367
+ }
368
+
356
369
  // Structurally share data between prev and new data if needed
357
370
  return replaceEqualDeep(prevData, data)
358
371
  }