@tanstack/query-core 5.105.1 → 5.105.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/legacy/{hydration-gHEs4kLM.d.ts → hydration-9_kOYxJM.d.ts} +26 -15
- package/build/legacy/hydration-9_kOYxJM.d.ts.map +1 -0
- package/build/legacy/{hydration-DdkP3REv.d.cts → hydration-BIRJt69T.d.cts} +26 -15
- package/build/legacy/hydration-BIRJt69T.d.cts.map +1 -0
- package/build/legacy/hydration.d.cts +1 -1
- package/build/legacy/hydration.d.ts +1 -1
- package/build/legacy/index.d.cts +1 -1
- package/build/legacy/index.d.ts +1 -1
- package/build/legacy/infiniteQueryBehavior.cjs +2 -1
- package/build/legacy/infiniteQueryBehavior.cjs.map +1 -1
- package/build/legacy/infiniteQueryBehavior.d.cts +1 -1
- package/build/legacy/infiniteQueryBehavior.d.cts.map +1 -1
- package/build/legacy/infiniteQueryBehavior.d.ts +1 -1
- package/build/legacy/infiniteQueryBehavior.d.ts.map +1 -1
- package/build/legacy/infiniteQueryBehavior.js +3 -2
- package/build/legacy/infiniteQueryBehavior.js.map +1 -1
- package/build/legacy/infiniteQueryObserver.d.cts +1 -1
- package/build/legacy/infiniteQueryObserver.d.ts +1 -1
- package/build/legacy/mutation.cjs +1 -0
- package/build/legacy/mutation.cjs.map +1 -1
- package/build/legacy/mutation.d.cts +1 -1
- package/build/legacy/mutation.d.ts +1 -1
- package/build/legacy/mutation.js +1 -0
- package/build/legacy/mutation.js.map +1 -1
- package/build/legacy/mutationCache.d.cts +1 -1
- package/build/legacy/mutationCache.d.ts +1 -1
- package/build/legacy/mutationObserver.d.cts +1 -1
- package/build/legacy/mutationObserver.d.ts +1 -1
- package/build/legacy/queriesObserver.d.cts +1 -1
- package/build/legacy/queriesObserver.d.ts +1 -1
- package/build/legacy/query.cjs +56 -37
- package/build/legacy/query.cjs.map +1 -1
- package/build/legacy/query.d.cts +1 -1
- package/build/legacy/query.d.ts +1 -1
- package/build/legacy/query.js +57 -38
- package/build/legacy/query.js.map +1 -1
- package/build/legacy/queryCache.d.cts +1 -1
- package/build/legacy/queryCache.d.ts +1 -1
- package/build/legacy/queryClient.cjs +11 -6
- package/build/legacy/queryClient.cjs.map +1 -1
- package/build/legacy/queryClient.d.cts +1 -1
- package/build/legacy/queryClient.d.ts +1 -1
- package/build/legacy/queryClient.js +11 -6
- package/build/legacy/queryClient.js.map +1 -1
- package/build/legacy/queryObserver.d.cts +1 -1
- package/build/legacy/queryObserver.d.ts +1 -1
- package/build/legacy/retryer.cjs +1 -1
- package/build/legacy/retryer.cjs.map +1 -1
- package/build/legacy/retryer.d.cts +1 -1
- package/build/legacy/retryer.d.ts +1 -1
- package/build/legacy/retryer.js +1 -1
- package/build/legacy/retryer.js.map +1 -1
- package/build/legacy/streamedQuery.cjs +10 -4
- package/build/legacy/streamedQuery.cjs.map +1 -1
- package/build/legacy/streamedQuery.d.cts +3 -1
- package/build/legacy/streamedQuery.d.cts.map +1 -1
- package/build/legacy/streamedQuery.d.ts +3 -1
- package/build/legacy/streamedQuery.d.ts.map +1 -1
- package/build/legacy/streamedQuery.js +11 -5
- package/build/legacy/streamedQuery.js.map +1 -1
- package/build/legacy/types.d.cts +1 -1
- package/build/legacy/types.d.ts +1 -1
- package/build/legacy/utils.cjs +23 -19
- package/build/legacy/utils.cjs.map +1 -1
- package/build/legacy/utils.d.cts +2 -2
- package/build/legacy/utils.d.ts +2 -2
- package/build/legacy/utils.js +23 -20
- package/build/legacy/utils.js.map +1 -1
- package/build/modern/{hydration-gHEs4kLM.d.ts → hydration-9_kOYxJM.d.ts} +26 -15
- package/build/modern/hydration-9_kOYxJM.d.ts.map +1 -0
- package/build/modern/{hydration-DdkP3REv.d.cts → hydration-BIRJt69T.d.cts} +26 -15
- package/build/modern/hydration-BIRJt69T.d.cts.map +1 -0
- package/build/modern/hydration.d.cts +1 -1
- package/build/modern/hydration.d.ts +1 -1
- package/build/modern/index.d.cts +1 -1
- package/build/modern/index.d.ts +1 -1
- package/build/modern/infiniteQueryBehavior.cjs +2 -1
- package/build/modern/infiniteQueryBehavior.cjs.map +1 -1
- package/build/modern/infiniteQueryBehavior.d.cts +1 -1
- package/build/modern/infiniteQueryBehavior.d.cts.map +1 -1
- package/build/modern/infiniteQueryBehavior.d.ts +1 -1
- package/build/modern/infiniteQueryBehavior.d.ts.map +1 -1
- package/build/modern/infiniteQueryBehavior.js +3 -2
- package/build/modern/infiniteQueryBehavior.js.map +1 -1
- package/build/modern/infiniteQueryObserver.d.cts +1 -1
- package/build/modern/infiniteQueryObserver.d.ts +1 -1
- package/build/modern/mutation.cjs +1 -0
- package/build/modern/mutation.cjs.map +1 -1
- package/build/modern/mutation.d.cts +1 -1
- package/build/modern/mutation.d.ts +1 -1
- package/build/modern/mutation.js +1 -0
- package/build/modern/mutation.js.map +1 -1
- package/build/modern/mutationCache.d.cts +1 -1
- package/build/modern/mutationCache.d.ts +1 -1
- package/build/modern/mutationObserver.d.cts +1 -1
- package/build/modern/mutationObserver.d.ts +1 -1
- package/build/modern/queriesObserver.d.cts +1 -1
- package/build/modern/queriesObserver.d.ts +1 -1
- package/build/modern/query.cjs +53 -35
- package/build/modern/query.cjs.map +1 -1
- package/build/modern/query.d.cts +1 -1
- package/build/modern/query.d.ts +1 -1
- package/build/modern/query.js +54 -36
- package/build/modern/query.js.map +1 -1
- package/build/modern/queryCache.d.cts +1 -1
- package/build/modern/queryCache.d.ts +1 -1
- package/build/modern/queryClient.cjs +11 -6
- package/build/modern/queryClient.cjs.map +1 -1
- package/build/modern/queryClient.d.cts +1 -1
- package/build/modern/queryClient.d.ts +1 -1
- package/build/modern/queryClient.js +11 -6
- package/build/modern/queryClient.js.map +1 -1
- package/build/modern/queryObserver.d.cts +1 -1
- package/build/modern/queryObserver.d.ts +1 -1
- package/build/modern/retryer.cjs +1 -1
- package/build/modern/retryer.cjs.map +1 -1
- package/build/modern/retryer.d.cts +1 -1
- package/build/modern/retryer.d.ts +1 -1
- package/build/modern/retryer.js +1 -1
- package/build/modern/retryer.js.map +1 -1
- package/build/modern/streamedQuery.cjs +10 -4
- package/build/modern/streamedQuery.cjs.map +1 -1
- package/build/modern/streamedQuery.d.cts +3 -1
- package/build/modern/streamedQuery.d.cts.map +1 -1
- package/build/modern/streamedQuery.d.ts +3 -1
- package/build/modern/streamedQuery.d.ts.map +1 -1
- package/build/modern/streamedQuery.js +11 -5
- package/build/modern/streamedQuery.js.map +1 -1
- package/build/modern/types.d.cts +1 -1
- package/build/modern/types.d.ts +1 -1
- package/build/modern/utils.cjs +23 -19
- package/build/modern/utils.cjs.map +1 -1
- package/build/modern/utils.d.cts +2 -2
- package/build/modern/utils.d.ts +2 -2
- package/build/modern/utils.js +23 -20
- package/build/modern/utils.js.map +1 -1
- package/package.json +1 -1
- package/src/infiniteQueryBehavior.ts +5 -1
- package/src/mutation.ts +4 -0
- package/src/query.ts +83 -65
- package/src/queryClient.ts +16 -10
- package/src/retryer.ts +3 -1
- package/src/streamedQuery.ts +14 -3
- package/src/utils.ts +39 -26
- package/build/legacy/hydration-DdkP3REv.d.cts.map +0 -1
- package/build/legacy/hydration-gHEs4kLM.d.ts.map +0 -1
- package/build/modern/hydration-DdkP3REv.d.cts.map +0 -1
- package/build/modern/hydration-gHEs4kLM.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retryer.cjs","names":["onlineManager","noop","focusManager","isServerEnvironment"],"sources":["../../src/retryer.ts"],"sourcesContent":["import { focusManager } from './focusManager'\nimport { onlineManager } from './onlineManager'\nimport { isServer as isServerEnvironment } from './environmentManager'\nimport { noop, sleep } from './utils'\nimport type { CancelOptions, DefaultError, NetworkMode } from './types'\n\n// TYPES\n\ninterface RetryerConfig<TData = unknown, TError = DefaultError> {\n fn: () => TData | Promise<TData>\n initialPromise?: Promise<TData>\n onCancel?: (error: TError) => void\n onFail?: (failureCount: number, error: TError) => void\n onPause?: () => void\n onContinue?: () => void\n retry?: RetryValue<TError>\n retryDelay?: RetryDelayValue<TError>\n networkMode: NetworkMode | undefined\n canRun: () => boolean\n}\n\n/**\n * Runs a function with retries, and can pause, continue, or cancel it. Queries and mutations use\n * one for each fetch or execution.\n */\nexport interface Retryer<TData = unknown> {\n /**\n * The promise that resolves with the data, or rejects once retries are exhausted or it is\n * cancelled.\n */\n promise: Promise<TData>\n /**\n * Cancels the run, rejecting `promise` with a `CancelledError`.\n */\n cancel: (cancelOptions?: CancelOptions) => void\n /**\n * Resumes a paused run, and returns `promise`.\n */\n continue: () => Promise<unknown>\n /**\n * Stops further retries. The current attempt still finishes.\n */\n cancelRetry: () => void\n /**\n * Allows retries again after `cancelRetry`.\n */\n continueRetry: () => void\n /**\n * Returns whether the run can start now, based on the network mode and `canRun`.\n */\n canStart: () => boolean\n /**\n * Starts the run, or waits until it can start, and returns `promise`.\n */\n start: () => Promise<TData>\n /**\n * Returns whether `promise` is still pending, resolved, or rejected.\n */\n status: () => 'pending' | 'resolved' | 'rejected'\n}\n\ntype RetryerStatus = 'pending' | 'resolved' | 'rejected'\n\n/** @inline */\nexport type RetryValue<TError> = boolean | number | ShouldRetryFunction<TError>\n\n/** @inline */\ntype ShouldRetryFunction<TError = DefaultError> = (\n failureCount: number,\n error: TError,\n) => boolean\n\n/** @inline */\nexport type RetryDelayValue<TError> = number | RetryDelayFunction<TError>\n\n/** @inline */\ntype RetryDelayFunction<TError = DefaultError> = (\n failureCount: number,\n error: TError,\n) => number\n\n/**\n * The default `retryDelay`: doubles with every failure, starting at 1 second, up to 30 seconds.\n * @param failureCount - The number of failures so far.\n * @returns The delay before the next retry, in milliseconds.\n */\nfunction defaultRetryDelay(failureCount: number) {\n return Math.min(1000 * 2 ** failureCount, 30000)\n}\n\n/**\n * Checks whether a fetch can run for the given network mode.\n * @param networkMode - The `networkMode` option. Defaults to `'online'`.\n * @returns `true` if the network mode is not `'online'`, or if it is and the client is online.\n */\nexport function canFetch(networkMode: NetworkMode | undefined): boolean {\n return (networkMode ?? 'online') === 'online'\n ? onlineManager.isOnline()\n : true\n}\n\n/**\n * The error thrown by a `Retryer` (and surfaced to `query.promise`/`mutation`) when a fetch is cancelled, e.g. via\n * `query.cancel()`. `revert`, if `true`, tells the caller to restore the state the query was in before the fetch\n * started instead of surfacing the error. `silent`, if `true`, tells the caller to suppress this error and instead\n * resolve with the promise of the fetch that triggered the cancellation.\n * @example\n * ```ts\n * query.cancel()\n *\n * try {\n * await query.promise\n * } catch (error) {\n * if (error instanceof CancelledError) {\n * // the fetch was cancelled, e.g. via `query.cancel()`\n * }\n * }\n * ```\n */\nexport class CancelledError extends Error {\n revert?: boolean\n silent?: boolean\n constructor(options?: CancelOptions) {\n super('CancelledError')\n this.revert = options?.revert\n this.silent = options?.silent\n }\n}\n\n/**\n * Checks whether a value is a `CancelledError`.\n * @param value - The value to check.\n * @returns `true` if `value` is a `CancelledError`.\n * @deprecated Use instanceof `CancelledError` instead.\n */\nexport function isCancelledError(value: any): value is CancelledError {\n return value instanceof CancelledError\n}\n\n/**\n * Creates a retryer, which runs a function and retries it on failure according to the `retry` and\n * `retryDelay` options. It pauses while the network mode doesn't allow fetching or `canRun` returns\n * `false`, and can be cancelled. Queries and mutations use it to run their `queryFn` and\n * `mutationFn`.\n * @param config - The function to run, the retry options, and the callbacks for failures, pausing,\n * continuing, and cancellation.\n * @returns The retryer, whose `promise` settles with the result of the function.\n */\nexport function createRetryer<TData = unknown, TError = DefaultError>(\n config: RetryerConfig<TData, TError>,\n): Retryer<TData> {\n let isRetryCancelled = false\n let failureCount = 0\n let continueFn: ((value?: unknown) => void) | undefined\n let status: RetryerStatus = 'pending'\n let promiseResolve: (data: TData) => void\n let promiseReject: (error: TError) => void\n\n const promise = new Promise<TData>((resolve, reject) => {\n promiseResolve = resolve\n promiseReject = reject\n })\n promise.catch(noop)\n\n const isResolved = () => status !== 'pending'\n\n const cancel = (cancelOptions?: CancelOptions): void => {\n if (!isResolved()) {\n const error = new CancelledError(cancelOptions) as TError\n reject(error)\n\n config.onCancel?.(error)\n }\n }\n const cancelRetry = () => {\n isRetryCancelled = true\n }\n\n const continueRetry = () => {\n isRetryCancelled = false\n }\n\n const canContinue = () =>\n focusManager.isFocused() &&\n (config.networkMode === 'always' || onlineManager.isOnline()) &&\n config.canRun()\n\n const canStart = () => canFetch(config.networkMode) && config.canRun()\n\n const resolve = (value: any) => {\n if (!isResolved()) {\n continueFn?.()\n status = 'resolved'\n promiseResolve(value)\n }\n }\n\n const reject = (value: any) => {\n if (!isResolved()) {\n continueFn?.()\n status = 'rejected'\n promiseReject(value)\n }\n }\n\n const pause = (canResume: () => boolean) => {\n return new Promise((continueResolve) => {\n continueFn = (value) => {\n if (isResolved() || canResume()) {\n continueResolve(value)\n }\n }\n config.onPause?.()\n }).then(() => {\n continueFn = undefined\n if (!isResolved()) {\n config.onContinue?.()\n }\n })\n }\n\n // Create loop function\n const run = () => {\n // Do nothing if already resolved\n if (isResolved()) {\n return\n }\n\n let promiseOrValue: any\n\n // we can re-use config.initialPromise on the first call of run()\n const initialPromise =\n failureCount === 0 ? config.initialPromise : undefined\n\n // Execute query\n try {\n promiseOrValue = initialPromise ?? config.fn()\n } catch (error) {\n promiseOrValue = Promise.reject(error)\n }\n\n Promise.resolve(promiseOrValue)\n .then(resolve)\n .catch((error) => {\n // Stop if the fetch is already resolved\n if (isResolved()) {\n return\n }\n\n // Do we need to retry the request?\n const retry = config.retry ?? (isServerEnvironment() ? 0 : 3)\n const retryDelay = config.retryDelay ?? defaultRetryDelay\n const delay =\n typeof retryDelay === 'function'\n ? retryDelay(failureCount, error)\n : retryDelay\n const shouldRetry =\n retry === true ||\n (typeof retry === 'number' && failureCount < retry) ||\n (typeof retry === 'function' && retry(failureCount, error))\n\n if (isRetryCancelled || !shouldRetry) {\n // We are done if the query does not need to be retried\n reject(error)\n return\n }\n\n failureCount++\n\n // Notify on fail\n config.onFail?.(failureCount, error)\n\n // Delay\n sleep(delay)\n // Pause if the document is not visible or when the device is offline\n .then(() => {\n return canContinue() ? undefined : pause(canContinue)\n })\n .then(() => {\n if (isRetryCancelled) {\n reject(error)\n } else {\n run()\n }\n })\n })\n }\n\n return {\n promise,\n status: () => status,\n cancel,\n continue: () => {\n continueFn?.()\n return promise\n },\n cancelRetry,\n continueRetry,\n canStart,\n start: () => {\n // Start loop\n if (canStart()) {\n run()\n } else {\n // Waiting to start (e.g. queued behind a scope) does not depend on focus,\n // only on the same conditions that allow starting in the first place\n pause(canStart).then(run)\n }\n return promise\n },\n }\n}\n"],"mappings":";;;;;;;;;;;AAsFA,SAAS,kBAAkB,cAAsB;CAC/C,OAAO,KAAK,IAAI,MAAO,KAAK,cAAc,GAAK;AACjD;;;;;;AAOA,SAAgB,SAAS,aAA+C;CACtE,QAAQ,eAAe,cAAc,WACjCA,sBAAAA,cAAc,SAAS,IACvB;AACN;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,iBAAb,cAAoC,MAAM;CAGxC,YAAY,SAAyB;EACnC,MAAM,gBAAgB;EACtB,KAAK,SAAS,SAAS;EACvB,KAAK,SAAS,SAAS;CACzB;AACF;;;;;;;AAQA,SAAgB,iBAAiB,OAAqC;CACpE,OAAO,iBAAiB;AAC1B;;;;;;;;;;AAWA,SAAgB,cACd,QACgB;CAChB,IAAI,mBAAmB;CACvB,IAAI,eAAe;CACnB,IAAI;CACJ,IAAI,SAAwB;CAC5B,IAAI;CACJ,IAAI;CAEJ,MAAM,UAAU,IAAI,SAAgB,SAAS,WAAW;EACtD,iBAAiB;EACjB,gBAAgB;CAClB,CAAC;CACD,QAAQ,MAAMC,cAAAA,IAAI;CAElB,MAAM,mBAAmB,WAAW;CAEpC,MAAM,UAAU,kBAAwC;EACtD,IAAI,CAAC,WAAW,GAAG;GACjB,MAAM,QAAQ,IAAI,eAAe,aAAa;GAC9C,OAAO,KAAK;GAEZ,OAAO,WAAW,KAAK;EACzB;CACF;CACA,MAAM,oBAAoB;EACxB,mBAAmB;CACrB;CAEA,MAAM,sBAAsB;EAC1B,mBAAmB;CACrB;CA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,OAAO,KAAK;IACZ;GACF;GAEA;GAGA,OAAO,SAAS,cAAc,KAAK;GAGnC,cAAA,MAAM,KAAK,CAAC,CAET,WAAW;IACV,OAAO,YAAY,IAAI,KAAA,IAAY,MAAM,WAAW;GACtD,CAAC,CAAC,CACD,WAAW;IACV,IAAI,kBACF,OAAO,KAAK;SAEZ,IAAI;GAER,CAAC;EACL,CAAC;CACL;CAEA,OAAO;EACL;EACA,cAAc;EACd;EACA,gBAAgB;GACd,aAAa;GACb,OAAO;EACT;EACA;EACA;EACA;EACA,aAAa;GAEX,IAAI,SAAS,GACX,IAAI;QAIJ,MAAM,QAAQ,CAAC,CAAC,KAAK,GAAG;GAE1B,OAAO;EACT;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"retryer.cjs","names":["onlineManager","noop","focusManager","isServerEnvironment"],"sources":["../../src/retryer.ts"],"sourcesContent":["import { focusManager } from './focusManager'\nimport { onlineManager } from './onlineManager'\nimport { isServer as isServerEnvironment } from './environmentManager'\nimport { noop, sleep } from './utils'\nimport type { CancelOptions, DefaultError, NetworkMode } from './types'\n\n// TYPES\n\ninterface RetryerConfig<TData = unknown, TError = DefaultError> {\n fn: () => TData | Promise<TData>\n initialPromise?: Promise<TData>\n onCancel?: (error: TError) => void\n onFail?: (failureCount: number, error: TError) => void\n onPause?: () => void\n onContinue?: () => void\n retry?: RetryValue<TError>\n retryDelay?: RetryDelayValue<TError>\n networkMode: NetworkMode | undefined\n canRun: () => boolean\n}\n\n/**\n * Runs a function with retries, and can pause, continue, or cancel it. Queries and mutations use\n * one for each fetch or execution.\n */\nexport interface Retryer<TData = unknown> {\n /**\n * The promise that resolves with the data, or rejects once retries are exhausted or it is\n * cancelled.\n */\n promise: Promise<TData>\n /**\n * Cancels the run, rejecting `promise` with a `CancelledError`.\n */\n cancel: (cancelOptions?: CancelOptions) => void\n /**\n * Resumes a paused run, and returns `promise`.\n */\n continue: () => Promise<unknown>\n /**\n * Stops further retries. The current attempt still finishes.\n */\n cancelRetry: () => void\n /**\n * Allows retries again after `cancelRetry`.\n */\n continueRetry: () => void\n /**\n * Returns whether the run can start now, based on the network mode and `canRun`.\n */\n canStart: () => boolean\n /**\n * Starts the run, or waits until it can start, and returns `promise`.\n */\n start: () => Promise<TData>\n /**\n * Returns whether `promise` is still pending, resolved, or rejected.\n */\n status: () => 'pending' | 'resolved' | 'rejected'\n}\n\ntype RetryerStatus = 'pending' | 'resolved' | 'rejected'\n\n/** @inline */\nexport type RetryValue<TError> = boolean | number | ShouldRetryFunction<TError>\n\n/** @inline */\ntype ShouldRetryFunction<TError = DefaultError> = (\n failureCount: number,\n error: TError,\n) => boolean\n\n/** @inline */\nexport type RetryDelayValue<TError> = number | RetryDelayFunction<TError>\n\n/** @inline */\ntype RetryDelayFunction<TError = DefaultError> = (\n failureCount: number,\n error: TError,\n) => number\n\n/**\n * The default `retryDelay`: doubles with every failure, starting at 1 second, up to 30 seconds.\n * @param failureCount - The number of failures so far.\n * @returns The delay before the next retry, in milliseconds.\n */\nfunction defaultRetryDelay(failureCount: number) {\n return Math.min(1000 * 2 ** failureCount, 30000)\n}\n\n/**\n * Checks whether a fetch can run for the given network mode.\n * @param networkMode - The `networkMode` option. Defaults to `'online'`.\n * @returns `true` if the network mode is not `'online'`, or if it is and the client is online.\n */\nexport function canFetch(networkMode: NetworkMode | undefined): boolean {\n return (networkMode ?? 'online') === 'online'\n ? onlineManager.isOnline()\n : true\n}\n\n/**\n * The error thrown by a `Retryer` (and surfaced to `query.promise`/`mutation`) when a fetch is cancelled, e.g. via\n * `query.cancel()`. `revert`, if `true`, tells the caller to restore the state the query was in before the fetch\n * started instead of surfacing the error. `silent`, if `true`, tells the caller to suppress this error and instead\n * resolve with the promise of the fetch that triggered the cancellation.\n * @example\n * ```ts\n * query.cancel()\n *\n * try {\n * await query.promise\n * } catch (error) {\n * if (error instanceof CancelledError) {\n * // the fetch was cancelled, e.g. via `query.cancel()`\n * }\n * }\n * ```\n */\nexport class CancelledError extends Error {\n revert?: boolean\n silent?: boolean\n constructor(options?: CancelOptions) {\n super('CancelledError')\n this.revert = options?.revert\n this.silent = options?.silent\n }\n}\n\n/**\n * Checks whether a value is a `CancelledError`.\n * @param value - The value to check.\n * @returns `true` if `value` is a `CancelledError`.\n * @deprecated Use instanceof `CancelledError` instead.\n */\nexport function isCancelledError(value: any): value is CancelledError {\n return value instanceof CancelledError\n}\n\n/**\n * Creates a retryer, which runs a function and retries it on failure according to the `retry` and\n * `retryDelay` options. It pauses while the network mode doesn't allow fetching or `canRun` returns\n * `false`, and can be cancelled. Queries and mutations use it to run their `queryFn` and\n * `mutationFn`.\n * @param config - The function to run, the retry options, and the callbacks for failures, pausing,\n * continuing, and cancellation.\n * @returns The retryer, whose `promise` settles with the result of the function.\n */\nexport function createRetryer<TData = unknown, TError = DefaultError>(\n config: RetryerConfig<TData, TError>,\n): Retryer<TData> {\n let isRetryCancelled = false\n let failureCount = 0\n let continueFn: ((value?: unknown) => void) | undefined\n let status: RetryerStatus = 'pending'\n let promiseResolve: (data: TData) => void\n let promiseReject: (error: TError) => void\n\n const promise = new Promise<TData>((resolve, reject) => {\n promiseResolve = resolve\n promiseReject = reject\n })\n promise.catch(noop)\n\n const isResolved = () => status !== 'pending'\n\n const cancel = (cancelOptions?: CancelOptions): void => {\n if (!isResolved()) {\n const error = new CancelledError(cancelOptions) as TError\n reject(error)\n\n config.onCancel?.(error)\n }\n }\n const cancelRetry = () => {\n isRetryCancelled = true\n }\n\n const continueRetry = () => {\n isRetryCancelled = false\n }\n\n const canContinue = () =>\n focusManager.isFocused() &&\n (config.networkMode === 'always' || onlineManager.isOnline()) &&\n config.canRun()\n\n const canStart = () => canFetch(config.networkMode) && config.canRun()\n\n const resolve = (value: any) => {\n if (!isResolved()) {\n continueFn?.()\n status = 'resolved'\n promiseResolve(value)\n }\n }\n\n const reject = (value: any) => {\n if (!isResolved()) {\n continueFn?.()\n status = 'rejected'\n promiseReject(value)\n }\n }\n\n const pause = (canResume: () => boolean) => {\n return new Promise((continueResolve) => {\n continueFn = (value) => {\n if (isResolved() || canResume()) {\n continueResolve(value)\n }\n }\n config.onPause?.()\n }).then(() => {\n continueFn = undefined\n if (!isResolved()) {\n config.onContinue?.()\n }\n })\n }\n\n // Create loop function\n const run = () => {\n // Do nothing if already resolved\n if (isResolved()) {\n return\n }\n\n let promiseOrValue: any\n\n // we can re-use config.initialPromise on the first call of run()\n const initialPromise =\n failureCount === 0 ? config.initialPromise : undefined\n\n // Execute query\n try {\n promiseOrValue = initialPromise ?? config.fn()\n } catch (error) {\n promiseOrValue = Promise.reject(error)\n }\n\n Promise.resolve(promiseOrValue)\n .then(resolve)\n .catch((error) => {\n // Stop if the fetch is already resolved\n if (isResolved()) {\n return\n }\n\n // Do we need to retry the request?\n const retry = config.retry ?? (isServerEnvironment() ? 0 : 3)\n const retryDelay = config.retryDelay ?? defaultRetryDelay\n const delay =\n typeof retryDelay === 'function'\n ? retryDelay(failureCount, error)\n : retryDelay\n const shouldRetry =\n retry === true ||\n (typeof retry === 'number' && failureCount < retry) ||\n (typeof retry === 'function' && retry(failureCount, error))\n\n if (isRetryCancelled || !shouldRetry) {\n // We are done if the query does not need to be retried\n reject(error)\n return\n }\n\n failureCount++\n\n // Notify on fail\n config.onFail?.(failureCount, error)\n\n // Delay\n sleep(delay)\n // Pause if the document is not visible or when the device is offline\n .then(() => {\n return isResolved() || canContinue()\n ? undefined\n : pause(canContinue)\n })\n .then(() => {\n if (isRetryCancelled) {\n reject(error)\n } else {\n run()\n }\n })\n })\n }\n\n return {\n promise,\n status: () => status,\n cancel,\n continue: () => {\n continueFn?.()\n return promise\n },\n cancelRetry,\n continueRetry,\n canStart,\n start: () => {\n // Start loop\n if (canStart()) {\n run()\n } else {\n // Waiting to start (e.g. queued behind a scope) does not depend on focus,\n // only on the same conditions that allow starting in the first place\n pause(canStart).then(run)\n }\n return promise\n },\n }\n}\n"],"mappings":";;;;;;;;;;;AAsFA,SAAS,kBAAkB,cAAsB;CAC/C,OAAO,KAAK,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S,GACX,IAAI;QAIJ,MAAM,QAAQ,CAAC,CAAC,KAAK,GAAG;GAE1B,OAAO;EACT;CACF;AACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $t as CancelledError, an as isCancelledError, en as RetryDelayValue, in as createRetryer, nn as Retryer, rn as canFetch, tn as RetryValue } from "./hydration-
|
|
1
|
+
import { $t as CancelledError, an as isCancelledError, en as RetryDelayValue, in as createRetryer, nn as Retryer, rn as canFetch, tn as RetryValue } from "./hydration-BIRJt69T.cjs";
|
|
2
2
|
export { CancelledError, RetryDelayValue, RetryValue, Retryer, canFetch, createRetryer, isCancelledError };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $t as CancelledError, an as isCancelledError, en as RetryDelayValue, in as createRetryer, nn as Retryer, rn as canFetch, tn as RetryValue } from "./hydration-
|
|
1
|
+
import { $t as CancelledError, an as isCancelledError, en as RetryDelayValue, in as createRetryer, nn as Retryer, rn as canFetch, tn as RetryValue } from "./hydration-9_kOYxJM.js";
|
|
2
2
|
export { CancelledError, RetryDelayValue, RetryValue, Retryer, canFetch, createRetryer, isCancelledError };
|
package/build/modern/retryer.js
CHANGED
|
@@ -137,7 +137,7 @@ function createRetryer(config) {
|
|
|
137
137
|
failureCount++;
|
|
138
138
|
config.onFail?.(failureCount, error);
|
|
139
139
|
sleep(delay).then(() => {
|
|
140
|
-
return canContinue() ? void 0 : pause(canContinue);
|
|
140
|
+
return isResolved() || canContinue() ? void 0 : pause(canContinue);
|
|
141
141
|
}).then(() => {
|
|
142
142
|
if (isRetryCancelled) reject(error);
|
|
143
143
|
else run();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retryer.js","names":["isServerEnvironment"],"sources":["../../src/retryer.ts"],"sourcesContent":["import { focusManager } from './focusManager'\nimport { onlineManager } from './onlineManager'\nimport { isServer as isServerEnvironment } from './environmentManager'\nimport { noop, sleep } from './utils'\nimport type { CancelOptions, DefaultError, NetworkMode } from './types'\n\n// TYPES\n\ninterface RetryerConfig<TData = unknown, TError = DefaultError> {\n fn: () => TData | Promise<TData>\n initialPromise?: Promise<TData>\n onCancel?: (error: TError) => void\n onFail?: (failureCount: number, error: TError) => void\n onPause?: () => void\n onContinue?: () => void\n retry?: RetryValue<TError>\n retryDelay?: RetryDelayValue<TError>\n networkMode: NetworkMode | undefined\n canRun: () => boolean\n}\n\n/**\n * Runs a function with retries, and can pause, continue, or cancel it. Queries and mutations use\n * one for each fetch or execution.\n */\nexport interface Retryer<TData = unknown> {\n /**\n * The promise that resolves with the data, or rejects once retries are exhausted or it is\n * cancelled.\n */\n promise: Promise<TData>\n /**\n * Cancels the run, rejecting `promise` with a `CancelledError`.\n */\n cancel: (cancelOptions?: CancelOptions) => void\n /**\n * Resumes a paused run, and returns `promise`.\n */\n continue: () => Promise<unknown>\n /**\n * Stops further retries. The current attempt still finishes.\n */\n cancelRetry: () => void\n /**\n * Allows retries again after `cancelRetry`.\n */\n continueRetry: () => void\n /**\n * Returns whether the run can start now, based on the network mode and `canRun`.\n */\n canStart: () => boolean\n /**\n * Starts the run, or waits until it can start, and returns `promise`.\n */\n start: () => Promise<TData>\n /**\n * Returns whether `promise` is still pending, resolved, or rejected.\n */\n status: () => 'pending' | 'resolved' | 'rejected'\n}\n\ntype RetryerStatus = 'pending' | 'resolved' | 'rejected'\n\n/** @inline */\nexport type RetryValue<TError> = boolean | number | ShouldRetryFunction<TError>\n\n/** @inline */\ntype ShouldRetryFunction<TError = DefaultError> = (\n failureCount: number,\n error: TError,\n) => boolean\n\n/** @inline */\nexport type RetryDelayValue<TError> = number | RetryDelayFunction<TError>\n\n/** @inline */\ntype RetryDelayFunction<TError = DefaultError> = (\n failureCount: number,\n error: TError,\n) => number\n\n/**\n * The default `retryDelay`: doubles with every failure, starting at 1 second, up to 30 seconds.\n * @param failureCount - The number of failures so far.\n * @returns The delay before the next retry, in milliseconds.\n */\nfunction defaultRetryDelay(failureCount: number) {\n return Math.min(1000 * 2 ** failureCount, 30000)\n}\n\n/**\n * Checks whether a fetch can run for the given network mode.\n * @param networkMode - The `networkMode` option. Defaults to `'online'`.\n * @returns `true` if the network mode is not `'online'`, or if it is and the client is online.\n */\nexport function canFetch(networkMode: NetworkMode | undefined): boolean {\n return (networkMode ?? 'online') === 'online'\n ? onlineManager.isOnline()\n : true\n}\n\n/**\n * The error thrown by a `Retryer` (and surfaced to `query.promise`/`mutation`) when a fetch is cancelled, e.g. via\n * `query.cancel()`. `revert`, if `true`, tells the caller to restore the state the query was in before the fetch\n * started instead of surfacing the error. `silent`, if `true`, tells the caller to suppress this error and instead\n * resolve with the promise of the fetch that triggered the cancellation.\n * @example\n * ```ts\n * query.cancel()\n *\n * try {\n * await query.promise\n * } catch (error) {\n * if (error instanceof CancelledError) {\n * // the fetch was cancelled, e.g. via `query.cancel()`\n * }\n * }\n * ```\n */\nexport class CancelledError extends Error {\n revert?: boolean\n silent?: boolean\n constructor(options?: CancelOptions) {\n super('CancelledError')\n this.revert = options?.revert\n this.silent = options?.silent\n }\n}\n\n/**\n * Checks whether a value is a `CancelledError`.\n * @param value - The value to check.\n * @returns `true` if `value` is a `CancelledError`.\n * @deprecated Use instanceof `CancelledError` instead.\n */\nexport function isCancelledError(value: any): value is CancelledError {\n return value instanceof CancelledError\n}\n\n/**\n * Creates a retryer, which runs a function and retries it on failure according to the `retry` and\n * `retryDelay` options. It pauses while the network mode doesn't allow fetching or `canRun` returns\n * `false`, and can be cancelled. Queries and mutations use it to run their `queryFn` and\n * `mutationFn`.\n * @param config - The function to run, the retry options, and the callbacks for failures, pausing,\n * continuing, and cancellation.\n * @returns The retryer, whose `promise` settles with the result of the function.\n */\nexport function createRetryer<TData = unknown, TError = DefaultError>(\n config: RetryerConfig<TData, TError>,\n): Retryer<TData> {\n let isRetryCancelled = false\n let failureCount = 0\n let continueFn: ((value?: unknown) => void) | undefined\n let status: RetryerStatus = 'pending'\n let promiseResolve: (data: TData) => void\n let promiseReject: (error: TError) => void\n\n const promise = new Promise<TData>((resolve, reject) => {\n promiseResolve = resolve\n promiseReject = reject\n })\n promise.catch(noop)\n\n const isResolved = () => status !== 'pending'\n\n const cancel = (cancelOptions?: CancelOptions): void => {\n if (!isResolved()) {\n const error = new CancelledError(cancelOptions) as TError\n reject(error)\n\n config.onCancel?.(error)\n }\n }\n const cancelRetry = () => {\n isRetryCancelled = true\n }\n\n const continueRetry = () => {\n isRetryCancelled = false\n }\n\n const canContinue = () =>\n focusManager.isFocused() &&\n (config.networkMode === 'always' || onlineManager.isOnline()) &&\n config.canRun()\n\n const canStart = () => canFetch(config.networkMode) && config.canRun()\n\n const resolve = (value: any) => {\n if (!isResolved()) {\n continueFn?.()\n status = 'resolved'\n promiseResolve(value)\n }\n }\n\n const reject = (value: any) => {\n if (!isResolved()) {\n continueFn?.()\n status = 'rejected'\n promiseReject(value)\n }\n }\n\n const pause = (canResume: () => boolean) => {\n return new Promise((continueResolve) => {\n continueFn = (value) => {\n if (isResolved() || canResume()) {\n continueResolve(value)\n }\n }\n config.onPause?.()\n }).then(() => {\n continueFn = undefined\n if (!isResolved()) {\n config.onContinue?.()\n }\n })\n }\n\n // Create loop function\n const run = () => {\n // Do nothing if already resolved\n if (isResolved()) {\n return\n }\n\n let promiseOrValue: any\n\n // we can re-use config.initialPromise on the first call of run()\n const initialPromise =\n failureCount === 0 ? config.initialPromise : undefined\n\n // Execute query\n try {\n promiseOrValue = initialPromise ?? config.fn()\n } catch (error) {\n promiseOrValue = Promise.reject(error)\n }\n\n Promise.resolve(promiseOrValue)\n .then(resolve)\n .catch((error) => {\n // Stop if the fetch is already resolved\n if (isResolved()) {\n return\n }\n\n // Do we need to retry the request?\n const retry = config.retry ?? (isServerEnvironment() ? 0 : 3)\n const retryDelay = config.retryDelay ?? defaultRetryDelay\n const delay =\n typeof retryDelay === 'function'\n ? retryDelay(failureCount, error)\n : retryDelay\n const shouldRetry =\n retry === true ||\n (typeof retry === 'number' && failureCount < retry) ||\n (typeof retry === 'function' && retry(failureCount, error))\n\n if (isRetryCancelled || !shouldRetry) {\n // We are done if the query does not need to be retried\n reject(error)\n return\n }\n\n failureCount++\n\n // Notify on fail\n config.onFail?.(failureCount, error)\n\n // Delay\n sleep(delay)\n // Pause if the document is not visible or when the device is offline\n .then(() => {\n return canContinue() ? undefined : pause(canContinue)\n })\n .then(() => {\n if (isRetryCancelled) {\n reject(error)\n } else {\n run()\n }\n })\n })\n }\n\n return {\n promise,\n status: () => status,\n cancel,\n continue: () => {\n continueFn?.()\n return promise\n },\n cancelRetry,\n continueRetry,\n canStart,\n start: () => {\n // Start loop\n if (canStart()) {\n run()\n } else {\n // Waiting to start (e.g. queued behind a scope) does not depend on focus,\n // only on the same conditions that allow starting in the first place\n pause(canStart).then(run)\n }\n return promise\n },\n }\n}\n"],"mappings":";;;;;;;;;;AAsFA,SAAS,kBAAkB,cAAsB;CAC/C,OAAO,KAAK,IAAI,MAAO,KAAK,cAAc,GAAK;AACjD;;;;;;AAOA,SAAgB,SAAS,aAA+C;CACtE,QAAQ,eAAe,cAAc,WACjC,cAAc,SAAS,IACvB;AACN;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,iBAAb,cAAoC,MAAM;CAGxC,YAAY,SAAyB;EACnC,MAAM,gBAAgB;EACtB,KAAK,SAAS,SAAS;EACvB,KAAK,SAAS,SAAS;CACzB;AACF;;;;;;;AAQA,SAAgB,iBAAiB,OAAqC;CACpE,OAAO,iBAAiB;AAC1B;;;;;;;;;;AAWA,SAAgB,cACd,QACgB;CAChB,IAAI,mBAAmB;CACvB,IAAI,eAAe;CACnB,IAAI;CACJ,IAAI,SAAwB;CAC5B,IAAI;CACJ,IAAI;CAEJ,MAAM,UAAU,IAAI,SAAgB,SAAS,WAAW;EACtD,iBAAiB;EACjB,gBAAgB;CAClB,CAAC;CACD,QAAQ,MAAM,IAAI;CAElB,MAAM,mBAAmB,WAAW;CAEpC,MAAM,UAAU,kBAAwC;EACtD,IAAI,CAAC,WAAW,GAAG;GACjB,MAAM,QAAQ,IAAI,eA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ACJ,UAAU,QACT,OAAO,UAAU,YAAY,eAAe,SAC5C,OAAO,UAAU,cAAc,MAAM,cAAc,KAAK;GAE3D,IAAI,oBAAoB,CAAC,aAAa;IAEpC,OAAO,KAAK;IACZ;GACF;GAEA;GAGA,OAAO,SAAS,cAAc,KAAK;GAGnC,MAAM,KAAK,CAAC,CAET,WAAW;IACV,OAAO,YAAY,IAAI,KAAA,IAAY,MAAM,WAAW;GACtD,CAAC,CAAC,CACD,WAAW;IACV,IAAI,kBACF,OAAO,KAAK;SAEZ,IAAI;GAER,CAAC;EACL,CAAC;CACL;CAEA,OAAO;EACL;EACA,cAAc;EACd;EACA,gBAAgB;GACd,aAAa;GACb,OAAO;EACT;EACA;EACA;EACA;EACA,aAAa;GAEX,IAAI,SAAS,GACX,IAAI;QAIJ,MAAM,QAAQ,CAAC,CAAC,KAAK,GAAG;GAE1B,OAAO;EACT;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"retryer.js","names":["isServerEnvironment"],"sources":["../../src/retryer.ts"],"sourcesContent":["import { focusManager } from './focusManager'\nimport { onlineManager } from './onlineManager'\nimport { isServer as isServerEnvironment } from './environmentManager'\nimport { noop, sleep } from './utils'\nimport type { CancelOptions, DefaultError, NetworkMode } from './types'\n\n// TYPES\n\ninterface RetryerConfig<TData = unknown, TError = DefaultError> {\n fn: () => TData | Promise<TData>\n initialPromise?: Promise<TData>\n onCancel?: (error: TError) => void\n onFail?: (failureCount: number, error: TError) => void\n onPause?: () => void\n onContinue?: () => void\n retry?: RetryValue<TError>\n retryDelay?: RetryDelayValue<TError>\n networkMode: NetworkMode | undefined\n canRun: () => boolean\n}\n\n/**\n * Runs a function with retries, and can pause, continue, or cancel it. Queries and mutations use\n * one for each fetch or execution.\n */\nexport interface Retryer<TData = unknown> {\n /**\n * The promise that resolves with the data, or rejects once retries are exhausted or it is\n * cancelled.\n */\n promise: Promise<TData>\n /**\n * Cancels the run, rejecting `promise` with a `CancelledError`.\n */\n cancel: (cancelOptions?: CancelOptions) => void\n /**\n * Resumes a paused run, and returns `promise`.\n */\n continue: () => Promise<unknown>\n /**\n * Stops further retries. The current attempt still finishes.\n */\n cancelRetry: () => void\n /**\n * Allows retries again after `cancelRetry`.\n */\n continueRetry: () => void\n /**\n * Returns whether the run can start now, based on the network mode and `canRun`.\n */\n canStart: () => boolean\n /**\n * Starts the run, or waits until it can start, and returns `promise`.\n */\n start: () => Promise<TData>\n /**\n * Returns whether `promise` is still pending, resolved, or rejected.\n */\n status: () => 'pending' | 'resolved' | 'rejected'\n}\n\ntype RetryerStatus = 'pending' | 'resolved' | 'rejected'\n\n/** @inline */\nexport type RetryValue<TError> = boolean | number | ShouldRetryFunction<TError>\n\n/** @inline */\ntype ShouldRetryFunction<TError = DefaultError> = (\n failureCount: number,\n error: TError,\n) => boolean\n\n/** @inline */\nexport type RetryDelayValue<TError> = number | RetryDelayFunction<TError>\n\n/** @inline */\ntype RetryDelayFunction<TError = DefaultError> = (\n failureCount: number,\n error: TError,\n) => number\n\n/**\n * The default `retryDelay`: doubles with every failure, starting at 1 second, up to 30 seconds.\n * @param failureCount - The number of failures so far.\n * @returns The delay before the next retry, in milliseconds.\n */\nfunction defaultRetryDelay(failureCount: number) {\n return Math.min(1000 * 2 ** failureCount, 30000)\n}\n\n/**\n * Checks whether a fetch can run for the given network mode.\n * @param networkMode - The `networkMode` option. Defaults to `'online'`.\n * @returns `true` if the network mode is not `'online'`, or if it is and the client is online.\n */\nexport function canFetch(networkMode: NetworkMode | undefined): boolean {\n return (networkMode ?? 'online') === 'online'\n ? onlineManager.isOnline()\n : true\n}\n\n/**\n * The error thrown by a `Retryer` (and surfaced to `query.promise`/`mutation`) when a fetch is cancelled, e.g. via\n * `query.cancel()`. `revert`, if `true`, tells the caller to restore the state the query was in before the fetch\n * started instead of surfacing the error. `silent`, if `true`, tells the caller to suppress this error and instead\n * resolve with the promise of the fetch that triggered the cancellation.\n * @example\n * ```ts\n * query.cancel()\n *\n * try {\n * await query.promise\n * } catch (error) {\n * if (error instanceof CancelledError) {\n * // the fetch was cancelled, e.g. via `query.cancel()`\n * }\n * }\n * ```\n */\nexport class CancelledError extends Error {\n revert?: boolean\n silent?: boolean\n constructor(options?: CancelOptions) {\n super('CancelledError')\n this.revert = options?.revert\n this.silent = options?.silent\n }\n}\n\n/**\n * Checks whether a value is a `CancelledError`.\n * @param value - The value to check.\n * @returns `true` if `value` is a `CancelledError`.\n * @deprecated Use instanceof `CancelledError` instead.\n */\nexport function isCancelledError(value: any): value is CancelledError {\n return value instanceof CancelledError\n}\n\n/**\n * Creates a retryer, which runs a function and retries it on failure according to the `retry` and\n * `retryDelay` options. It pauses while the network mode doesn't allow fetching or `canRun` returns\n * `false`, and can be cancelled. Queries and mutations use it to run their `queryFn` and\n * `mutationFn`.\n * @param config - The function to run, the retry options, and the callbacks for failures, pausing,\n * continuing, and cancellation.\n * @returns The retryer, whose `promise` settles with the result of the function.\n */\nexport function createRetryer<TData = unknown, TError = DefaultError>(\n config: RetryerConfig<TData, TError>,\n): Retryer<TData> {\n let isRetryCancelled = false\n let failureCount = 0\n let continueFn: ((value?: unknown) => void) | undefined\n let status: RetryerStatus = 'pending'\n let promiseResolve: (data: TData) => void\n let promiseReject: (error: TError) => void\n\n const promise = new Promise<TData>((resolve, reject) => {\n promiseResolve = resolve\n promiseReject = reject\n })\n promise.catch(noop)\n\n const isResolved = () => status !== 'pending'\n\n const cancel = (cancelOptions?: CancelOptions): void => {\n if (!isResolved()) {\n const error = new CancelledError(cancelOptions) as TError\n reject(error)\n\n config.onCancel?.(error)\n }\n }\n const cancelRetry = () => {\n isRetryCancelled = true\n }\n\n const continueRetry = () => {\n isRetryCancelled = false\n }\n\n const canContinue = () =>\n focusManager.isFocused() &&\n (config.networkMode === 'always' || onlineManager.isOnline()) &&\n config.canRun()\n\n const canStart = () => canFetch(config.networkMode) && config.canRun()\n\n const resolve = (value: any) => {\n if (!isResolved()) {\n continueFn?.()\n status = 'resolved'\n promiseResolve(value)\n }\n }\n\n const reject = (value: any) => {\n if (!isResolved()) {\n continueFn?.()\n status = 'rejected'\n promiseReject(value)\n }\n }\n\n const pause = (canResume: () => boolean) => {\n return new Promise((continueResolve) => {\n continueFn = (value) => {\n if (isResolved() || canResume()) {\n continueResolve(value)\n }\n }\n config.onPause?.()\n }).then(() => {\n continueFn = undefined\n if (!isResolved()) {\n config.onContinue?.()\n }\n })\n }\n\n // Create loop function\n const run = () => {\n // Do nothing if already resolved\n if (isResolved()) {\n return\n }\n\n let promiseOrValue: any\n\n // we can re-use config.initialPromise on the first call of run()\n const initialPromise =\n failureCount === 0 ? config.initialPromise : undefined\n\n // Execute query\n try {\n promiseOrValue = initialPromise ?? config.fn()\n } catch (error) {\n promiseOrValue = Promise.reject(error)\n }\n\n Promise.resolve(promiseOrValue)\n .then(resolve)\n .catch((error) => {\n // Stop if the fetch is already resolved\n if (isResolved()) {\n return\n }\n\n // Do we need to retry the request?\n const retry = config.retry ?? (isServerEnvironment() ? 0 : 3)\n const retryDelay = config.retryDelay ?? defaultRetryDelay\n const delay =\n typeof retryDelay === 'function'\n ? retryDelay(failureCount, error)\n : retryDelay\n const shouldRetry =\n retry === true ||\n (typeof retry === 'number' && failureCount < retry) ||\n (typeof retry === 'function' && retry(failureCount, error))\n\n if (isRetryCancelled || !shouldRetry) {\n // We are done if the query does not need to be retried\n reject(error)\n return\n }\n\n failureCount++\n\n // Notify on fail\n config.onFail?.(failureCount, error)\n\n // Delay\n sleep(delay)\n // Pause if the document is not visible or when the device is offline\n .then(() => {\n return isResolved() || canContinue()\n ? undefined\n : pause(canContinue)\n })\n .then(() => {\n if (isRetryCancelled) {\n reject(error)\n } else {\n run()\n }\n })\n })\n }\n\n return {\n promise,\n status: () => status,\n cancel,\n continue: () => {\n continueFn?.()\n return promise\n },\n cancelRetry,\n continueRetry,\n canStart,\n start: () => {\n // Start loop\n if (canStart()) {\n run()\n } else {\n // Waiting to start (e.g. queued behind a scope) does not depend on focus,\n // only on the same conditions that allow starting in the first place\n pause(canStart).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EACT;EACA;EACA;EACA;EACA,aAAa;GAEX,IAAI,SAAS,GACX,IAAI;QAIJ,MAAM,QAAQ,CAAC,CAAC,KAAK,GAAG;GAE1B,OAAO;EACT;CACF;AACF"}
|
|
@@ -6,6 +6,8 @@ const require_utils = require("./utils.cjs");
|
|
|
6
6
|
* Data will be an Array of all the chunks received.
|
|
7
7
|
* The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.
|
|
8
8
|
* The query will stay in fetchStatus 'fetching' until the stream ends.
|
|
9
|
+
* Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`.
|
|
10
|
+
* If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes.
|
|
9
11
|
* @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional
|
|
10
12
|
* `refetchMode`, `reducer`, and `initialValue` options.
|
|
11
13
|
* @returns A query function to pass as `queryFn`.
|
|
@@ -21,6 +23,8 @@ const require_utils = require("./utils.cjs");
|
|
|
21
23
|
*/
|
|
22
24
|
function streamedQuery({ streamFn, refetchMode = "reset", reducer = (items, chunk) => require_utils.addToEnd(items, chunk), initialValue = [] }) {
|
|
23
25
|
return async (context) => {
|
|
26
|
+
const signal = context[require_utils.fetchSignal];
|
|
27
|
+
if (signal?.aborted) return initialValue;
|
|
24
28
|
const query = context.client.getQueryCache().find({
|
|
25
29
|
queryKey: context.queryKey,
|
|
26
30
|
exact: true
|
|
@@ -32,20 +36,22 @@ function streamedQuery({ streamFn, refetchMode = "reset", reducer = (items, chun
|
|
|
32
36
|
});
|
|
33
37
|
let result = initialValue;
|
|
34
38
|
let cancelled = false;
|
|
35
|
-
const
|
|
39
|
+
const streamFnContext = require_utils.addConsumeAwareSignal({
|
|
36
40
|
client: context.client,
|
|
37
41
|
meta: context.meta,
|
|
38
42
|
queryKey: context.queryKey,
|
|
39
43
|
pageParam: context.pageParam,
|
|
40
44
|
direction: context.direction
|
|
41
|
-
}, () => context.signal, () => cancelled = true)
|
|
45
|
+
}, () => context.signal, () => cancelled = true, signal);
|
|
46
|
+
const isStreamInactive = () => cancelled || signal?.aborted === true;
|
|
47
|
+
const stream = await streamFn(streamFnContext);
|
|
42
48
|
const isReplaceRefetch = isRefetch && refetchMode === "replace";
|
|
43
49
|
for await (const chunk of stream) {
|
|
44
|
-
if (
|
|
50
|
+
if (isStreamInactive()) break;
|
|
45
51
|
if (isReplaceRefetch) result = reducer(result, chunk);
|
|
46
52
|
else context.client.setQueryData(context.queryKey, (prev) => reducer(prev === void 0 ? initialValue : prev, chunk));
|
|
47
53
|
}
|
|
48
|
-
if (isReplaceRefetch && !
|
|
54
|
+
if (isReplaceRefetch && !isStreamInactive()) context.client.setQueryData(context.queryKey, result);
|
|
49
55
|
const data = context.client.getQueryData(context.queryKey);
|
|
50
56
|
return data === void 0 ? initialValue : data;
|
|
51
57
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streamedQuery.cjs","names":["addToEnd","addConsumeAwareSignal"],"sources":["../../src/streamedQuery.ts"],"sourcesContent":["import { addConsumeAwareSignal, addToEnd } from './utils'\nimport type {\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n} from './types'\n\ntype BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {\n /** The function that returns an `AsyncIterable` to stream data from. */\n streamFn: (\n context: QueryFunctionContext<TQueryKey>,\n ) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>\n /**\n * Defines how refetches are handled.\n * - `'reset'` (default): erases all data and puts the query back into `pending` state.\n * - `'append'`: appends new data to the existing data.\n * - `'replace'`: writes all data to the cache once the stream ends.\n */\n refetchMode?: 'append' | 'reset' | 'replace'\n}\n\ntype SimpleStreamedQueryParams<\n TQueryFnData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n reducer?: never\n initialValue?: never\n}\n\ntype ReducibleStreamedQueryParams<\n TQueryFnData,\n TData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n /**\n * Reduces streamed chunks into the final data shape. Required whenever `TData` is not an\n * array, since there is no default way to accumulate non-array chunks.\n */\n reducer: (acc: TData, chunk: TQueryFnData) => TData\n /**\n * The value used while the first chunk is being fetched, and returned if the stream yields no\n * values. Required together with a custom `reducer`.\n */\n initialValue: TData\n}\n\ntype StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> =\n | SimpleStreamedQueryParams<TQueryFnData, TQueryKey>\n | ReducibleStreamedQueryParams<TQueryFnData, TData, TQueryKey>\n\n/**\n * This is a helper function to create a query function that streams data from an AsyncIterable.\n * Data will be an Array of all the chunks received.\n * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.\n * The query will stay in fetchStatus 'fetching' until the stream ends.\n * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional\n * `refetchMode`, `reducer`, and `initialValue` options.\n * @returns A query function to pass as `queryFn`.\n * @example\n * ```ts\n * await queryClient.query({\n * queryKey: ['data'],\n * queryFn: streamedQuery({\n * streamFn: fetchDataInChunks,\n * }),\n * })\n * ```\n */\nexport function streamedQuery<\n TQueryFnData = unknown,\n TData = Array<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n>({\n streamFn,\n refetchMode = 'reset',\n reducer = (items, chunk) =>\n addToEnd(items as Array<TQueryFnData>, chunk) as TData,\n initialValue = [] as TData,\n}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>): QueryFunction<\n TData,\n TQueryKey\n> {\n return async (context) => {\n const query = context.client\n .getQueryCache()\n .find({ queryKey: context.queryKey, exact: true })\n const isRefetch = !!query && query.isFetched()\n if (isRefetch && refetchMode === 'reset') {\n query.setState({\n ...query.resetState,\n fetchStatus: 'fetching',\n })\n }\n\n let result = initialValue\n\n let cancelled = false as boolean\n const streamFnContext = addConsumeAwareSignal<\n OmitKeyof<typeof context, 'signal'>\n >(\n {\n client: context.client,\n meta: context.meta,\n queryKey: context.queryKey,\n pageParam: context.pageParam,\n direction: context.direction,\n },\n () => context.signal,\n () => (cancelled = true),\n )\n\n const stream = await streamFn(streamFnContext)\n\n const isReplaceRefetch = isRefetch && refetchMode === 'replace'\n\n for await (const chunk of stream) {\n if (
|
|
1
|
+
{"version":3,"file":"streamedQuery.cjs","names":["addToEnd","signalContext","fetchSignal","addConsumeAwareSignal"],"sources":["../../src/streamedQuery.ts"],"sourcesContent":["import { addConsumeAwareSignal, addToEnd, fetchSignal } from './utils'\nimport type { FetchSignalContext } from './utils'\nimport type {\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n} from './types'\n\ntype BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {\n /** The function that returns an `AsyncIterable` to stream data from. */\n streamFn: (\n context: QueryFunctionContext<TQueryKey>,\n ) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>\n /**\n * Defines how refetches are handled.\n * - `'reset'` (default): erases all data and puts the query back into `pending` state.\n * - `'append'`: appends new data to the existing data.\n * - `'replace'`: writes all data to the cache once the stream ends.\n */\n refetchMode?: 'append' | 'reset' | 'replace'\n}\n\ntype SimpleStreamedQueryParams<\n TQueryFnData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n reducer?: never\n initialValue?: never\n}\n\ntype ReducibleStreamedQueryParams<\n TQueryFnData,\n TData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n /**\n * Reduces streamed chunks into the final data shape. Required whenever `TData` is not an\n * array, since there is no default way to accumulate non-array chunks.\n */\n reducer: (acc: TData, chunk: TQueryFnData) => TData\n /**\n * The value used while the first chunk is being fetched, and returned if the stream yields no\n * values. Required together with a custom `reducer`.\n */\n initialValue: TData\n}\n\ntype StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> =\n | SimpleStreamedQueryParams<TQueryFnData, TQueryKey>\n | ReducibleStreamedQueryParams<TQueryFnData, TData, TQueryKey>\n\n/**\n * This is a helper function to create a query function that streams data from an AsyncIterable.\n * Data will be an Array of all the chunks received.\n * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.\n * The query will stay in fetchStatus 'fetching' until the stream ends.\n * Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`.\n * If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes.\n * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional\n * `refetchMode`, `reducer`, and `initialValue` options.\n * @returns A query function to pass as `queryFn`.\n * @example\n * ```ts\n * await queryClient.query({\n * queryKey: ['data'],\n * queryFn: streamedQuery({\n * streamFn: fetchDataInChunks,\n * }),\n * })\n * ```\n */\nexport function streamedQuery<\n TQueryFnData = unknown,\n TData = Array<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n>({\n streamFn,\n refetchMode = 'reset',\n reducer = (items, chunk) =>\n addToEnd(items as Array<TQueryFnData>, chunk) as TData,\n initialValue = [] as TData,\n}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>): QueryFunction<\n TData,\n TQueryKey\n> {\n return async (context) => {\n const signalContext: FetchSignalContext = context\n const signal = signalContext[fetchSignal]\n if (signal?.aborted) {\n return initialValue\n }\n\n const query = context.client\n .getQueryCache()\n .find({ queryKey: context.queryKey, exact: true })\n const isRefetch = !!query && query.isFetched()\n if (isRefetch && refetchMode === 'reset') {\n query.setState({\n ...query.resetState,\n fetchStatus: 'fetching',\n })\n }\n\n let result = initialValue\n\n let cancelled = false as boolean\n const streamFnContext = addConsumeAwareSignal<\n OmitKeyof<typeof context, 'signal'>\n >(\n {\n client: context.client,\n meta: context.meta,\n queryKey: context.queryKey,\n pageParam: context.pageParam,\n direction: context.direction,\n },\n () => context.signal,\n () => (cancelled = true),\n signal,\n )\n\n const isStreamInactive = () => cancelled || signal?.aborted === true\n const stream = await streamFn(streamFnContext)\n\n const isReplaceRefetch = isRefetch && refetchMode === 'replace'\n\n for await (const chunk of stream) {\n if (isStreamInactive()) {\n break\n }\n\n if (isReplaceRefetch) {\n // don't append to the cache directly when replace-refetching\n result = reducer(result, chunk)\n } else {\n context.client.setQueryData<TData>(context.queryKey, (prev) =>\n reducer(prev === undefined ? initialValue : prev, chunk),\n )\n }\n }\n\n // finalize result: replace-refetching needs to write to the cache\n if (isReplaceRefetch && !isStreamInactive()) {\n context.client.setQueryData<TData>(context.queryKey, result)\n }\n\n const data = context.client.getQueryData<TData>(context.queryKey)\n return data === undefined ? initialValue : data\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwEA,SAAgB,cAId,EACA,UACA,cAAc,SACd,WAAW,OAAO,UAChBA,cAAAA,SAAS,OAA8B,KAAK,GAC9C,eAAe,CAAC,KAIhB;CACA,OAAO,OAAO,YAAY;EAExB,MAAM,SAASC,QAAcC,cAAAA;EAC7B,IAAI,QAAQ,SACV,OAAO;EAGT,MAAM,QAAQ,QAAQ,OACnB,cAAc,CAAC,CACf,KAAK;GAAE,UAAU,QAAQ;GAAU,OAAO;EAAK,CAAC;EACnD,MAAM,YAAY,CAAC,CAAC,SAAS,MAAM,UAAU;EAC7C,IAAI,aAAa,gBAAgB,SAC/B,MAAM,SAAS;GACb,GAAG,MAAM;GACT,aAAa;EACf,CAAC;EAGH,IAAI,SAAS;EAEb,IAAI,YAAY;EAChB,MAAM,kBAAkBC,cAAAA,sBAGtB;GACE,QAAQ,QAAQ;GAChB,MAAM,QAAQ;GACd,UAAU,QAAQ;GAClB,WAAW,QAAQ;GACnB,WAAW,QAAQ;EACrB,SACM,QAAQ,cACP,YAAY,MACnB,MACF;EAEA,MAAM,yBAAyB,aAAa,QAAQ,YAAY;EAChE,MAAM,SAAS,MAAM,SAAS,eAAe;EAE7C,MAAM,mBAAmB,aAAa,gBAAgB;EAEtD,WAAW,MAAM,SAAS,QAAQ;GAChC,IAAI,iBAAiB,GACnB;GAGF,IAAI,kBAEF,SAAS,QAAQ,QAAQ,KAAK;QAE9B,QAAQ,OAAO,aAAoB,QAAQ,WAAW,SACpD,QAAQ,SAAS,KAAA,IAAY,eAAe,MAAM,KAAK,CACzD;EAEJ;EAGA,IAAI,oBAAoB,CAAC,iBAAiB,GACxC,QAAQ,OAAO,aAAoB,QAAQ,UAAU,MAAM;EAG7D,MAAM,OAAO,QAAQ,OAAO,aAAoB,QAAQ,QAAQ;EAChE,OAAO,SAAS,KAAA,IAAY,eAAe;CAC7C;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Ct as QueryKey, St as QueryFunctionContext, xt as QueryFunction } from "./hydration-
|
|
1
|
+
import { Ct as QueryKey, St as QueryFunctionContext, xt as QueryFunction } from "./hydration-BIRJt69T.cjs";
|
|
2
2
|
type BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {
|
|
3
3
|
/** The function that returns an `AsyncIterable` to stream data from. */
|
|
4
4
|
streamFn: (context: QueryFunctionContext<TQueryKey>) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>;
|
|
@@ -32,6 +32,8 @@ type StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> = Simp
|
|
|
32
32
|
* Data will be an Array of all the chunks received.
|
|
33
33
|
* The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.
|
|
34
34
|
* The query will stay in fetchStatus 'fetching' until the stream ends.
|
|
35
|
+
* Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`.
|
|
36
|
+
* If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes.
|
|
35
37
|
* @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional
|
|
36
38
|
* `refetchMode`, `reducer`, and `initialValue` options.
|
|
37
39
|
* @returns A query function to pass as `queryFn`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streamedQuery.d.cts","names":[],"sources":["../../src/streamedQuery.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"streamedQuery.d.cts","names":[],"sources":["../../src/streamedQuery.ts"],"mappings":";KASK,wBAAwB,cAAc,kBAAkB;;EAE3D,WACE,SAAS,qBAAqB,eAC3B,cAAc,gBAAgB,QAAQ,cAAc;;;;;;;EAOzD;;KAGG,0BACH,cACA,kBAAkB,YAChB,wBAAwB,cAAc;EACxC;EACA;;KAGG,6BACH,cACA,OACA,kBAAkB,YAChB,wBAAwB,cAAc;;;;;EAKxC,UAAU,KAAK,OAAO,OAAO,iBAAiB;;;;;EAK9C,cAAc;;KAGX,oBAAoB,cAAc,OAAO,kBAAkB,YAC5D,0BAA0B,cAAc,aACxC,6BAA6B,cAAc,OAAO;;;;;;;;;;;;;;;;;;;;;wBAsBtC,cACd,wBACA,QAAQ,MAAM,eACd,kBAAkB,WAAW,YAE7B,UACA,aACA,SAEA,gBACC,oBAAoB,cAAc,OAAO,aAAa,cACvD,OACA"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Ct as QueryKey, St as QueryFunctionContext, xt as QueryFunction } from "./hydration-
|
|
1
|
+
import { Ct as QueryKey, St as QueryFunctionContext, xt as QueryFunction } from "./hydration-9_kOYxJM.js";
|
|
2
2
|
type BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {
|
|
3
3
|
/** The function that returns an `AsyncIterable` to stream data from. */
|
|
4
4
|
streamFn: (context: QueryFunctionContext<TQueryKey>) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>;
|
|
@@ -32,6 +32,8 @@ type StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> = Simp
|
|
|
32
32
|
* Data will be an Array of all the chunks received.
|
|
33
33
|
* The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.
|
|
34
34
|
* The query will stay in fetchStatus 'fetching' until the stream ends.
|
|
35
|
+
* Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`.
|
|
36
|
+
* If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes.
|
|
35
37
|
* @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional
|
|
36
38
|
* `refetchMode`, `reducer`, and `initialValue` options.
|
|
37
39
|
* @returns A query function to pass as `queryFn`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streamedQuery.d.ts","names":[],"sources":["../../src/streamedQuery.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"streamedQuery.d.ts","names":[],"sources":["../../src/streamedQuery.ts"],"mappings":";KASK,wBAAwB,cAAc,kBAAkB;;EAE3D,WACE,SAAS,qBAAqB,eAC3B,cAAc,gBAAgB,QAAQ,cAAc;;;;;;;EAOzD;;KAGG,0BACH,cACA,kBAAkB,YAChB,wBAAwB,cAAc;EACxC;EACA;;KAGG,6BACH,cACA,OACA,kBAAkB,YAChB,wBAAwB,cAAc;;;;;EAKxC,UAAU,KAAK,OAAO,OAAO,iBAAiB;;;;;EAK9C,cAAc;;KAGX,oBAAoB,cAAc,OAAO,kBAAkB,YAC5D,0BAA0B,cAAc,aACxC,6BAA6B,cAAc,OAAO;;;;;;;;;;;;;;;;;;;;;wBAsBtC,cACd,wBACA,QAAQ,MAAM,eACd,kBAAkB,WAAW,YAE7B,UACA,aACA,SAEA,gBACC,oBAAoB,cAAc,OAAO,aAAa,cACvD,OACA"}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import { addConsumeAwareSignal, addToEnd } from "./utils.js";
|
|
1
|
+
import { addConsumeAwareSignal, addToEnd, fetchSignal } from "./utils.js";
|
|
2
2
|
// src/streamedQuery.ts
|
|
3
3
|
/**
|
|
4
4
|
* This is a helper function to create a query function that streams data from an AsyncIterable.
|
|
5
5
|
* Data will be an Array of all the chunks received.
|
|
6
6
|
* The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.
|
|
7
7
|
* The query will stay in fetchStatus 'fetching' until the stream ends.
|
|
8
|
+
* Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`.
|
|
9
|
+
* If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes.
|
|
8
10
|
* @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional
|
|
9
11
|
* `refetchMode`, `reducer`, and `initialValue` options.
|
|
10
12
|
* @returns A query function to pass as `queryFn`.
|
|
@@ -20,6 +22,8 @@ import { addConsumeAwareSignal, addToEnd } from "./utils.js";
|
|
|
20
22
|
*/
|
|
21
23
|
function streamedQuery({ streamFn, refetchMode = "reset", reducer = (items, chunk) => addToEnd(items, chunk), initialValue = [] }) {
|
|
22
24
|
return async (context) => {
|
|
25
|
+
const signal = context[fetchSignal];
|
|
26
|
+
if (signal?.aborted) return initialValue;
|
|
23
27
|
const query = context.client.getQueryCache().find({
|
|
24
28
|
queryKey: context.queryKey,
|
|
25
29
|
exact: true
|
|
@@ -31,20 +35,22 @@ function streamedQuery({ streamFn, refetchMode = "reset", reducer = (items, chun
|
|
|
31
35
|
});
|
|
32
36
|
let result = initialValue;
|
|
33
37
|
let cancelled = false;
|
|
34
|
-
const
|
|
38
|
+
const streamFnContext = addConsumeAwareSignal({
|
|
35
39
|
client: context.client,
|
|
36
40
|
meta: context.meta,
|
|
37
41
|
queryKey: context.queryKey,
|
|
38
42
|
pageParam: context.pageParam,
|
|
39
43
|
direction: context.direction
|
|
40
|
-
}, () => context.signal, () => cancelled = true)
|
|
44
|
+
}, () => context.signal, () => cancelled = true, signal);
|
|
45
|
+
const isStreamInactive = () => cancelled || signal?.aborted === true;
|
|
46
|
+
const stream = await streamFn(streamFnContext);
|
|
41
47
|
const isReplaceRefetch = isRefetch && refetchMode === "replace";
|
|
42
48
|
for await (const chunk of stream) {
|
|
43
|
-
if (
|
|
49
|
+
if (isStreamInactive()) break;
|
|
44
50
|
if (isReplaceRefetch) result = reducer(result, chunk);
|
|
45
51
|
else context.client.setQueryData(context.queryKey, (prev) => reducer(prev === void 0 ? initialValue : prev, chunk));
|
|
46
52
|
}
|
|
47
|
-
if (isReplaceRefetch && !
|
|
53
|
+
if (isReplaceRefetch && !isStreamInactive()) context.client.setQueryData(context.queryKey, result);
|
|
48
54
|
const data = context.client.getQueryData(context.queryKey);
|
|
49
55
|
return data === void 0 ? initialValue : data;
|
|
50
56
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streamedQuery.js","names":[],"sources":["../../src/streamedQuery.ts"],"sourcesContent":["import { addConsumeAwareSignal, addToEnd } from './utils'\nimport type {\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n} from './types'\n\ntype BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {\n /** The function that returns an `AsyncIterable` to stream data from. */\n streamFn: (\n context: QueryFunctionContext<TQueryKey>,\n ) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>\n /**\n * Defines how refetches are handled.\n * - `'reset'` (default): erases all data and puts the query back into `pending` state.\n * - `'append'`: appends new data to the existing data.\n * - `'replace'`: writes all data to the cache once the stream ends.\n */\n refetchMode?: 'append' | 'reset' | 'replace'\n}\n\ntype SimpleStreamedQueryParams<\n TQueryFnData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n reducer?: never\n initialValue?: never\n}\n\ntype ReducibleStreamedQueryParams<\n TQueryFnData,\n TData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n /**\n * Reduces streamed chunks into the final data shape. Required whenever `TData` is not an\n * array, since there is no default way to accumulate non-array chunks.\n */\n reducer: (acc: TData, chunk: TQueryFnData) => TData\n /**\n * The value used while the first chunk is being fetched, and returned if the stream yields no\n * values. Required together with a custom `reducer`.\n */\n initialValue: TData\n}\n\ntype StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> =\n | SimpleStreamedQueryParams<TQueryFnData, TQueryKey>\n | ReducibleStreamedQueryParams<TQueryFnData, TData, TQueryKey>\n\n/**\n * This is a helper function to create a query function that streams data from an AsyncIterable.\n * Data will be an Array of all the chunks received.\n * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.\n * The query will stay in fetchStatus 'fetching' until the stream ends.\n * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional\n * `refetchMode`, `reducer`, and `initialValue` options.\n * @returns A query function to pass as `queryFn`.\n * @example\n * ```ts\n * await queryClient.query({\n * queryKey: ['data'],\n * queryFn: streamedQuery({\n * streamFn: fetchDataInChunks,\n * }),\n * })\n * ```\n */\nexport function streamedQuery<\n TQueryFnData = unknown,\n TData = Array<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n>({\n streamFn,\n refetchMode = 'reset',\n reducer = (items, chunk) =>\n addToEnd(items as Array<TQueryFnData>, chunk) as TData,\n initialValue = [] as TData,\n}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>): QueryFunction<\n TData,\n TQueryKey\n> {\n return async (context) => {\n const query = context.client\n .getQueryCache()\n .find({ queryKey: context.queryKey, exact: true })\n const isRefetch = !!query && query.isFetched()\n if (isRefetch && refetchMode === 'reset') {\n query.setState({\n ...query.resetState,\n fetchStatus: 'fetching',\n })\n }\n\n let result = initialValue\n\n let cancelled = false as boolean\n const streamFnContext = addConsumeAwareSignal<\n OmitKeyof<typeof context, 'signal'>\n >(\n {\n client: context.client,\n meta: context.meta,\n queryKey: context.queryKey,\n pageParam: context.pageParam,\n direction: context.direction,\n },\n () => context.signal,\n () => (cancelled = true),\n )\n\n const stream = await streamFn(streamFnContext)\n\n const isReplaceRefetch = isRefetch && refetchMode === 'replace'\n\n for await (const chunk of stream) {\n if (
|
|
1
|
+
{"version":3,"file":"streamedQuery.js","names":["signalContext"],"sources":["../../src/streamedQuery.ts"],"sourcesContent":["import { addConsumeAwareSignal, addToEnd, fetchSignal } from './utils'\nimport type { FetchSignalContext } from './utils'\nimport type {\n OmitKeyof,\n QueryFunction,\n QueryFunctionContext,\n QueryKey,\n} from './types'\n\ntype BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {\n /** The function that returns an `AsyncIterable` to stream data from. */\n streamFn: (\n context: QueryFunctionContext<TQueryKey>,\n ) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>\n /**\n * Defines how refetches are handled.\n * - `'reset'` (default): erases all data and puts the query back into `pending` state.\n * - `'append'`: appends new data to the existing data.\n * - `'replace'`: writes all data to the cache once the stream ends.\n */\n refetchMode?: 'append' | 'reset' | 'replace'\n}\n\ntype SimpleStreamedQueryParams<\n TQueryFnData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n reducer?: never\n initialValue?: never\n}\n\ntype ReducibleStreamedQueryParams<\n TQueryFnData,\n TData,\n TQueryKey extends QueryKey,\n> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {\n /**\n * Reduces streamed chunks into the final data shape. Required whenever `TData` is not an\n * array, since there is no default way to accumulate non-array chunks.\n */\n reducer: (acc: TData, chunk: TQueryFnData) => TData\n /**\n * The value used while the first chunk is being fetched, and returned if the stream yields no\n * values. Required together with a custom `reducer`.\n */\n initialValue: TData\n}\n\ntype StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> =\n | SimpleStreamedQueryParams<TQueryFnData, TQueryKey>\n | ReducibleStreamedQueryParams<TQueryFnData, TData, TQueryKey>\n\n/**\n * This is a helper function to create a query function that streams data from an AsyncIterable.\n * Data will be an Array of all the chunks received.\n * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.\n * The query will stay in fetchStatus 'fetching' until the stream ends.\n * Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`.\n * If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes.\n * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional\n * `refetchMode`, `reducer`, and `initialValue` options.\n * @returns A query function to pass as `queryFn`.\n * @example\n * ```ts\n * await queryClient.query({\n * queryKey: ['data'],\n * queryFn: streamedQuery({\n * streamFn: fetchDataInChunks,\n * }),\n * })\n * ```\n */\nexport function streamedQuery<\n TQueryFnData = unknown,\n TData = Array<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n>({\n streamFn,\n refetchMode = 'reset',\n reducer = (items, chunk) =>\n addToEnd(items as Array<TQueryFnData>, chunk) as TData,\n initialValue = [] as TData,\n}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>): QueryFunction<\n TData,\n TQueryKey\n> {\n return async (context) => {\n const signalContext: FetchSignalContext = context\n const signal = signalContext[fetchSignal]\n if (signal?.aborted) {\n return initialValue\n }\n\n const query = context.client\n .getQueryCache()\n .find({ queryKey: context.queryKey, exact: true })\n const isRefetch = !!query && query.isFetched()\n if (isRefetch && refetchMode === 'reset') {\n query.setState({\n ...query.resetState,\n fetchStatus: 'fetching',\n })\n }\n\n let result = initialValue\n\n let cancelled = false as boolean\n const streamFnContext = addConsumeAwareSignal<\n OmitKeyof<typeof context, 'signal'>\n >(\n {\n client: context.client,\n meta: context.meta,\n queryKey: context.queryKey,\n pageParam: context.pageParam,\n direction: context.direction,\n },\n () => context.signal,\n () => (cancelled = true),\n signal,\n )\n\n const isStreamInactive = () => cancelled || signal?.aborted === true\n const stream = await streamFn(streamFnContext)\n\n const isReplaceRefetch = isRefetch && refetchMode === 'replace'\n\n for await (const chunk of stream) {\n if (isStreamInactive()) {\n break\n }\n\n if (isReplaceRefetch) {\n // don't append to the cache directly when replace-refetching\n result = reducer(result, chunk)\n } else {\n context.client.setQueryData<TData>(context.queryKey, (prev) =>\n reducer(prev === undefined ? initialValue : prev, chunk),\n )\n }\n }\n\n // finalize result: replace-refetching needs to write to the cache\n if (isReplaceRefetch && !isStreamInactive()) {\n context.client.setQueryData<TData>(context.queryKey, result)\n }\n\n const data = context.client.getQueryData<TData>(context.queryKey)\n return data === undefined ? initialValue : data\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwEA,SAAgB,cAId,EACA,UACA,cAAc,SACd,WAAW,OAAO,UAChB,SAAS,OAA8B,KAAK,GAC9C,eAAe,CAAC,KAIhB;CACA,OAAO,OAAO,YAAY;EAExB,MAAM,SAASA,QAAc;EAC7B,IAAI,QAAQ,SACV,OAAO;EAGT,MAAM,QAAQ,QAAQ,OACnB,cAAc,CAAC,CACf,KAAK;GAAE,UAAU,QAAQ;GAAU,OAAO;EAAK,CAAC;EACnD,MAAM,YAAY,CAAC,CAAC,SAAS,MAAM,UAAU;EAC7C,IAAI,aAAa,gBAAgB,SAC/B,MAAM,SAAS;GACb,GAAG,MAAM;GACT,aAAa;EACf,CAAC;EAGH,IAAI,SAAS;EAEb,IAAI,YAAY;EAChB,MAAM,kBAAkB,sBAGtB;GACE,QAAQ,QAAQ;GAChB,MAAM,QAAQ;GACd,UAAU,QAAQ;GAClB,WAAW,QAAQ;GACnB,WAAW,QAAQ;EACrB,SACM,QAAQ,cACP,YAAY,MACnB,MACF;EAEA,MAAM,yBAAyB,aAAa,QAAQ,YAAY;EAChE,MAAM,SAAS,MAAM,SAAS,eAAe;EAE7C,MAAM,mBAAmB,aAAa,gBAAgB;EAEtD,WAAW,MAAM,SAAS,QAAQ;GAChC,IAAI,iBAAiB,GACnB;GAGF,IAAI,kBAEF,SAAS,QAAQ,QAAQ,KAAK;QAE9B,QAAQ,OAAO,aAAoB,QAAQ,WAAW,SACpD,QAAQ,SAAS,KAAA,IAAY,eAAe,MAAM,KAAK,CACzD;EAEJ;EAGA,IAAI,oBAAoB,CAAC,iBAAiB,GACxC,QAAQ,OAAO,aAAoB,QAAQ,UAAU,MAAM;EAG7D,MAAM,OAAO,QAAQ,OAAO,aAAoB,QAAQ,QAAQ;EAChE,OAAO,SAAS,KAAA,IAAY,eAAe;CAC7C;AACF"}
|
package/build/modern/types.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as MutationObserverBaseResult, A as InfiniteData, At as QueryObserverOptions, B as InfiniteQueryObserverSuccessResult, Bt as RefetchQueryFilters, C as FetchPreviousPageOptions, Ct as QueryKey, D as GetPreviousPageParamFunction, Dt as QueryObserverBaseResult, E as GetNextPageParamFunction, Et as QueryMeta, F as InfiniteQueryObserverOptions, Ft as QueryObserverSuccessResult, G as InvalidateQueryFilters, Gt as StaleTime, H as InitialDataFunction, Ht as ResetOptions, I as InfiniteQueryObserverPendingResult, It as QueryOptions, J as MutateOptions, Jt as UnsetMarker, K as MutateFunction, Kt as StaleTimeFunction, L as InfiniteQueryObserverPlaceholderResult, Lt as QueryPersister, M as InfiniteQueryObserverBaseResult, Mt as QueryObserverPlaceholderResult, N as InfiniteQueryObserverLoadingErrorResult, Nt as QueryObserverRefetchErrorResult, O as InferDataFromTag, Ot as QueryObserverLoadingErrorResult, P as InfiniteQueryObserverLoadingResult, Pt as QueryObserverResult, Q as MutationMeta, Qt as unsetMarker, R as InfiniteQueryObserverRefetchErrorResult, Rt as QueryStatus, S as FetchNextPageOptions, St as QueryFunctionContext, T as FetchStatus, Tt as QueryKeyWithDataTag, U as InitialPageParam, Ut as ResultOptions, V as InfiniteQueryPageParamsOptions, Vt as Register, W as InvalidateOptions, Wt as SetDataOptions, X as MutationFunctionContext, Xt as dataTagErrorSymbol, Y as MutationFunction, Yt as WithRequired, Z as MutationKey, Zt as dataTagSymbol, _ as DefinedQueryObserverResult, _t as QueriesPlaceholderDataFunction, at as MutationObserverSuccessResult, b as EnsureQueryDataOptions, bt as QueryExecuteOptions, ct as MutationStatus, d as DataTag, dt as NotifyEvent, et as MutationObserverErrorResult, f as DefaultError, ft as NotifyEventType, g as DefinedInfiniteQueryObserverResult, gt as PlaceholderDataFunction, h as DefaultedQueryObserverOptions, ht as Override, it as MutationObserverResult, j as InfiniteQueryExecuteOptions, jt as QueryObserverPendingResult, k as InferErrorFromTag, kt as QueryObserverLoadingResult, l as AnyDataTag, lt as NetworkMode, m as DefaultedInfiniteQueryObserverOptions, mt as OmitKeyof, nt as MutationObserverLoadingResult, ot as MutationOptions, p as DefaultOptions, pt as NotifyOnChangeProps, q as MutateFunctionRest, qt as ThrowOnError, rt as MutationObserverOptions, st as MutationScope, tt as MutationObserverIdleResult, u as CancelOptions, ut as NonUndefinedGuard, v as DistributiveOmit, vt as QueryBooleanOption, w as FetchQueryOptions, wt as QueryKeyHashFunction, x as FetchInfiniteQueryOptions, xt as QueryFunction, y as EnsureInfiniteQueryDataOptions, yt as QueryClientConfig, z as InfiniteQueryObserverResult, zt as RefetchOptions } from "./hydration-
|
|
1
|
+
import { $ as MutationObserverBaseResult, A as InfiniteData, At as QueryObserverOptions, B as InfiniteQueryObserverSuccessResult, Bt as RefetchQueryFilters, C as FetchPreviousPageOptions, Ct as QueryKey, D as GetPreviousPageParamFunction, Dt as QueryObserverBaseResult, E as GetNextPageParamFunction, Et as QueryMeta, F as InfiniteQueryObserverOptions, Ft as QueryObserverSuccessResult, G as InvalidateQueryFilters, Gt as StaleTime, H as InitialDataFunction, Ht as ResetOptions, I as InfiniteQueryObserverPendingResult, It as QueryOptions, J as MutateOptions, Jt as UnsetMarker, K as MutateFunction, Kt as StaleTimeFunction, L as InfiniteQueryObserverPlaceholderResult, Lt as QueryPersister, M as InfiniteQueryObserverBaseResult, Mt as QueryObserverPlaceholderResult, N as InfiniteQueryObserverLoadingErrorResult, Nt as QueryObserverRefetchErrorResult, O as InferDataFromTag, Ot as QueryObserverLoadingErrorResult, P as InfiniteQueryObserverLoadingResult, Pt as QueryObserverResult, Q as MutationMeta, Qt as unsetMarker, R as InfiniteQueryObserverRefetchErrorResult, Rt as QueryStatus, S as FetchNextPageOptions, St as QueryFunctionContext, T as FetchStatus, Tt as QueryKeyWithDataTag, U as InitialPageParam, Ut as ResultOptions, V as InfiniteQueryPageParamsOptions, Vt as Register, W as InvalidateOptions, Wt as SetDataOptions, X as MutationFunctionContext, Xt as dataTagErrorSymbol, Y as MutationFunction, Yt as WithRequired, Z as MutationKey, Zt as dataTagSymbol, _ as DefinedQueryObserverResult, _t as QueriesPlaceholderDataFunction, at as MutationObserverSuccessResult, b as EnsureQueryDataOptions, bt as QueryExecuteOptions, ct as MutationStatus, d as DataTag, dt as NotifyEvent, et as MutationObserverErrorResult, f as DefaultError, ft as NotifyEventType, g as DefinedInfiniteQueryObserverResult, gt as PlaceholderDataFunction, h as DefaultedQueryObserverOptions, ht as Override, it as MutationObserverResult, j as InfiniteQueryExecuteOptions, jt as QueryObserverPendingResult, k as InferErrorFromTag, kt as QueryObserverLoadingResult, l as AnyDataTag, lt as NetworkMode, m as DefaultedInfiniteQueryObserverOptions, mt as OmitKeyof, nt as MutationObserverLoadingResult, ot as MutationOptions, p as DefaultOptions, pt as NotifyOnChangeProps, q as MutateFunctionRest, qt as ThrowOnError, rt as MutationObserverOptions, st as MutationScope, tt as MutationObserverIdleResult, u as CancelOptions, ut as NonUndefinedGuard, v as DistributiveOmit, vt as QueryBooleanOption, w as FetchQueryOptions, wt as QueryKeyHashFunction, x as FetchInfiniteQueryOptions, xt as QueryFunction, y as EnsureInfiniteQueryDataOptions, yt as QueryClientConfig, z as InfiniteQueryObserverResult, zt as RefetchOptions } from "./hydration-BIRJt69T.cjs";
|
|
2
2
|
export { AnyDataTag, CancelOptions, DataTag, DefaultError, DefaultOptions, DefaultedInfiniteQueryObserverOptions, DefaultedQueryObserverOptions, DefinedInfiniteQueryObserverResult, DefinedQueryObserverResult, DistributiveOmit, EnsureInfiniteQueryDataOptions, EnsureQueryDataOptions, FetchInfiniteQueryOptions, FetchNextPageOptions, FetchPreviousPageOptions, FetchQueryOptions, FetchStatus, GetNextPageParamFunction, GetPreviousPageParamFunction, InferDataFromTag, InferErrorFromTag, InfiniteData, InfiniteQueryExecuteOptions, InfiniteQueryObserverBaseResult, InfiniteQueryObserverLoadingErrorResult, InfiniteQueryObserverLoadingResult, InfiniteQueryObserverOptions, InfiniteQueryObserverPendingResult, InfiniteQueryObserverPlaceholderResult, InfiniteQueryObserverRefetchErrorResult, InfiniteQueryObserverResult, InfiniteQueryObserverSuccessResult, InfiniteQueryPageParamsOptions, InitialDataFunction, InitialPageParam, InvalidateOptions, InvalidateQueryFilters, MutateFunction, MutateFunctionRest, MutateOptions, MutationFunction, MutationFunctionContext, MutationKey, MutationMeta, MutationObserverBaseResult, MutationObserverErrorResult, MutationObserverIdleResult, MutationObserverLoadingResult, MutationObserverOptions, MutationObserverResult, MutationObserverSuccessResult, MutationOptions, MutationScope, MutationStatus, NetworkMode, NonUndefinedGuard, NotifyEvent, NotifyEventType, NotifyOnChangeProps, OmitKeyof, Override, PlaceholderDataFunction, QueriesPlaceholderDataFunction, QueryBooleanOption, QueryClientConfig, QueryExecuteOptions, QueryFunction, QueryFunctionContext, QueryKey, QueryKeyHashFunction, QueryKeyWithDataTag, QueryMeta, QueryObserverBaseResult, QueryObserverLoadingErrorResult, QueryObserverLoadingResult, QueryObserverOptions, QueryObserverPendingResult, QueryObserverPlaceholderResult, QueryObserverRefetchErrorResult, QueryObserverResult, QueryObserverSuccessResult, QueryOptions, QueryPersister, QueryStatus, RefetchOptions, RefetchQueryFilters, Register, ResetOptions, ResultOptions, SetDataOptions, StaleTime, StaleTimeFunction, ThrowOnError, UnsetMarker, WithRequired, dataTagErrorSymbol, dataTagSymbol, unsetMarker };
|
package/build/modern/types.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as MutationObserverBaseResult, A as InfiniteData, At as QueryObserverOptions, B as InfiniteQueryObserverSuccessResult, Bt as RefetchQueryFilters, C as FetchPreviousPageOptions, Ct as QueryKey, D as GetPreviousPageParamFunction, Dt as QueryObserverBaseResult, E as GetNextPageParamFunction, Et as QueryMeta, F as InfiniteQueryObserverOptions, Ft as QueryObserverSuccessResult, G as InvalidateQueryFilters, Gt as StaleTime, H as InitialDataFunction, Ht as ResetOptions, I as InfiniteQueryObserverPendingResult, It as QueryOptions, J as MutateOptions, Jt as UnsetMarker, K as MutateFunction, Kt as StaleTimeFunction, L as InfiniteQueryObserverPlaceholderResult, Lt as QueryPersister, M as InfiniteQueryObserverBaseResult, Mt as QueryObserverPlaceholderResult, N as InfiniteQueryObserverLoadingErrorResult, Nt as QueryObserverRefetchErrorResult, O as InferDataFromTag, Ot as QueryObserverLoadingErrorResult, P as InfiniteQueryObserverLoadingResult, Pt as QueryObserverResult, Q as MutationMeta, Qt as unsetMarker, R as InfiniteQueryObserverRefetchErrorResult, Rt as QueryStatus, S as FetchNextPageOptions, St as QueryFunctionContext, T as FetchStatus, Tt as QueryKeyWithDataTag, U as InitialPageParam, Ut as ResultOptions, V as InfiniteQueryPageParamsOptions, Vt as Register, W as InvalidateOptions, Wt as SetDataOptions, X as MutationFunctionContext, Xt as dataTagErrorSymbol, Y as MutationFunction, Yt as WithRequired, Z as MutationKey, Zt as dataTagSymbol, _ as DefinedQueryObserverResult, _t as QueriesPlaceholderDataFunction, at as MutationObserverSuccessResult, b as EnsureQueryDataOptions, bt as QueryExecuteOptions, ct as MutationStatus, d as DataTag, dt as NotifyEvent, et as MutationObserverErrorResult, f as DefaultError, ft as NotifyEventType, g as DefinedInfiniteQueryObserverResult, gt as PlaceholderDataFunction, h as DefaultedQueryObserverOptions, ht as Override, it as MutationObserverResult, j as InfiniteQueryExecuteOptions, jt as QueryObserverPendingResult, k as InferErrorFromTag, kt as QueryObserverLoadingResult, l as AnyDataTag, lt as NetworkMode, m as DefaultedInfiniteQueryObserverOptions, mt as OmitKeyof, nt as MutationObserverLoadingResult, ot as MutationOptions, p as DefaultOptions, pt as NotifyOnChangeProps, q as MutateFunctionRest, qt as ThrowOnError, rt as MutationObserverOptions, st as MutationScope, tt as MutationObserverIdleResult, u as CancelOptions, ut as NonUndefinedGuard, v as DistributiveOmit, vt as QueryBooleanOption, w as FetchQueryOptions, wt as QueryKeyHashFunction, x as FetchInfiniteQueryOptions, xt as QueryFunction, y as EnsureInfiniteQueryDataOptions, yt as QueryClientConfig, z as InfiniteQueryObserverResult, zt as RefetchOptions } from "./hydration-
|
|
1
|
+
import { $ as MutationObserverBaseResult, A as InfiniteData, At as QueryObserverOptions, B as InfiniteQueryObserverSuccessResult, Bt as RefetchQueryFilters, C as FetchPreviousPageOptions, Ct as QueryKey, D as GetPreviousPageParamFunction, Dt as QueryObserverBaseResult, E as GetNextPageParamFunction, Et as QueryMeta, F as InfiniteQueryObserverOptions, Ft as QueryObserverSuccessResult, G as InvalidateQueryFilters, Gt as StaleTime, H as InitialDataFunction, Ht as ResetOptions, I as InfiniteQueryObserverPendingResult, It as QueryOptions, J as MutateOptions, Jt as UnsetMarker, K as MutateFunction, Kt as StaleTimeFunction, L as InfiniteQueryObserverPlaceholderResult, Lt as QueryPersister, M as InfiniteQueryObserverBaseResult, Mt as QueryObserverPlaceholderResult, N as InfiniteQueryObserverLoadingErrorResult, Nt as QueryObserverRefetchErrorResult, O as InferDataFromTag, Ot as QueryObserverLoadingErrorResult, P as InfiniteQueryObserverLoadingResult, Pt as QueryObserverResult, Q as MutationMeta, Qt as unsetMarker, R as InfiniteQueryObserverRefetchErrorResult, Rt as QueryStatus, S as FetchNextPageOptions, St as QueryFunctionContext, T as FetchStatus, Tt as QueryKeyWithDataTag, U as InitialPageParam, Ut as ResultOptions, V as InfiniteQueryPageParamsOptions, Vt as Register, W as InvalidateOptions, Wt as SetDataOptions, X as MutationFunctionContext, Xt as dataTagErrorSymbol, Y as MutationFunction, Yt as WithRequired, Z as MutationKey, Zt as dataTagSymbol, _ as DefinedQueryObserverResult, _t as QueriesPlaceholderDataFunction, at as MutationObserverSuccessResult, b as EnsureQueryDataOptions, bt as QueryExecuteOptions, ct as MutationStatus, d as DataTag, dt as NotifyEvent, et as MutationObserverErrorResult, f as DefaultError, ft as NotifyEventType, g as DefinedInfiniteQueryObserverResult, gt as PlaceholderDataFunction, h as DefaultedQueryObserverOptions, ht as Override, it as MutationObserverResult, j as InfiniteQueryExecuteOptions, jt as QueryObserverPendingResult, k as InferErrorFromTag, kt as QueryObserverLoadingResult, l as AnyDataTag, lt as NetworkMode, m as DefaultedInfiniteQueryObserverOptions, mt as OmitKeyof, nt as MutationObserverLoadingResult, ot as MutationOptions, p as DefaultOptions, pt as NotifyOnChangeProps, q as MutateFunctionRest, qt as ThrowOnError, rt as MutationObserverOptions, st as MutationScope, tt as MutationObserverIdleResult, u as CancelOptions, ut as NonUndefinedGuard, v as DistributiveOmit, vt as QueryBooleanOption, w as FetchQueryOptions, wt as QueryKeyHashFunction, x as FetchInfiniteQueryOptions, xt as QueryFunction, y as EnsureInfiniteQueryDataOptions, yt as QueryClientConfig, z as InfiniteQueryObserverResult, zt as RefetchOptions } from "./hydration-9_kOYxJM.js";
|
|
2
2
|
export { AnyDataTag, CancelOptions, DataTag, DefaultError, DefaultOptions, DefaultedInfiniteQueryObserverOptions, DefaultedQueryObserverOptions, DefinedInfiniteQueryObserverResult, DefinedQueryObserverResult, DistributiveOmit, EnsureInfiniteQueryDataOptions, EnsureQueryDataOptions, FetchInfiniteQueryOptions, FetchNextPageOptions, FetchPreviousPageOptions, FetchQueryOptions, FetchStatus, GetNextPageParamFunction, GetPreviousPageParamFunction, InferDataFromTag, InferErrorFromTag, InfiniteData, InfiniteQueryExecuteOptions, InfiniteQueryObserverBaseResult, InfiniteQueryObserverLoadingErrorResult, InfiniteQueryObserverLoadingResult, InfiniteQueryObserverOptions, InfiniteQueryObserverPendingResult, InfiniteQueryObserverPlaceholderResult, InfiniteQueryObserverRefetchErrorResult, InfiniteQueryObserverResult, InfiniteQueryObserverSuccessResult, InfiniteQueryPageParamsOptions, InitialDataFunction, InitialPageParam, InvalidateOptions, InvalidateQueryFilters, MutateFunction, MutateFunctionRest, MutateOptions, MutationFunction, MutationFunctionContext, MutationKey, MutationMeta, MutationObserverBaseResult, MutationObserverErrorResult, MutationObserverIdleResult, MutationObserverLoadingResult, MutationObserverOptions, MutationObserverResult, MutationObserverSuccessResult, MutationOptions, MutationScope, MutationStatus, NetworkMode, NonUndefinedGuard, NotifyEvent, NotifyEventType, NotifyOnChangeProps, OmitKeyof, Override, PlaceholderDataFunction, QueriesPlaceholderDataFunction, QueryBooleanOption, QueryClientConfig, QueryExecuteOptions, QueryFunction, QueryFunctionContext, QueryKey, QueryKeyHashFunction, QueryKeyWithDataTag, QueryMeta, QueryObserverBaseResult, QueryObserverLoadingErrorResult, QueryObserverLoadingResult, QueryObserverOptions, QueryObserverPendingResult, QueryObserverPlaceholderResult, QueryObserverRefetchErrorResult, QueryObserverResult, QueryObserverSuccessResult, QueryOptions, QueryPersister, QueryStatus, RefetchOptions, RefetchQueryFilters, Register, ResetOptions, ResultOptions, SetDataOptions, StaleTime, StaleTimeFunction, ThrowOnError, UnsetMarker, WithRequired, dataTagErrorSymbol, dataTagSymbol, unsetMarker };
|
package/build/modern/utils.cjs
CHANGED
|
@@ -183,7 +183,7 @@ function replaceEqualDeep(a, b, depth = 0) {
|
|
|
183
183
|
*/
|
|
184
184
|
function shallowEqualObjects(a, b) {
|
|
185
185
|
if (!b || Object.keys(a).length !== Object.keys(b).length) return false;
|
|
186
|
-
for (const key
|
|
186
|
+
for (const key of Object.keys(a)) if (!hasOwn.call(b, key) || a[key] !== b[key]) return false;
|
|
187
187
|
return true;
|
|
188
188
|
}
|
|
189
189
|
/**
|
|
@@ -273,29 +273,27 @@ function keepPreviousData(previousData) {
|
|
|
273
273
|
}
|
|
274
274
|
/**
|
|
275
275
|
* Returns a new array with `item` added at the end. If that makes the array longer than `max`,
|
|
276
|
-
*
|
|
277
|
-
* `items` already did.
|
|
276
|
+
* excess items are removed from the start.
|
|
278
277
|
* @param items - The current items.
|
|
279
278
|
* @param item - The value to append.
|
|
280
|
-
* @param max - The
|
|
279
|
+
* @param max - The maximum number of items to keep. `0` (the default) means no limit.
|
|
281
280
|
* @returns A new array with `item` added.
|
|
282
281
|
*/
|
|
283
282
|
function addToEnd(items, item, max = 0) {
|
|
284
283
|
const newItems = [...items, item];
|
|
285
|
-
return max && newItems.length > max ? newItems.slice(
|
|
284
|
+
return max && newItems.length > max ? newItems.slice(-max) : newItems;
|
|
286
285
|
}
|
|
287
286
|
/**
|
|
288
287
|
* Returns a new array with `item` added at the start. If that makes the array longer than `max`,
|
|
289
|
-
*
|
|
290
|
-
* `items` already did.
|
|
288
|
+
* excess items are removed from the end.
|
|
291
289
|
* @param items - The current items.
|
|
292
290
|
* @param item - The value to prepend.
|
|
293
|
-
* @param max - The
|
|
291
|
+
* @param max - The maximum number of items to keep. `0` (the default) means no limit.
|
|
294
292
|
* @returns A new array with `item` added.
|
|
295
293
|
*/
|
|
296
294
|
function addToStart(items, item, max = 0) {
|
|
297
295
|
const newItems = [item, ...items];
|
|
298
|
-
return max && newItems.length > max ? newItems.slice(0,
|
|
296
|
+
return max && newItems.length > max ? newItems.slice(0, max) : newItems;
|
|
299
297
|
}
|
|
300
298
|
/**
|
|
301
299
|
* Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent
|
|
@@ -348,6 +346,7 @@ function shouldThrowError(throwOnError, params) {
|
|
|
348
346
|
if (typeof throwOnError === "function") return throwOnError(...params);
|
|
349
347
|
return !!throwOnError;
|
|
350
348
|
}
|
|
349
|
+
const fetchSignal = Symbol();
|
|
351
350
|
/**
|
|
352
351
|
* Adds a lazy `signal` getter to an object, such as a query function context. The first time
|
|
353
352
|
* `signal` is read, `onCancelled` is registered for the signal's `abort` event (or called right
|
|
@@ -355,20 +354,24 @@ function shouldThrowError(throwOnError, params) {
|
|
|
355
354
|
* @param object - The object to add the `signal` property to.
|
|
356
355
|
* @param getSignal - Returns the `AbortSignal`. Called once, when `signal` is first read.
|
|
357
356
|
* @param onCancelled - Called when the signal is aborted, if `signal` was read.
|
|
357
|
+
* @param internalSignal - The fetch signal to forward without consuming the getter.
|
|
358
358
|
* @returns The same object, with the `signal` property added.
|
|
359
359
|
*/
|
|
360
|
-
function addConsumeAwareSignal(object, getSignal, onCancelled) {
|
|
360
|
+
function addConsumeAwareSignal(object, getSignal, onCancelled, internalSignal) {
|
|
361
361
|
let consumed = false;
|
|
362
362
|
let signal;
|
|
363
|
-
Object.
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
363
|
+
Object.defineProperties(object, {
|
|
364
|
+
[fetchSignal]: { value: internalSignal },
|
|
365
|
+
signal: {
|
|
366
|
+
enumerable: true,
|
|
367
|
+
get: () => {
|
|
368
|
+
signal ??= getSignal();
|
|
369
|
+
if (consumed) return signal;
|
|
370
|
+
consumed = true;
|
|
371
|
+
if (signal.aborted) onCancelled();
|
|
372
|
+
else signal.addEventListener("abort", onCancelled, { once: true });
|
|
373
|
+
return signal;
|
|
374
|
+
}
|
|
372
375
|
}
|
|
373
376
|
});
|
|
374
377
|
return object;
|
|
@@ -377,6 +380,7 @@ exports.addConsumeAwareSignal = addConsumeAwareSignal;
|
|
|
377
380
|
exports.addToEnd = addToEnd;
|
|
378
381
|
exports.addToStart = addToStart;
|
|
379
382
|
exports.ensureQueryFn = ensureQueryFn;
|
|
383
|
+
exports.fetchSignal = fetchSignal;
|
|
380
384
|
exports.functionalUpdate = functionalUpdate;
|
|
381
385
|
exports.hashKey = hashKey;
|
|
382
386
|
exports.hashQueryKeyByOptions = hashQueryKeyByOptions;
|