@hyper-fetch/core 10.4.0 → 10.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/__tests__/features/adapter/adapter.mapping.spec.ts +29 -1
- package/__tests__/features/cache/cache.modes.spec.ts +33 -0
- package/__tests__/features/client/client.configuration.spec.ts +24 -0
- package/__tests__/features/request/request.exec.spec.ts +129 -0
- package/__tests__/features/request/request.signal.spec.ts +243 -0
- package/__tests__/features/request/request.throw-on-error.spec.ts +219 -0
- package/__tests__/features/request/request.typescript.spec.ts +46 -0
- package/dist/adapter/adapter.d.ts +8 -1
- package/dist/adapter/adapter.d.ts.map +1 -1
- package/dist/adapter/adapter.types.d.ts +7 -8
- package/dist/adapter/adapter.types.d.ts.map +1 -1
- package/dist/client/client.types.d.ts +2 -1
- package/dist/client/client.types.d.ts.map +1 -1
- package/dist/client/client.utils.d.ts +6 -1
- package/dist/client/client.utils.d.ts.map +1 -1
- package/dist/index.mjs +1539 -1389
- package/dist/index.mjs.map +1 -1
- package/dist/infinite/infinite.d.ts.map +1 -1
- package/dist/request/request.d.ts +10 -2
- package/dist/request/request.d.ts.map +1 -1
- package/dist/request/request.types.d.ts +15 -0
- package/dist/request/request.types.d.ts.map +1 -1
- package/dist/request/request.utils.d.ts +19 -1
- package/dist/request/request.utils.d.ts.map +1 -1
- package/dist/sdk/sdk.d.ts +1 -0
- package/dist/sdk/sdk.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/adapter/adapter.ts +10 -3
- package/src/adapter/adapter.types.ts +7 -5
- package/src/client/client.types.ts +2 -1
- package/src/client/client.utils.ts +12 -2
- package/src/infinite/infinite.ts +2 -1
- package/src/request/request.ts +95 -26
- package/src/request/request.types.ts +15 -0
- package/src/request/request.utils.ts +148 -46
- package/src/sdk/sdk.ts +4 -0
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/plugin/plugin.ts","../src/constants/time.constants.ts","../src/request/request.hooks.ts","../src/mocker/mocker.ts","../src/adapter/adapter.bindings.ts","../src/adapter/adapter.utils.ts","../src/adapter/adapter.ts","../src/constants/http.constants.ts","../src/optimistic/optimistic.utils.ts","../src/optimistic/optimistic.ts","../src/utils/error.utils.ts","../src/utils/uuid.utils.ts","../../../node_modules/.pnpm/events@3.3.0/node_modules/events/events.js","../src/utils/emitter.utils.ts","../src/optimistic/optimistic.settlement.ts","../src/request/request.utils.ts","../src/request/request.ts","../src/cache/cache.ts","../src/cache/cache.utils.ts","../src/cache/cache.events.ts","../src/dispatcher/dispatcher.constants.ts","../src/dispatcher/dispatcher.events.ts","../src/dispatcher/dispatcher.ts","../src/dispatcher/dispatcher.utils.ts","../src/http-adapter/http-adapter.constants.ts","../src/http-adapter/http-adapter.utils.ts","../src/http-adapter/http-adapter.fetch.ts","../src/http-adapter/http-adapter.ts","../src/managers/app/app.manager.ts","../src/managers/app/app.manager.utils.ts","../src/managers/app/app.manager.events.ts","../src/managers/app/app.manager.constants.ts","../src/managers/request/request.manager.ts","../src/managers/request/request.manager.utils.ts","../src/managers/request/request.manager.events.ts","../src/managers/logger/logger.manager.ts","../src/managers/logger/logger.manager.utils.ts","../src/managers/logger/logger.manager.constants.ts","../src/client/client.utils.ts","../src/client/client.ts","../src/client/client.constants.ts","../src/client/client.create.ts","../src/sdk/sdk.ts","../src/infinite/infinite.utils.ts","../src/infinite/infinite.ts"],"sourcesContent":["import type { ClientInstance } from \"client\";\nimport type { PluginMethodParameters, PluginMethods, PluginOptionsType } from \"plugin\";\n\n/**\n * Base class for plugins that hook into the request, cache, dispatcher, and adapter lifecycle.\n * Extend this to build devtools, logging, analytics, or custom side-effect plugins.\n */\nexport class Plugin<Client extends ClientInstance = ClientInstance, PluginData = void> {\n public name: string;\n public data: PluginData;\n\n public client: Client | undefined = undefined;\n\n private pluginMethods: Partial<PluginMethods<Client>> = {};\n\n constructor(public config: PluginOptionsType<PluginData>) {\n this.name = config.name;\n if (config.data) {\n this.data = config.data;\n }\n }\n\n /** Bind the plugin to a client instance. Called automatically when the plugin is added via `client.addPlugin()`. */\n initialize = (client: Client) => {\n this.client = client;\n return this;\n };\n\n /** Invoke a registered plugin method by name. Used internally by the client to dispatch lifecycle events. */\n trigger = <Key extends keyof PluginMethods<Client>>(method: Key, data: PluginMethodParameters<Key, Client>) => {\n const callback = this.pluginMethods[method];\n if (callback) {\n callback(data as any);\n }\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Plugin lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /**\n * Callback that will be executed when plugin is mounted\n */\n onMount = (callback: PluginMethods<Client>[\"onMount\"]) => {\n this.pluginMethods.onMount = callback;\n return this;\n };\n\n /**\n * Callback that will be executed when plugin is unmounted\n */\n onUnmount = (callback: PluginMethods<Client>[\"onUnmount\"]) => {\n this.pluginMethods.onUnmount = callback;\n return this;\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Request lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /**\n * Callback that will be executed when request is created\n */\n onRequestCreate = (callback: PluginMethods<Client>[\"onRequestCreate\"]) => {\n this.pluginMethods.onRequestCreate = callback;\n return this;\n };\n /**\n * Callback that will be executed when request gets triggered\n */\n onRequestTrigger = (callback: PluginMethods<Client>[\"onRequestTrigger\"]) => {\n this.pluginMethods.onRequestTrigger = callback;\n return this;\n };\n /**\n * Callback that will be executed when request starts\n */\n onRequestStart = (callback: PluginMethods<Client>[\"onRequestStart\"]) => {\n this.pluginMethods.onRequestStart = callback;\n return this;\n };\n /**\n * Callback that will be executed when response is successful\n */\n onRequestSuccess = (callback: PluginMethods<Client>[\"onRequestSuccess\"]) => {\n this.pluginMethods.onRequestSuccess = callback;\n return this;\n };\n /**\n * Callback that will be executed when response is failed\n */\n onRequestError = (callback: PluginMethods<Client>[\"onRequestError\"]) => {\n this.pluginMethods.onRequestError = callback;\n return this;\n };\n /**\n * Callback that will be executed when response is finished\n */\n onRequestFinished = (callback: PluginMethods<Client>[\"onRequestFinished\"]) => {\n this.pluginMethods.onRequestFinished = callback;\n return this;\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Dispatcher lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /** Called when the dispatcher storage is fully cleared */\n onDispatcherCleared = (callback: PluginMethods<Client>[\"onDispatcherCleared\"]) => {\n this.pluginMethods.onDispatcherCleared = callback;\n return this;\n };\n\n /** Called when a dispatcher queue has no more pending requests */\n onDispatcherQueueDrained = (callback: PluginMethods<Client>[\"onDispatcherQueueDrained\"]) => {\n this.pluginMethods.onDispatcherQueueDrained = callback;\n return this;\n };\n\n /** Called when a dispatcher queue transitions to running, paused, or stopped */\n onDispatcherQueueRunning = (callback: PluginMethods<Client>[\"onDispatcherQueueRunning\"]) => {\n this.pluginMethods.onDispatcherQueueRunning = callback;\n return this;\n };\n\n /** Called when a new item is added to a dispatcher queue */\n onDispatcherItemAdded = (callback: PluginMethods<Client>[\"onDispatcherItemAdded\"]) => {\n this.pluginMethods.onDispatcherItemAdded = callback;\n return this;\n };\n\n /** Called when an item is removed from a dispatcher queue */\n onDispatcherItemDeleted = (callback: PluginMethods<Client>[\"onDispatcherItemDeleted\"]) => {\n this.pluginMethods.onDispatcherItemDeleted = callback;\n return this;\n };\n\n /** Called when a new dispatcher queue is created */\n onDispatcherQueueCreated = (callback: PluginMethods<Client>[\"onDispatcherQueueCreated\"]) => {\n this.pluginMethods.onDispatcherQueueCreated = callback;\n return this;\n };\n\n /** Called when an entire dispatcher queue is cleared */\n onDispatcherQueueCleared = (callback: PluginMethods<Client>[\"onDispatcherQueueCleared\"]) => {\n this.pluginMethods.onDispatcherQueueCleared = callback;\n return this;\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Cache lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /** Called when a cache entry is created or updated */\n onCacheItemChange = (callback: PluginMethods<Client>[\"onCacheItemChange\"]) => {\n this.pluginMethods.onCacheItemChange = callback;\n return this;\n };\n\n /** Called when a cache entry is deleted */\n onCacheItemDelete = (callback: PluginMethods<Client>[\"onCacheItemDelete\"]) => {\n this.pluginMethods.onCacheItemDelete = callback;\n return this;\n };\n\n /** Called when a cache entry is invalidated */\n onCacheItemInvalidate = (callback: PluginMethods<Client>[\"onCacheItemInvalidate\"]) => {\n this.pluginMethods.onCacheItemInvalidate = callback;\n return this;\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Adapter lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /** Called when the adapter fetcher is about to execute a request */\n onAdapterFetch = (callback: PluginMethods<Client>[\"onAdapterFetch\"]) => {\n this.pluginMethods.onAdapterFetch = callback;\n return this;\n };\n}\n","export enum Time {\n SEC = 1e3,\n MIN = 6e4,\n HOUR = 3.6e6,\n DAY = 8.64e7,\n WEEK = 6.048e8,\n MONTH_30 = 2.592e9,\n MONTH_31 = 2.6784e9,\n YEAR = 3.1536e10,\n YEAR_LEAP = 3.162_24e10,\n}\n","import type {\n RequestEventType,\n RequestProgressEventType,\n RequestResponseEventType,\n RequestRetryEventType,\n} from \"managers\";\n\nimport type { RequestInstance } from \"./request.types\";\n\ntype HookName =\n | \"onBeforeSent\"\n | \"onRequestStart\"\n | \"onResponseStart\"\n | \"onUploadProgress\"\n | \"onDownloadProgress\"\n | \"onResponse\"\n | \"onRetry\"\n | \"onRemove\";\n\nexport interface RequestHooks<R extends RequestInstance> {\n onBeforeSent: (cb: (eventData: RequestEventType<R>) => void) => () => void;\n onRequestStart: (cb: (eventData: RequestEventType<R>) => void) => () => void;\n onResponseStart: (cb: (eventData: RequestEventType<R>) => void) => () => void;\n onUploadProgress: (cb: (eventData: RequestProgressEventType<R>) => void) => () => void;\n onDownloadProgress: (cb: (eventData: RequestProgressEventType<R>) => void) => () => void;\n onResponse: (cb: (eventData: RequestResponseEventType<R>) => void) => () => void;\n /** Called when a failed attempt of a `send()` schedules a retry, with the `retry` number and its `delay` */\n onRetry: (cb: (eventData: RequestRetryEventType<R>) => void) => () => void;\n onRemove: (cb: (eventData: RequestEventType<R>) => void) => () => void;\n /** @internal Invoke all registered listeners for a given hook */\n __emit: (name: HookName, data: any) => void;\n /** @internal Get a snapshot of all registered listeners (used by clone) */\n __snapshot: () => Record<HookName, ((...args: any[]) => void)[]>;\n}\n\nconst HOOK_NAMES: HookName[] = [\n \"onBeforeSent\",\n \"onRequestStart\",\n \"onResponseStart\",\n \"onUploadProgress\",\n \"onDownloadProgress\",\n \"onResponse\",\n \"onRetry\",\n \"onRemove\",\n];\n\nexport function createRequestHooks<R extends RequestInstance>(\n initial?: Record<HookName, ((...args: any[]) => void)[]>,\n): RequestHooks<R> {\n const listeners: Record<HookName, ((...args: any[]) => void)[]> = {\n onBeforeSent: [],\n onRequestStart: [],\n onResponseStart: [],\n onUploadProgress: [],\n onDownloadProgress: [],\n onResponse: [],\n onRetry: [],\n onRemove: [],\n };\n\n if (initial) {\n HOOK_NAMES.forEach((name) => {\n listeners[name] = [...initial[name]];\n });\n }\n\n const subscribe = (name: HookName) => {\n return (cb: (...args: any[]) => void) => {\n listeners[name].push(cb);\n return () => {\n const idx = listeners[name].indexOf(cb);\n if (idx !== -1) {listeners[name].splice(idx, 1);}\n };\n };\n };\n\n return {\n onBeforeSent: subscribe(\"onBeforeSent\"),\n onRequestStart: subscribe(\"onRequestStart\"),\n onResponseStart: subscribe(\"onResponseStart\"),\n onUploadProgress: subscribe(\"onUploadProgress\"),\n onDownloadProgress: subscribe(\"onDownloadProgress\"),\n onResponse: subscribe(\"onResponse\"),\n onRetry: subscribe(\"onRetry\"),\n onRemove: subscribe(\"onRemove\"),\n __emit(name: HookName, data: any) {\n listeners[name].forEach((cb) => {\n cb(data);\n });\n },\n __snapshot() {\n const snap = {} as Record<HookName, ((...args: any[]) => void)[]>;\n HOOK_NAMES.forEach((name) => {\n snap[name] = [...listeners[name]];\n });\n return snap;\n },\n };\n}\n","import type { getAdapterBindings, AdapterInstance } from \"adapter\";\nimport { RequestProcessingError } from \"adapter\";\nimport type { ExtractAdapterExtraType, ExtractAdapterStatusType } from \"types\";\n\nexport const mocker = async <T extends AdapterInstance>({\n request,\n requestId,\n onError,\n onResponseEnd,\n onTimeoutError,\n onRequestEnd,\n createAbortListener,\n onResponseProgress,\n onRequestProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onSuccess,\n adapter,\n}: Awaited<ReturnType<typeof getAdapterBindings<T>>>) => {\n if (!request.unstable_mock) {\n throw new RequestProcessingError(\"Mock should be defined when calling mocker\");\n }\n\n let thrown = false;\n\n const {\n requestTime = 20,\n responseTime = 20,\n totalUploaded = 1000,\n totalDownloaded = 1000,\n timeout,\n } = request.unstable_mock.config;\n const result = await request.unstable_mock.fn({ request, requestId });\n\n const { data, error, status, extra = request.client.adapter.defaultExtra } = result;\n // Without the `success` flag, a mock with nothing but an error is a failed response\n const hasData = data !== undefined && data !== null;\n const { success = !error || hasData } = result;\n\n createAbortListener({\n status: adapter.systemErrorStatus,\n extra: adapter.systemErrorExtra,\n onAbort: () => {\n thrown = true;\n },\n });\n\n onBeforeRequest();\n onRequestStart();\n\n const progress = (\n totalTime: number,\n totalSize: number,\n progressFunction: typeof onResponseProgress | typeof onRequestProgress,\n ) =>\n new Promise((resolveProgress) => {\n if (thrown) {\n resolveProgress(true);\n return;\n }\n\n const interval = 20;\n const dataStart = Date.now();\n const intervals = Math.ceil(totalTime / interval);\n const chunkSize = Math.ceil(totalSize / intervals);\n let currentlyLoaded = 0;\n const timer = setInterval(function handleProgressInterval() {\n // Aborted or timed out - nothing more is transferred\n if (thrown) {\n resolveProgress(true);\n clearInterval(timer);\n return;\n }\n\n const currentTime = Math.min(totalTime, Date.now() - dataStart);\n currentlyLoaded += currentlyLoaded + chunkSize >= totalSize ? totalSize - currentlyLoaded : chunkSize;\n progressFunction({\n total: totalSize,\n loaded: currentTime >= totalTime ? totalSize : currentlyLoaded,\n });\n\n if (currentTime >= totalTime) {\n resolveProgress(true);\n clearInterval(timer);\n }\n }, interval);\n });\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n if (typeof timeout === \"number\") {\n timeoutId = setTimeout(() => {\n thrown = true;\n onTimeoutError({\n status: 0 as ExtractAdapterStatusType<T>,\n extra: extra as ExtractAdapterExtraType<T>,\n });\n }, timeout);\n }\n if (!thrown) {\n await progress(requestTime, totalUploaded, onRequestProgress);\n }\n if (!thrown) {\n onRequestEnd();\n onResponseStart();\n }\n if (!thrown) {\n await progress(responseTime, totalDownloaded, onResponseProgress);\n }\n clearTimeout(timeoutId);\n // An abort or a timeout was already reported when it happened\n if (thrown) {\n return;\n }\n if (success || (error && data)) {\n onSuccess({\n data,\n error,\n status: status as ExtractAdapterStatusType<T>,\n extra: extra as ExtractAdapterExtraType<T>,\n });\n } else {\n onError({\n error,\n status: status as ExtractAdapterStatusType<T>,\n extra: extra as ExtractAdapterExtraType<T>,\n });\n }\n onResponseEnd();\n};\n","import type { ResponseSuccessType, ResponseErrorType, ProgressDataType, ProgressType, AdapterInstance } from \"adapter\";\nimport { getErrorMessage, RequestProcessingError } from \"adapter\";\nimport type { LoggerMethods } from \"managers\";\nimport type { RequestInstance, ProgressEventType } from \"request\";\nimport { getProgressData, scopeKey } from \"request\";\nimport type {\n ExtractResponseType,\n ExtractErrorType,\n ExtractPayloadType,\n ExtractAdapterOptionsType,\n ExtractAdapterStatusType,\n ExtractAdapterExtraType,\n} from \"types\";\n\nexport const getAdapterBindings = async <T extends AdapterInstance>({\n request: baseRequest,\n requestId,\n resolve,\n onStartTime,\n internalErrorMapping,\n}: {\n request: RequestInstance;\n requestId: string;\n resolve: (value: ResponseSuccessType<any, T> | ResponseErrorType<any, T>) => void;\n onStartTime: (timestamp: number) => void;\n internalErrorMapping: (error: ReturnType<typeof getErrorMessage>) => any;\n}) => {\n const { requestManager, loggerManager } = baseRequest.client;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { unstable_payloadMapper } = baseRequest.client.adapter;\n\n const logger = loggerManager.initialize(baseRequest.client, \"Adapter\");\n\n let requestStartTimestamp: null | number = null;\n let responseStartTimestamp: null | number = null;\n let request = baseRequest;\n\n // Progress\n let requestTotal = 1;\n let responseTotal = 1;\n // Last emitted progress - an identical update is not emitted again\n let previousRequestProgress: { total: number; loaded: number } | null = null;\n let previousResponseProgress: { total: number; loaded: number } | null = null;\n\n const isSameProgress = (previous: { total: number; loaded: number } | null, next: ProgressType) =>\n !!previous && previous.total === next.total && previous.loaded === next.loaded;\n\n // Pre request modifications\n logger.debug({\n title: `Running middleware callbacks`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n\n request = await request.client.unstable_modifyRequest(request);\n\n if (request.auth) {\n request = await request.client.unstable_modifyAuth(request);\n }\n\n if (request.unstable_requestMapper) {\n request = await request.unstable_requestMapper(request, requestId);\n }\n\n // Request Setup\n const { client, abortKey } = request;\n const scopedAbortKey = scopeKey(abortKey, request.scope);\n\n // eslint-disable-next-line prefer-destructuring\n let payload = request.payload;\n\n if (request.unstable_payloadMapper) {\n payload = await request.unstable_payloadMapper<ExtractPayloadType<RequestInstance>>(request.payload);\n } else if (unstable_payloadMapper) {\n payload = await unstable_payloadMapper(payload);\n }\n\n // Defaults from `adapter.setAdapterDefaults()`, overridden by the options of the request\n const adapterDefaults = client.adapter.unstable_getAdapterDefaults?.(request as any);\n const adapterOptions = (adapterDefaults ? { ...adapterDefaults, ...request.options } : request.options) as\n | ExtractAdapterOptionsType<T>\n | undefined;\n const startTime = Date.now();\n onStartTime(startTime);\n\n const getRequestStartTimestamp = () => {\n return requestStartTimestamp;\n };\n\n const getResponseStartTimestamp = () => {\n return responseStartTimestamp;\n };\n\n // Progress\n\n const getTotal = (previousTotal: number, progress?: ProgressDataType) => {\n if (!progress) {\n return previousTotal;\n }\n const total = Number(progress.total || 0);\n const loaded = Number(progress.loaded || 0);\n return Math.max(total, loaded, previousTotal);\n };\n\n const handleRequestProgress = (\n startTimestamp: number,\n progressTimestamp: number,\n progressEvent: ProgressEventType,\n ) => {\n const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);\n\n if (!isSameProgress(previousRequestProgress, progress)) {\n previousRequestProgress = { total: progress.total, loaded: progress.loaded };\n requestManager.events.emitUploadProgress({ ...progress, requestId, request });\n }\n };\n\n const handleResponseProgress = (\n startTimestamp: number,\n progressTimestamp: number,\n progressEvent: ProgressEventType,\n ) => {\n const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);\n\n if (!isSameProgress(previousResponseProgress, progress)) {\n previousResponseProgress = { total: progress.total, loaded: progress.loaded };\n requestManager.events.emitDownloadProgress({ ...progress, requestId, request });\n }\n };\n\n // Pre-request\n\n const onBeforeRequest = () => {\n logger.debug({\n title: `Request about to be sent`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n client.triggerPlugins(\"onRequestTrigger\", { request });\n };\n\n // Request\n\n const onRequestStart = (progress?: ProgressDataType) => {\n logger.info({\n title: `Request start`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n client.triggerPlugins(\"onRequestStart\", { request });\n\n if (progress?.total) {\n requestTotal = getTotal(requestTotal, progress);\n }\n\n const initialPayload = {\n total: requestTotal,\n loaded: progress?.loaded || 0,\n };\n requestStartTimestamp = Date.now();\n handleRequestProgress(requestStartTimestamp, requestStartTimestamp, initialPayload);\n requestManager.events.emitRequestStart({ requestId, request });\n return requestStartTimestamp;\n };\n\n const onRequestProgress = (progress: ProgressDataType) => {\n if (!requestStartTimestamp) {\n requestStartTimestamp = Date.now();\n }\n requestTotal = getTotal(requestTotal, progress);\n\n const progressTimestamp = Date.now();\n\n handleRequestProgress(requestStartTimestamp, progressTimestamp, {\n total: requestTotal,\n loaded: progress.loaded || 0,\n });\n return progressTimestamp;\n };\n\n const onRequestEnd = () => {\n if (!requestStartTimestamp) {\n requestStartTimestamp = Date.now();\n }\n\n const progressTimestamp = Date.now();\n handleRequestProgress(requestStartTimestamp, progressTimestamp, {\n total: requestTotal,\n loaded: requestTotal,\n });\n return progressTimestamp;\n };\n\n // Response\n\n const onResponseStart = (progress?: ProgressDataType) => {\n responseStartTimestamp = Date.now();\n\n responseTotal = getTotal(responseTotal, progress);\n\n const initialPayload = {\n total: responseTotal,\n loaded: progress?.loaded || 0,\n };\n\n handleResponseProgress(responseStartTimestamp, responseStartTimestamp, initialPayload);\n requestManager.events.emitResponseStart({ requestId, request });\n return responseStartTimestamp;\n };\n\n const onResponseProgress = (progress: ProgressDataType) => {\n if (!responseStartTimestamp) {\n responseStartTimestamp = Date.now();\n }\n\n const progressTimestamp = Date.now();\n responseTotal = getTotal(responseTotal, progress);\n\n // The total never drops below the loaded bytes - e.g. a compressed body is counted after decompression,\n // while its Content-Length tells the compressed size\n handleResponseProgress(responseStartTimestamp, progressTimestamp, {\n total: responseTotal,\n loaded: progress.loaded || 0,\n });\n return progressTimestamp;\n };\n\n const onResponseEnd = () => {\n if (!responseStartTimestamp) {\n responseStartTimestamp = Date.now();\n }\n\n const progressTimestamp = Date.now();\n handleResponseProgress(responseStartTimestamp, progressTimestamp, {\n total: responseTotal,\n loaded: responseTotal,\n });\n return progressTimestamp;\n };\n\n // Success\n\n const onSuccess = async ({\n data,\n error,\n status,\n extra,\n }: {\n data: any;\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n error?: ExtractErrorType<T>;\n }): Promise<ResponseSuccessType<ExtractResponseType<T>, T>> => {\n let response: ResponseSuccessType<ExtractResponseType<T>, T> = {\n data,\n error: error ?? null,\n success: true,\n status,\n extra,\n requestTimestamp: startTime,\n responseTimestamp: Date.now(),\n };\n try {\n response = (await request.client.unstable_modifyResponse?.(response, request)) as typeof data;\n response = (await request.client.unstable_modifySuccessResponse?.(response, request)) as typeof data;\n\n client.triggerPlugins(\"onRequestSuccess\", { response, request });\n client.triggerPlugins(\"onRequestFinished\", { response, request });\n } catch (interceptorError) {\n // A throwing interceptor or plugin fails the request, it must not leave it without any response\n response = {\n data: null,\n error: internalErrorMapping(interceptorError as ReturnType<typeof getErrorMessage>),\n success: false,\n status,\n extra,\n requestTimestamp: startTime,\n responseTimestamp: Date.now(),\n } as unknown as typeof response;\n }\n\n resolve(response);\n\n logger.info({\n title: `Response success`,\n type: \"response\",\n extra: {\n request,\n requestId,\n response,\n },\n });\n return response;\n };\n\n // Errors\n\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n const onError = getAdapterOnError({\n request,\n requestId,\n startTime,\n logger,\n resolve,\n });\n\n const onAbortError = ({\n status,\n extra,\n }: {\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n }) => {\n logger.error({\n title: `Abort error`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n const error = internalErrorMapping(getErrorMessage(\"abort\"));\n return onError({ error, status, extra });\n };\n\n const onTimeoutError = ({\n status,\n extra,\n }: {\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n }) => {\n logger.error({\n title: `Timeout error`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n const error = internalErrorMapping(getErrorMessage(\"timeout\"));\n return onError({ error, status, extra });\n };\n\n const onUnexpectedError = ({\n status,\n extra,\n }: {\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n }) => {\n logger.error({\n title: `Unexpected error`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n const error = internalErrorMapping(getErrorMessage());\n return onError({ error, status, extra });\n };\n\n // Abort\n\n const getAbortController = () => {\n return requestManager.getAbortController(scopedAbortKey, requestId);\n };\n\n const createAbortListener = ({\n status,\n extra,\n onAbort = () => {},\n }: {\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n onAbort?: () => void;\n }) => {\n const controller = getAbortController();\n if (!controller) {\n throw new RequestProcessingError(\"Controller is not found\");\n }\n\n const abort = () => {\n onAbortError({ status, extra });\n onAbort();\n requestManager.events.emitAbort({ requestId, request });\n };\n\n // Instant abort when we stack many requests triggered at once, and we receive aborted controller\n if (controller.signal.aborted) {\n abort();\n }\n\n // Abort during the request\n controller.signal.addEventListener(\"abort\", abort);\n\n return () => controller.signal.removeEventListener(\"abort\", abort);\n };\n\n logger.debug({\n title: `Mounted adapter bindings`,\n type: \"request\",\n extra: {\n request,\n requestId,\n payload,\n adapterOptions,\n },\n });\n\n const queryParams = baseRequest.client.adapter.unstable_queryParamsMapper(request.queryParams);\n const endpoint = baseRequest.client.adapter.unstable_endpointMapper(request.endpoint);\n const headers = baseRequest.client.adapter.unstable_headerMapper(request);\n const { url } = baseRequest.client;\n\n return {\n request,\n requestId,\n url,\n endpoint,\n queryParams,\n payload,\n headers,\n adapter: baseRequest.client.adapter,\n adapterOptions,\n getAbortController,\n getRequestStartTimestamp,\n getResponseStartTimestamp,\n createAbortListener,\n onBeforeRequest,\n onRequestStart,\n onRequestProgress,\n onRequestEnd,\n onResponseStart,\n onResponseProgress,\n onResponseEnd,\n onSuccess,\n onAbortError,\n onTimeoutError,\n onUnexpectedError,\n onError,\n };\n};\n\nexport function getAdapterOnError<T extends AdapterInstance>({\n request,\n requestId,\n startTime,\n resolve,\n logger,\n}: {\n request: RequestInstance;\n requestId: string;\n startTime: number;\n logger: LoggerMethods;\n resolve: (value: ResponseSuccessType<any, T> | ResponseErrorType<any, T>) => void;\n}) {\n const { client } = request;\n\n return async ({\n error,\n status,\n extra,\n }: {\n error: any;\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n }): Promise<ResponseErrorType<any, T>> => {\n let response: ResponseErrorType<any, T> = {\n data: null,\n status,\n error,\n success: false,\n extra,\n requestTimestamp: startTime,\n responseTimestamp: Date.now(),\n };\n\n try {\n response = (await client.unstable_modifyResponse(response, request)) as typeof response;\n response = (await client.unstable_modifyErrorResponse(response, request)) as typeof response;\n\n client.triggerPlugins(\"onRequestError\", { response, request });\n client.triggerPlugins(\"onRequestFinished\", { response, request });\n } catch (interceptorError) {\n // A throwing interceptor or plugin replaces the error, it must not leave the request without any response\n response = { ...response, data: null, error: interceptorError, success: false };\n }\n\n resolve(response);\n\n logger.error({\n title: `Request error`,\n type: \"request\",\n extra: {\n request,\n requestId,\n response,\n },\n });\n\n return response;\n };\n}\n","/* eslint-disable max-classes-per-file */\n// Utils\nimport type { RequestInstance } from \"request\";\n\nexport class TimeoutError extends Error {\n constructor() {\n super(\"Request timeout\");\n this.name = \"TimeoutError\";\n }\n}\n\nexport class AbortError extends Error {\n constructor() {\n super(\"Request aborted\");\n this.name = \"AbortError\";\n }\n}\n\nexport class DeletedError extends Error {\n constructor() {\n super(\"Request deleted\");\n this.name = \"DeletedError\";\n }\n}\n\nexport class RequestProcessingError extends Error {\n description?: string = undefined;\n\n constructor(description?: string) {\n super(\"Request processing error\");\n this.description = description;\n this.name = \"RequestProcessingError\";\n }\n}\n\nexport class UnexpectedError extends Error {\n description?: string = undefined;\n\n constructor(description?: string) {\n super(\"Unexpected error\");\n this.description = description;\n this.name = \"UnexpectedError\";\n }\n}\n\nexport const getErrorMessage = (errorCase?: \"timeout\" | \"abort\" | \"deleted\" | \"processing\" | \"unexpected\") => {\n if (errorCase === \"timeout\") {\n return new TimeoutError();\n }\n if (errorCase === \"abort\") {\n return new AbortError();\n }\n if (errorCase === \"deleted\") {\n return new DeletedError();\n }\n if (errorCase === \"processing\") {\n return new RequestProcessingError();\n }\n return new UnexpectedError();\n};\n\n// Mappers\n\nexport const stringifyValue = (response: string | unknown): string => {\n try {\n return JSON.stringify(response as string);\n } catch {\n return \"\";\n }\n};\n\n/**\n * Payloads which are sent as they are - `fetch`, XHR and other transports know how to handle them\n * (and how to describe them with the `Content-Type` header)\n */\nconst isRawPayload = (payload: unknown): boolean => {\n return (\n (typeof FormData !== \"undefined\" && payload instanceof FormData) ||\n (typeof Blob !== \"undefined\" && payload instanceof Blob) ||\n (typeof URLSearchParams !== \"undefined\" && payload instanceof URLSearchParams) ||\n (typeof ReadableStream !== \"undefined\" && payload instanceof ReadableStream) ||\n (typeof ArrayBuffer !== \"undefined\" && (payload instanceof ArrayBuffer || ArrayBuffer.isView(payload)))\n );\n};\n\n/** `HeadersInit` can be an object, a list of pairs or the `Headers` instance */\nconst getHeadersEntries = (headers: HeadersInit | undefined): [string, string][] => {\n if (!headers) {\n return [];\n }\n if (typeof Headers !== \"undefined\" && headers instanceof Headers) {\n const entries: [string, string][] = [];\n headers.forEach((value, key) => entries.push([key, value]));\n return entries;\n }\n if (Array.isArray(headers)) {\n return headers as [string, string][];\n }\n return Object.entries(headers);\n};\n\nexport const getAdapterHeaders = (request: RequestInstance) => {\n const isObject = typeof request.payload === \"object\" && request.payload !== null;\n const entries = getHeadersEntries(request.headers);\n // Header names are case-insensitive, so \"content-type\" given with the request replaces the default one\n const hasContentType = entries.some(([name]) => name.toLowerCase() === \"content-type\");\n const headers: Record<string, string> = {};\n\n if (isObject && !isRawPayload(request.payload) && !hasContentType) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n entries.forEach(([name, value]) => {\n // Empty value is the way to not send a header (also the default one)\n if (value !== undefined && value !== null) {\n headers[name] = value;\n }\n });\n return headers as HeadersInit;\n};\n\nexport const getAdapterPayload = (data: unknown): string | FormData => {\n // Binary, form and stream payloads can't be turned into JSON - they would end up as \"{}\"\n if (isRawPayload(data)) {\n return data as FormData;\n }\n\n return stringifyValue(data);\n};\n","import type { Client, ClientInstance } from \"client\";\nimport type { LoggerMethods } from \"managers\";\nimport { mocker } from \"mocker\";\nimport type { RequestInstance, RequestOptionsType } from \"request\";\n/* eslint-disable class-methods-use-this */\nimport type { EmptyTypes, ExtendRequest } from \"types\";\n\nimport { getAdapterOnError, getAdapterBindings } from \"./adapter.bindings\";\nimport type {\n EndpointMapper,\n AdapterFetcherType,\n AdapterPayloadMappingType,\n HeaderMappingType,\n QueryParamsMapper,\n QueryParamsType,\n RequestResponseType,\n ResponseType,\n} from \"./adapter.types\";\nimport type { getErrorMessage } from \"./adapter.utils\";\nimport { getAdapterHeaders, getAdapterPayload, RequestProcessingError } from \"./adapter.utils\";\n\nexport type DefaultMapperType = <V, C = undefined>(value: V, config?: C) => V;\nexport const defaultMapper: DefaultMapperType = (value) => value;\n\n/**\n * Base adapter class responsible for executing HTTP requests. Adapters handle endpoint resolution,\n * header/payload/query-params mapping, and the actual fetch call. Extend or configure this class\n * to integrate custom transport layers (e.g., axios, graphql, firebase).\n */\nexport class Adapter<\n AdapterOptions,\n MethodType extends string,\n StatusType extends number | string,\n Extra extends Record<string, any>,\n QueryParams = QueryParamsType | string | EmptyTypes,\n DefaultQueryParams = undefined,\n EndpointType = string,\n EndpointMapperType extends EndpointMapper<EndpointType> | DefaultMapperType = DefaultMapperType,\n QueryParamsMapperType extends QueryParamsMapper<QueryParams> | DefaultMapperType = DefaultMapperType,\n HeaderMapperType extends HeaderMappingType | DefaultMapperType = DefaultMapperType,\n PayloadMapperType extends AdapterPayloadMappingType | DefaultMapperType = DefaultMapperType,\n RequestOptions extends Record<string, any> = {},\n> {\n /** Fetching function */\n public unstable_fetcher: AdapterFetcherType<\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >;\n\n /**\n * ********************\n * Defaults\n * ********************\n */\n\n public name: string;\n public defaultMethod: MethodType;\n public defaultExtra: Extra;\n public systemErrorStatus: StatusType;\n public systemErrorExtra: Extra;\n public defaultRequestOptions?: RequestOptionsType<EndpointType, AdapterOptions, MethodType> = undefined;\n public logger: LoggerMethods;\n public initialized = false;\n public client: ClientInstance;\n\n public unstable_onInitializeCallback?: (options: { client: ClientInstance }) => void = undefined;\n\n public unstable_queryParamsMapperConfig: Parameters<QueryParamsMapperType>[1];\n public unstable_headerMapperConfig: Parameters<HeaderMapperType>[1];\n public unstable_payloadMapperConfig: Parameters<PayloadMapperType>[1];\n public unstable_endpointMapperConfig: Parameters<EndpointMapperType>[1];\n\n /**\n * Type-only carrier of the additional `createRequest` fields declared by this adapter.\n * It has no runtime value - adapters read those fields from `request.requestOptions`.\n */\n public unstable_requestOptionsType?: RequestOptions = undefined;\n\n constructor(\n public options: {\n name: string;\n defaultMethod: MethodType;\n defaultExtra: Extra;\n systemErrorStatus: StatusType;\n systemErrorExtra: Extra;\n defaultRequestOptions?: RequestOptionsType<EndpointType, AdapterOptions, MethodType>;\n },\n ) {\n this.name = options.name;\n this.defaultMethod = options.defaultMethod;\n this.defaultExtra = options.defaultExtra;\n this.systemErrorStatus = options.systemErrorStatus;\n this.systemErrorExtra = options.systemErrorExtra;\n this.defaultRequestOptions = options.defaultRequestOptions;\n }\n\n /** Initialize the adapter with a client reference and set up logging. Called automatically when the client is created. */\n initialize = (client: ClientInstance) => {\n this.logger = client.loggerManager.initialize(client, \"Adapter\");\n this.initialized = true;\n this.client = client;\n\n this.unstable_onInitializeCallback?.({ client });\n return this;\n };\n\n /** Register a callback invoked once the adapter is initialized with a client. */\n onInitialize = (callback: (options: { client: ClientInstance }) => void) => {\n this.unstable_onInitializeCallback = callback;\n return this;\n };\n\n /**\n * ********************\n * Options Setters\n * ********************\n */\n\n public unstable_internalErrorMapping: (error: ReturnType<typeof getErrorMessage>) => any = (error) => error;\n /** Method to get default headers and to map them based on the data format exchange, by default it handles FormData / JSON formats. */\n public unstable_headerMapper: HeaderMapperType = getAdapterHeaders as HeaderMapperType;\n /** Method to get request data and transform them to the required format. It handles FormData and JSON by default. */\n public unstable_payloadMapper: PayloadMapperType = getAdapterPayload as PayloadMapperType;\n /** Method to get the endpoint for the adapter request. */\n public unstable_endpointMapper: EndpointMapperType = defaultMapper as EndpointMapperType;\n /** Method to get request data and transform them to the required format. */\n public unstable_queryParamsMapper: QueryParamsMapperType = defaultMapper as QueryParamsMapperType;\n /**\n * Turns query params given as a callback into data, at the moment they are set on a request. Unset by default, so\n * adapters without it store query params as given. See {@link Adapter.setQueryParamsResolver}.\n */\n public unstable_queryParamsResolver?: (callback: (...args: any[]) => unknown) => unknown = undefined;\n /** Get default adapter options for the request. */\n public unstable_getAdapterDefaults?: (\n request: ExtendRequest<\n RequestInstance,\n {\n client: Client<\n any,\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >;\n }\n >,\n ) => AdapterOptions = undefined;\n /** Get default request options for the request. */\n public unstable_getRequestDefaults?: (\n options: RequestOptionsType<EndpointType, AdapterOptions, MethodType>,\n ) => Partial<RequestOptionsType<EndpointType, AdapterOptions, MethodType>> = undefined;\n /**\n * Get formatted endpoint name of the request.\n * Helpful in displaying long endpoints like in case of graphql schemas etc.\n */\n public unstable_devtoolsEndpointGetter: (endpoint: string, requestOptions?: Record<string, any>) => string = (\n endpoint,\n ) => endpoint;\n\n /**\n * ********************\n * Methods\n * ********************\n */\n\n /** Set the default HTTP method used when a request does not specify one. */\n setDefaultMethod = (method: MethodType) => {\n this.defaultMethod = method;\n return this;\n };\n\n /** Set the default extra metadata attached to every request response (e.g., headers, status). */\n setDefaultExtra = (extra: Extra) => {\n this.defaultExtra = extra;\n return this;\n };\n\n /** Set a function that formats the endpoint string for display in devtools. */\n setDevtoolsEndpointGetter = (callback: (endpoint: string, requestOptions?: Record<string, any>) => string) => {\n this.unstable_devtoolsEndpointGetter = callback;\n return this;\n };\n\n /**\n * This method allows to configure global defaults for the request configuration like method, auth, deduplication etc.\n */\n setRequestDefaults = (callback: typeof this.unstable_getRequestDefaults): this => {\n this.unstable_getRequestDefaults = callback;\n return this;\n };\n\n /**\n * Set the adapter default options added to every sent request\n */\n setAdapterDefaults = (\n callback: (\n request: ExtendRequest<\n RequestInstance,\n {\n // No need for global error type, because we haven't sent the request yet\n client: Client<\n any,\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >;\n }\n >,\n ) => AdapterOptions,\n ): this => {\n this.unstable_getAdapterDefaults = callback;\n return this;\n };\n\n /** Set a custom mapping for internal adapter errors before they are returned in the response. */\n setInternalErrorMapping = (callback: (error: ReturnType<typeof getErrorMessage>) => any) => {\n this.unstable_internalErrorMapping = callback;\n return this;\n };\n\n /**\n * Set the custom header mapping function\n */\n setHeaderMapper = <NewMapper extends HeaderMappingType>(headerMapper: NewMapper) => {\n this.unstable_headerMapper = ((req: Parameters<NewMapper>[0]) =>\n headerMapper(req, this.unstable_headerMapperConfig as Parameters<NewMapper>[1])) as unknown as HeaderMapperType;\n return this as unknown as Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n NewMapper,\n PayloadMapperType,\n RequestOptions\n >;\n };\n\n /**\n * Set the request payload mapping function which gets triggered before request is send\n */\n setPayloadMapper = <NewMapper extends AdapterPayloadMappingType>(payloadMapper: NewMapper) => {\n this.unstable_payloadMapper = ((req: Parameters<NewMapper>[0]) =>\n payloadMapper(\n req,\n this.unstable_payloadMapperConfig as Parameters<NewMapper>[1],\n )) as unknown as PayloadMapperType;\n return this as unknown as Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n NewMapper,\n RequestOptions\n >;\n };\n\n /**\n * Set the endpoint mapping function which transforms the endpoint string before the request is sent\n */\n setEndpointMapper = <NewEndpointMapper extends EndpointMapper<EndpointType>>(endpointMapper: NewEndpointMapper) => {\n this.unstable_endpointMapper = ((endpoint: Parameters<NewEndpointMapper>[0]) =>\n endpointMapper(\n endpoint,\n this.unstable_endpointMapperConfig as Parameters<NewEndpointMapper>[1],\n )) as unknown as EndpointMapperType;\n return this as unknown as Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n NewEndpointMapper,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >;\n };\n\n /**\n * Set the query params mapping function which get triggered before request get sent\n */\n setQueryParamsMapper = <NewQueryParamsMapper extends QueryParamsMapper<QueryParams>>(\n queryParamsMapper: NewQueryParamsMapper,\n ) => {\n this.unstable_queryParamsMapper = ((queryParams: Parameters<NewQueryParamsMapper>[0]) =>\n queryParamsMapper(\n queryParams,\n this.unstable_queryParamsMapperConfig as Parameters<NewQueryParamsMapper>[1],\n )) as unknown as QueryParamsMapperType;\n return this as unknown as Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n NewQueryParamsMapper,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >;\n };\n\n /**\n * Let requests take query params as a callback. When a request gets a function as its query params (in\n * `createRequest`, `setQueryParams` or `send`), the resolver runs right away and the request stores what it returns,\n * so cache keys, query keys and `toJSON()` only ever see data. The resolver decides what the callback receives.\n *\n * Opt-in: adapters without a resolver store query params as given. Declare the callback in the adapter's query params\n * type so requests accept it.\n *\n * @example\n * // The Firebase adapter passes a constraints builder and stores the constraints it collected\n * adapter.setQueryParamsResolver((callback) => callback(createConstraints()).toJSON());\n */\n setQueryParamsResolver = (resolver: (callback: (...args: any[]) => unknown) => unknown) => {\n this.unstable_queryParamsResolver = resolver;\n return this;\n };\n\n /** Set the configuration object passed as the second argument to the query params mapper. */\n setQueryParamsMapperConfig = <NewQueryParamsMapperConfig extends Parameters<QueryParamsMapperType>[1]>(\n config: NewQueryParamsMapperConfig,\n ) => {\n this.unstable_queryParamsMapperConfig = config;\n return this;\n };\n\n /** Set the configuration object passed as the second argument to the header mapper. */\n setHeaderMapperConfig = <NewHeaderMapperConfig extends Parameters<HeaderMapperType>[1]>(\n config: NewHeaderMapperConfig,\n ) => {\n this.unstable_headerMapperConfig = config;\n return this;\n };\n\n /** Set the configuration object passed as the second argument to the endpoint mapper. */\n setEndpointMapperConfig = <NewEndpointMapperConfig extends Parameters<EndpointMapperType>[1]>(\n config: NewEndpointMapperConfig,\n ) => {\n this.unstable_endpointMapperConfig = config;\n return this;\n };\n\n /** Set the configuration object passed as the second argument to the payload mapper. */\n setPayloadMapperConfig = <NewPayloadMapperConfig extends Parameters<PayloadMapperType>[1]>(\n config: NewPayloadMapperConfig,\n ) => {\n this.unstable_payloadMapperConfig = config;\n return this;\n };\n\n /**\n * ********************\n * Fetching\n * ********************\n */\n\n /** Set the fetcher function that performs the actual network request. Must be called before any request can be executed. */\n public setFetcher(\n fetcher: AdapterFetcherType<\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >,\n ) {\n this.unstable_fetcher = fetcher.bind(this);\n return this;\n }\n\n /** Execute a request through the adapter pipeline: maps endpoint/headers/payload, runs plugins, then calls the fetcher. */\n public async fetch(\n request: ExtendRequest<\n RequestInstance,\n {\n // No need for global error type, it doesn't matter to the fetcher itself\n client: Client<\n any,\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >;\n }\n >,\n requestId: string,\n ): Promise<RequestResponseType<RequestInstance>> {\n let startTime: number | undefined;\n\n const execute = async (resolve: (value: ResponseType<any, any, any>) => void) => {\n try {\n if (!this.initialized) {\n throw new RequestProcessingError(`Adapter ${this.options.name} is not initialized`);\n }\n\n if (!this.unstable_fetcher) {\n throw new RequestProcessingError(`Fetcher for ${this.options.name} adapter is not set`);\n }\n\n this.client.triggerPlugins(\"onAdapterFetch\", {\n adapter: this,\n request,\n requestId,\n });\n\n const bindings = await getAdapterBindings<\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >({\n request,\n requestId,\n resolve,\n internalErrorMapping: this.unstable_internalErrorMapping,\n onStartTime: (time) => {\n startTime = time;\n },\n });\n\n if (request.unstable_mock && request.isMockerEnabled && request.client.isMockerEnabled) {\n return await mocker<\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >(bindings);\n }\n\n // Awaited so a rejected async fetcher lands in the catch below and resolves the request with the error\n return await this.unstable_fetcher(bindings);\n } catch (error) {\n const onError = getAdapterOnError({\n request,\n requestId,\n startTime: startTime || Date.now(),\n logger: this.logger,\n resolve,\n });\n\n return onError({\n error: this.unstable_internalErrorMapping(error as ReturnType<typeof getErrorMessage>),\n status: this.options.systemErrorStatus,\n extra: this.options.systemErrorExtra,\n });\n }\n };\n\n const promise = new Promise((resolve) => {\n execute(resolve);\n });\n\n return promise as Promise<RequestResponseType<RequestInstance>>;\n }\n}\n","export enum HttpMethods {\n GET = \"GET\",\n POST = \"POST\",\n PUT = \"PUT\",\n PATCH = \"PATCH\",\n DELETE = \"DELETE\",\n /** Safe, idempotent read with a request body (IETF draft-ietf-httpbis-safe-method-w-body). */\n QUERY = \"QUERY\",\n}\n\n/** Methods that are safe reads: routed to the fetch dispatcher and deduplicated by default. */\nexport const SAFE_HTTP_METHODS: string[] = [HttpMethods.GET, HttpMethods.QUERY];\n","import type { OptimisticInsertOptionsType } from \"./optimistic.types\";\n\n/** Erased match - a predicate or a plain value compared with the `key` field */\nexport type OptimisticMatcher = ((item: any) => boolean) | unknown;\n\n/** Selects list items: the match and the field a plain value is compared with */\nexport type OptimisticSelector = { match: OptimisticMatcher; key?: PropertyKey };\n\ntype Item = Record<PropertyKey, unknown>;\n\nconst isComparableId = (value: unknown): value is string | number =>\n typeof value === \"string\" || typeof value === \"number\";\n\n/**\n * Tells if the item is selected by the match. Plain values are compared with the `key` field of the item, numbers and\n * strings match each other the same way route params do (`\"1\"` matches `1`).\n */\nexport const isOptimisticMatch = (item: unknown, match: OptimisticMatcher, key: PropertyKey = \"id\"): boolean => {\n if (typeof match === \"function\") {\n return !!match(item);\n }\n if (item === null || typeof item !== \"object\") {\n return false;\n }\n const value = (item as Item)[key];\n if (Object.is(value, match)) {\n return true;\n }\n return isComparableId(value) && isComparableId(match) && String(value) === String(match);\n};\n\nconst assertList = (list: unknown): unknown[] => {\n if (!Array.isArray(list)) {\n throw new TypeError(\"Optimistic list helpers need an array, use .list(field) for an array inside an object\");\n }\n return list;\n};\n\nconst assertEntry = (data: unknown): Item => {\n if (data === null || typeof data !== \"object\" || Array.isArray(data)) {\n throw new TypeError(\"Optimistic increment(field, by) needs an object, use increment(match, field, by) on a list\");\n }\n return data as Item;\n};\n\nconst addToField = (item: Item, field: PropertyKey, by: number): Item => {\n const value = item[field];\n return { ...item, [field]: (typeof value === \"number\" ? value : 0) + by };\n};\n\n/**\n * Maps the matching items. The list keeps its reference when nothing matched, so unchanged data produces no write.\n */\nconst mapMatching = (list: unknown, { match, key }: OptimisticSelector, map: (item: Item) => Item): unknown[] => {\n const items = assertList(list);\n let changed = false;\n const next = items.map((item) => {\n if (!isOptimisticMatch(item, match, key)) {\n return item;\n }\n changed = true;\n return map(item as Item);\n });\n return changed ? next : items;\n};\n\nexport const patchItems = (list: unknown, selector: OptimisticSelector, fields: object): unknown[] => {\n return mapMatching(list, selector, (item) => ({ ...item, ...fields }));\n};\n\nexport const insertItem = (list: unknown, item: unknown, options?: OptimisticInsertOptionsType): unknown[] => {\n const items = assertList(list);\n const at = options?.at ?? \"end\";\n if (at === \"start\") {\n return [item, ...items];\n }\n if (at === \"end\") {\n return [...items, item];\n }\n const next = [...items];\n next.splice(at, 0, item);\n return next;\n};\n\nexport const removeItems = (list: unknown, { match, key }: OptimisticSelector): unknown[] => {\n const items = assertList(list);\n const next = items.filter((item) => !isOptimisticMatch(item, match, key));\n return next.length === items.length ? items : next;\n};\n\nexport const incrementItems = (\n list: unknown,\n selector: OptimisticSelector,\n { field, by }: { field: PropertyKey; by: number },\n): unknown[] => {\n return mapMatching(list, selector, (item) => addToField(item, field, by));\n};\n\nexport const incrementField = (data: unknown, field: PropertyKey, by: number): Item => {\n return addToField(assertEntry(data), field, by);\n};\n\n/**\n * Runs a list helper on the array held in `field`. A missing list counts as empty, the object keeps its reference when\n * the list did not change.\n */\nexport const updateListField = (data: unknown, field: PropertyKey, update: (list: unknown[]) => unknown[]): Item => {\n const entry = assertEntry(data);\n const list = entry[field] ?? [];\n const next = update(assertList(list));\n return next === list ? entry : { ...entry, [field]: next };\n};\n","/* eslint-disable max-params -- increment(match, field, by, options) is the public signature of the helper */\nimport type { RequestInstance } from \"request\";\n\nimport type {\n OptimisticFactoryType,\n OptimisticInsertOptionsType,\n OptimisticMatchOptionsType,\n OptimisticOperationCommitType,\n OptimisticOperationRollbackType,\n} from \"./optimistic.types\";\nimport type { OptimisticMatcher } from \"./optimistic.utils\";\nimport {\n incrementField,\n incrementItems,\n insertItem,\n patchItems,\n removeItems,\n updateListField,\n} from \"./optimistic.utils\";\n\n/**\n * Callbacks are stored with an erased mutation type - the mutation type is only checked where they are passed in,\n * which keeps operations of a specific mutation assignable to the erased one.\n */\ntype OptimisticOperationOptions<Data> = {\n target: RequestInstance;\n allVariants: boolean;\n update: (data: Data) => Data;\n onRollback?: OptimisticOperationRollbackType<Data, RequestInstance>;\n onCommit?: OptimisticOperationCommitType<Data, RequestInstance>;\n};\n\n/**\n * One change of one target, built with `optimistic(target)`. Core applies it before the mutation is sent, and runs its\n * `.commit()` on success or its `.rollback()` when the mutation fails, is aborted or removed from the queue.\n * Operations are immutable - `.rollback()` and `.commit()` return a new operation, so one can be reused.\n */\nexport class OptimisticOperation<Data, Mutation extends RequestInstance = RequestInstance> {\n /** @internal */\n readonly target: RequestInstance;\n /** @internal */\n readonly allVariants: boolean;\n /** @internal */\n readonly update: (data: Data) => Data;\n /** @internal */\n readonly onRollback?: OptimisticOperationRollbackType<Data, RequestInstance> = undefined;\n /** @internal */\n readonly onCommit?: OptimisticOperationCommitType<Data, RequestInstance> = undefined;\n\n constructor(options: OptimisticOperationOptions<Data>) {\n this.target = options.target;\n this.allVariants = options.allVariants;\n this.update = options.update;\n this.onRollback = options.onRollback;\n this.onCommit = options.onCommit;\n }\n\n /**\n * Undo of this change, written by hand and run by core when the mutation fails for good, is aborted or removed from\n * the queue. Rollbacks of one mutation run in reverse order of the changes. It receives\n * `{ data, previous, reason, response, request }` and returns the new data; returning nothing leaves the data as it\n * is. Build the result from `data` and use `previous` only to look old values up. Must be synchronous.\n * Without it nothing is undone locally and the target is refetched.\n */\n // Method syntax keeps the mutation type bivariant, so operations typed by a mutation fit erased requests\n rollback(callback: OptimisticOperationRollbackType<Data, Mutation>): OptimisticOperation<Data, Mutation> {\n return new OptimisticOperation({\n target: this.target,\n allVariants: this.allVariants,\n update: this.update,\n onRollback: callback as OptimisticOperationRollbackType<Data, RequestInstance>,\n onCommit: this.onCommit,\n });\n }\n\n /**\n * Runs when the mutation succeeds, before the target is refreshed. It receives `{ data, response, request }` and\n * returns the new data, for example to swap a temporary item for the one from the response. Returning nothing leaves\n * the data as it is. Must be synchronous.\n */\n commit(callback: OptimisticOperationCommitType<Data, Mutation>): OptimisticOperation<Data, Mutation> {\n return new OptimisticOperation({\n target: this.target,\n allVariants: this.allVariants,\n update: this.update,\n onRollback: this.onRollback,\n onCommit: callback as OptimisticOperationCommitType<Data, RequestInstance>,\n });\n }\n}\n\ntype ListUpdate = (list: unknown[]) => unknown[];\n\nconst createTarget = (target: RequestInstance, allVariants: boolean) => {\n const operation = (update: (data: unknown) => unknown) => {\n return new OptimisticOperation<unknown>({ target, allVariants, update });\n };\n\n const createListHelpers = (onList: (update: ListUpdate) => (data: unknown) => unknown) => ({\n patch: (match: OptimisticMatcher, fields: object, options?: OptimisticMatchOptionsType<PropertyKey>) => {\n return operation(onList((list) => patchItems(list, { match, key: options?.key }, fields)));\n },\n insert: (item: unknown, options?: OptimisticInsertOptionsType) => {\n return operation(onList((list) => insertItem(list, item, options)));\n },\n remove: (match: OptimisticMatcher, options?: OptimisticMatchOptionsType<PropertyKey>) => {\n return operation(onList((list) => removeItems(list, { match, key: options?.key })));\n },\n increment: (\n match: OptimisticMatcher,\n field: PropertyKey,\n by: number,\n options?: OptimisticMatchOptionsType<PropertyKey>,\n ) => {\n return operation(onList((list) => incrementItems(list, { match, key: options?.key }, { field, by })));\n },\n });\n\n // The target's data is the list itself\n const listHelpers = createListHelpers((update) => (data) => update(data as unknown[]));\n\n return {\n ...listHelpers,\n set: (updater: (data: unknown) => unknown) => operation(updater),\n // `increment(field, by)` changes the data, `increment(match, field, by)` the matching list items\n increment: (...args: [PropertyKey, number] | [OptimisticMatcher, PropertyKey, number, object?]) => {\n if (args.length >= 3) {\n const [match, field, by, options] = args as [OptimisticMatcher, PropertyKey, number, object?];\n return listHelpers.increment(match, field, by, options);\n }\n const [field, by] = args as [PropertyKey, number];\n return operation((data) => incrementField(data, field, by));\n },\n list: (field: PropertyKey) => {\n return createListHelpers((update) => (data) => updateListField(data, field, update));\n },\n };\n};\n\nconst optimisticFactory = (target: RequestInstance) => createTarget(target, false);\noptimisticFactory.all = (target: RequestInstance) => createTarget(target, true);\n\n/**\n * Describes an optimistic change of a cached request. Return the operations from `setOptimistic` or pass them with the\n * `optimistic` send option, core applies them, runs `.commit()` / `.rollback()` when the mutation settles and refreshes\n * the targets once the last pending mutation on them is done.\n *\n * - `optimistic(getTodos)` - the entry of this request (its params and query params)\n * - `optimistic.all(getTodos)` - every cached variant of it, whatever the query params (filters, infinite pages)\n *\n * Helpers: `set(updater)`, `patch(match, fields)`, `insert(item, { at })`, `remove(match)`,\n * `increment(field, by)` / `increment(match, field, by)` and `.list(\"field\")` for an array inside an object.\n *\n * @example\n * optimistic(getTodos)\n * .patch(params.todoId, payload)\n * .rollback(({ data, previous }) => {\n * const before = previous.find((todo) => todo.id === params.todoId);\n * return data.map((todo) => (todo.id === params.todoId && before ? before : todo));\n * });\n */\nexport const optimistic = optimisticFactory as unknown as OptimisticFactoryType;\n","/**\n * Callbacks, listeners, plugins and optimistic handlers are the code of the user running inside of the request\n * lifecycle. Their error can't break it, and it can't get lost either - it is thrown from a timer, outside of the\n * lifecycle, so it reaches the error handlers of the environment (`window.onerror`, `uncaughtException`).\n * @internal\n * @param error value thrown by the user code\n */\nexport const throwOutsideLifecycle = (error: unknown): void => {\n setTimeout(() => {\n throw error;\n });\n};\n\n/**\n * Runs the code of the user in the middle of the request lifecycle. When it throws, the lifecycle goes on\n * and the error is thrown outside of it.\n * @internal\n * @param callback code of the user to run\n * @returns `true` when the callback finished, `false` when it threw\n */\nexport const runUserCode = (callback: VoidFunction): boolean => {\n try {\n callback();\n return true;\n } catch (error) {\n throwOutsideLifecycle(error);\n return false;\n }\n};\n","import type { RequestInstance } from \"request\";\n\nexport const getUniqueRequestId = (request: Pick<RequestInstance, \"queryKey\">) => {\n return `${request.queryKey}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n","import Emitter from \"events\";\n\nimport { runUserCode } from \"./error.utils\";\n\nconst getListenName = (event: string | symbol) => `listen_${String(event)}`;\n\nexport class EventEmitter extends Emitter {\n emitCallbacks: ((event: string, data: any, isTriggeredExternally?: true) => void)[] = [];\n\n // eslint-disable-next-line @typescript-eslint/no-useless-constructor\n constructor(options?: ConstructorParameters<typeof Emitter>[0]) {\n super(options);\n }\n\n emit(type: string, data: any, isTriggeredExternally: boolean) {\n const params: [string, any, true?] = [type, data];\n\n if (isTriggeredExternally) {\n params.push(isTriggeredExternally);\n }\n\n this.emitCallbacks?.forEach((callback) => runUserCode(() => callback(...params)));\n\n // Every listener gets the event - a throwing one can't keep it from the listeners added after it\n const listeners = this.rawListeners(type);\n listeners.forEach((listener) => runUserCode(() => listener.call(this, ...params.slice(1))));\n\n return listeners.length > 0;\n }\n\n onEmit = (callback: (event: string, data: any, isTriggeredExternally?: true) => void) => {\n this.emitCallbacks?.push(callback);\n return () => {\n this.emitCallbacks = this.emitCallbacks?.filter((cb) => cb !== callback);\n };\n };\n\n onListener = (event: string, listener: (count: number) => void) => {\n super.on(getListenName(event), listener);\n return () => {\n super.off(getListenName(event), listener);\n };\n };\n\n on = (event: string | symbol, listener: (...args: any[]) => void) => {\n super.on(event, listener);\n super.emit(getListenName(event), super.listeners(event).length);\n return this;\n };\n\n off = (event: string | symbol, listener: (...args: any[]) => void) => {\n super.off(event, listener);\n super.emit(getListenName(event), super.listeners(event).length);\n return this;\n };\n\n addListener = this.on;\n removeListener = this.off;\n}\n","import type { AdapterInstance, ResponseSuccessType, ResponseType } from \"adapter\";\nimport type { CacheValueType } from \"cache\";\nimport type { ClientInstance } from \"client\";\nimport type {\n OptimisticCallbackResult,\n OptimisticCallbackReturnType,\n OptimisticRollbackArgs,\n RequestInstance,\n} from \"request\";\nimport { getRequestKey, scopeKey, stringifyKey } from \"request\";\nimport { throwOutsideLifecycle } from \"utils\";\n\nimport { OptimisticOperation } from \"./optimistic\";\n\n/**\n * Settlement of optimistic updates.\n *\n * Every cache key changed by pending mutations has a counter. While it is above zero, fetch responses for the key are\n * not written to the cache, and fetches still running when a mutation on the key settles are marked as stale - they\n * started before the change was confirmed or reverted. Once the last mutation settles and the stale fetches are done,\n * the key is refreshed (invalidated) once, so the server's data replaces the optimistic value.\n */\n\ntype KeyState = {\n /** Mutations still pending on the key */\n pending: number;\n /** A settled mutation asked for the refresh */\n refresh: boolean;\n /** Request used to invalidate the key */\n request: RequestInstance;\n};\n\ntype ClientState = {\n keys: Map<string, KeyState>;\n /** Running fetches that started before a mutation on their key settled - request id to storage key */\n staleRequests: Map<string, string>;\n};\n\ntype AppliedOperation = {\n operation: OptimisticOperation<unknown, RequestInstance>;\n storageKey: string;\n /** Request of the changed entry */\n request: RequestInstance;\n previous: unknown;\n};\n\n/** @internal State of one mutation's optimistic updates, from applying them until the mutation settles */\nexport type OptimisticPendingType = {\n client: ClientInstance;\n result: OptimisticCallbackResult<unknown>;\n applied: AppliedOperation[];\n /** Every key the operations target, with the request used to refresh it */\n targets: Map<string, RequestInstance>;\n /** Keys changed by the operations - their fetch responses are held back until the mutation settles */\n guarded: Set<string>;\n /** Keys where user code failed - refreshed whatever the outcome */\n failed: Set<string>;\n};\n\n/** @internal How the mutation settled */\nexport type OptimisticOutcomeType =\n | { type: \"success\"; response: ResponseType<any, any, AdapterInstance>; request: RequestInstance }\n | ({ type: \"rollback\" } & OptimisticRollbackArgs<RequestInstance>);\n\nconst clientStates = new WeakMap<ClientInstance, ClientState>();\n\nconst getClientState = (client: ClientInstance): ClientState => {\n let state = clientStates.get(client);\n if (!state) {\n state = { keys: new Map(), staleRequests: new Map() };\n clientStates.set(client, state);\n }\n return state;\n};\n\n/**\n * Failures of user code (helpers, commits, rollbacks, predicates) are logged and thrown outside of the request\n * lifecycle, like every other user code running in it - the request and the other changes still settle.\n */\nconst reportFailure = (client: ClientInstance, title: string, extra: { error: unknown } & Record<string, unknown>) => {\n client.logger.error({ title, type: \"system\", extra });\n throwOutsideLifecycle(extra.error);\n};\n\nconst readEntry = (client: ClientInstance, storageKey: string) => {\n return client.cache.get<unknown, unknown>(storageKey);\n};\n\n/**\n * Writes the data through the regular cache path, so listeners get one event per change. The entry keeps its\n * timestamps and staleness - an optimistic value doesn't make the entry fresh.\n */\nconst writeData = (request: RequestInstance, entry: CacheValueType<unknown, unknown, AdapterInstance>, data: unknown) => {\n const entryRequest = request.clone({ staleTime: entry.staleTime, cacheTime: entry.cacheTime }) as RequestInstance;\n request.client.cache.set(entryRequest, { ...entry, data });\n};\n\n/**\n * Cache keys targeted by the operation. `optimistic.all()` matches every entry of the same method and endpoint\n * whatever the query params; a custom cache key matches itself and the keys derived from it (infinite pages).\n */\nconst resolveTargets = (client: ClientInstance, operation: OptimisticOperation<unknown, RequestInstance>) => {\n const { target } = operation;\n const targets = new Map<string, RequestInstance>();\n\n if (!operation.allVariants) {\n targets.set(scopeKey(target.cacheKey, target.scope), target);\n return targets;\n }\n\n const isGeneratedKey = target.cacheKey === getRequestKey(target);\n const prefix = isGeneratedKey\n ? `${stringifyKey(target.method)}_${stringifyKey(target.endpoint)}_`\n : `${target.cacheKey}_`;\n\n client.cache.keys().forEach((storageKey) => {\n const entry = client.cache.storage.get<unknown, unknown, AdapterInstance>(storageKey);\n if (!entry || entry.scope !== target.scope) {\n return;\n }\n if (entry.cacheKey === target.cacheKey) {\n targets.set(storageKey, target);\n } else if (entry.cacheKey.startsWith(prefix)) {\n // `setCacheKey` marks the instance it is called on - a clone keeps the user's request untouched\n targets.set(storageKey, target.clone().setCacheKey(entry.cacheKey) as RequestInstance);\n }\n });\n\n return targets;\n};\n\n/**\n * Runs `.rollback()` / `.commit()` of an operation and writes what it returned. User code can't break the settlement:\n * a throw or a promise is reported and the key gets refreshed.\n */\nconst runSettleCallback = (\n pending: OptimisticPendingType,\n { operation, storageKey, request, previous }: AppliedOperation,\n outcome: OptimisticOutcomeType,\n) => {\n const { client } = pending;\n const entry = readEntry(client, storageKey);\n const isCommit = outcome.type === \"success\";\n const title = isCommit ? \"Optimistic commit failed\" : \"Optimistic rollback failed\";\n const run = (data: unknown) => {\n if (outcome.type === \"success\") {\n const response = outcome.response as ResponseSuccessType<unknown, AdapterInstance>;\n return operation.onCommit?.({ data, response, request: outcome.request });\n }\n const { type: _type, ...args } = outcome;\n return operation.onRollback?.({ ...args, data, previous });\n };\n\n // Entry deleted or cache cleared in the meantime - there is nothing to update\n if (!(isCommit ? operation.onCommit : operation.onRollback) || !entry) {\n return;\n }\n\n try {\n const next = run(entry.data);\n\n if (next instanceof Promise) {\n next.catch((error: unknown) => reportFailure(client, title, { error, storageKey }));\n throw new TypeError(\"Optimistic rollback and commit must be synchronous, the returned promise was ignored\");\n }\n if (next !== undefined && next !== entry.data) {\n writeData(request, entry, next);\n }\n } catch (error) {\n reportFailure(client, title, { error, storageKey, request: outcome.request });\n pending.failed.add(storageKey);\n }\n};\n\n/** Rollback of the hand-written object form - runs once, its failure can't affect the request */\nconst runObjectRollback = (pending: OptimisticPendingType, args: OptimisticRollbackArgs<RequestInstance>) => {\n const { client, result } = pending;\n const onFailure = (error: unknown) => {\n reportFailure(client, \"Optimistic rollback failed\", { error, reason: args.reason, request: args.request });\n };\n\n try {\n // Async rollback is not awaited, but its rejection can't stay unhandled\n Promise.resolve(result.rollback?.(args)).catch(onFailure);\n } catch (error) {\n onFailure(error);\n }\n};\n\nconst runObjectInvalidation = ({ client, result }: OptimisticPendingType, request: RequestInstance) => {\n result.invalidate?.forEach((target) => {\n try {\n client.cache.invalidate(target);\n } catch (error) {\n reportFailure(client, \"Optimistic invalidation failed\", { error, target, request });\n }\n });\n};\n\n/**\n * `rollbackOnError` decides about final errors only - aborted and removed requests are always reverted.\n * A predicate that throws is reported and the change is reverted.\n */\nconst shouldRollback = (pending: OptimisticPendingType, outcome: OptimisticRollbackArgs<RequestInstance>) => {\n const { rollbackOnError } = pending.result;\n if (outcome.reason !== \"error\" || rollbackOnError === undefined || rollbackOnError === true) {\n return true;\n }\n if (rollbackOnError === false) {\n return false;\n }\n try {\n return !!rollbackOnError({ response: outcome.response, request: outcome.request });\n } catch (error) {\n reportFailure(pending.client, \"Optimistic rollbackOnError failed\", { error, request: outcome.request });\n return true;\n }\n};\n\nconst getRunningRequestsOnKey = (client: ClientInstance, storageKey: string) => {\n return [...client.fetchDispatcher.getAllRunningRequests(), ...client.submitDispatcher.getAllRunningRequests()].filter(\n ({ request }) => scopeKey(request.cacheKey, request.scope) === storageKey,\n );\n};\n\nconst hasStaleRequests = (state: ClientState, storageKey: string) => {\n return [...state.staleRequests.values()].includes(storageKey);\n};\n\n/** Refreshes the key once nothing pending or stale is left on it */\nconst refreshWhenIdle = (client: ClientInstance, state: ClientState, storageKey: string) => {\n const keyState = state.keys.get(storageKey);\n if (!keyState || keyState.pending > 0 || hasStaleRequests(state, storageKey)) {\n return;\n }\n state.keys.delete(storageKey);\n if (keyState.refresh) {\n client.cache.invalidate(keyState.request);\n }\n};\n\nconst release = (pending: OptimisticPendingType, refresh: boolean) => {\n const { client, targets, failed, guarded } = pending;\n const state = getClientState(client);\n\n targets.forEach((request, storageKey) => {\n const keyState = state.keys.get(storageKey);\n const shouldRefresh = refresh || failed.has(storageKey);\n\n if (!guarded.has(storageKey)) {\n // Nothing was changed here - refresh together with the mutations still pending on the key, or right away\n if (keyState && shouldRefresh) {\n keyState.refresh = true;\n } else if (shouldRefresh) {\n client.cache.invalidate(request);\n }\n return;\n }\n // State was reset by clearing the client\n if (!keyState) {\n return;\n }\n keyState.pending -= 1;\n keyState.refresh = keyState.refresh || shouldRefresh;\n keyState.request = request;\n\n getRunningRequestsOnKey(client, storageKey).forEach(({ requestId }) => {\n state.staleRequests.set(requestId, storageKey);\n });\n\n refreshWhenIdle(client, state, storageKey);\n });\n};\n\n/**\n * @internal\n * Normalizes what `setOptimistic` or the `optimistic` send option returned into the object form.\n */\nexport const getOptimisticResult = (\n value: OptimisticCallbackReturnType<unknown, RequestInstance> | undefined,\n): OptimisticCallbackResult<unknown> => {\n if (Array.isArray(value)) {\n return { updates: value };\n }\n return value || {};\n};\n\n/**\n * @internal\n * Applies the operations of the mutation and registers its target keys as pending. A failing operation is reported,\n * the others still apply.\n */\nexport const applyOptimistic = (\n client: ClientInstance,\n result: OptimisticCallbackResult<unknown>,\n): OptimisticPendingType => {\n const pending: OptimisticPendingType = {\n client,\n result,\n applied: [],\n targets: new Map(),\n guarded: new Set(),\n failed: new Set(),\n };\n const state = getClientState(client);\n\n result.updates?.forEach((value) => {\n try {\n if (!(value instanceof OptimisticOperation)) {\n throw new TypeError(\"Optimistic updates accept operations created with optimistic()\");\n }\n const operation = value as OptimisticOperation<unknown, RequestInstance>;\n\n resolveTargets(client, operation).forEach((request, storageKey) => {\n pending.targets.set(storageKey, request);\n const entry = readEntry(client, storageKey);\n // No data yet - there is nothing to change and nothing to revert\n if (!entry) {\n return;\n }\n try {\n const next = operation.update(entry.data);\n if (next !== entry.data) {\n writeData(request, entry, next);\n }\n pending.applied.push({ operation, storageKey, request, previous: entry.data });\n pending.guarded.add(storageKey);\n } catch (error) {\n reportFailure(client, \"Optimistic update failed\", { error, storageKey });\n pending.failed.add(storageKey);\n }\n });\n } catch (error) {\n reportFailure(client, \"Optimistic update failed\", { error, operation: value });\n }\n });\n\n pending.guarded.forEach((storageKey) => {\n const request = pending.targets.get(storageKey) as RequestInstance;\n const keyState = state.keys.get(storageKey) ?? { pending: 0, refresh: false, request };\n keyState.pending += 1;\n state.keys.set(storageKey, keyState);\n });\n\n return pending;\n};\n\n/**\n * @internal\n * Settles the mutation once. Success runs the commits and invalidations, a final error, abort or queue removal runs the\n * rollbacks in reverse order of application. The targets get refreshed after the last pending mutation on them.\n */\nexport const settleOptimistic = (pending: OptimisticPendingType, outcome: OptimisticOutcomeType) => {\n const { result, applied } = pending;\n const canRefresh = result.revalidate !== false;\n\n if (outcome.type === \"success\") {\n applied.forEach((operation) => runSettleCallback(pending, operation, outcome));\n runObjectInvalidation(pending, outcome.request);\n return release(pending, canRefresh);\n }\n\n const { type: _type, ...args } = outcome;\n if (!shouldRollback(pending, args)) {\n return release(pending, false);\n }\n\n // The latest change is reverted first\n for (let index = applied.length - 1; index >= 0; index -= 1) {\n runSettleCallback(pending, applied[index], outcome);\n }\n runObjectRollback(pending, args);\n return release(pending, canRefresh);\n};\n\n/**\n * @internal\n * Stale response guard, called where the dispatcher writes a response to the cache. A response is discarded when a\n * mutation changed its key and is pending, or when the fetch started before the latest such mutation settled - the\n * refresh after the mutation supplies current data. Keys that had no data when the change was applied are not\n * guarded, so a first load is never held back. Manual cache writes don't go through this check.\n */\nexport const isStaleOptimisticResponse = (\n client: ClientInstance,\n request: RequestInstance,\n requestId: string,\n): boolean => {\n const state = clientStates.get(client);\n if (!state) {\n return false;\n }\n\n const storageKey = scopeKey(request.cacheKey, request.scope);\n const isMarked = state.staleRequests.delete(requestId);\n const isPending = (state.keys.get(storageKey)?.pending ?? 0) > 0;\n if (isMarked) {\n refreshWhenIdle(client, state, storageKey);\n }\n\n return isMarked || isPending;\n};\n\n/** @internal Drops the pending state of the client, its mutations will never settle after clearing it */\nexport const resetOptimisticState = (client: ClientInstance) => {\n clientStates.delete(client);\n};\n","import { getErrorMessage } from \"adapter\";\nimport type { AdapterInstance, ProgressType, RequestResponseType, ResponseType } from \"adapter\";\nimport { SAFE_HTTP_METHODS } from \"constants/http.constants\";\nimport type { Dispatcher } from \"dispatcher\";\nimport type { RequestResponseEventType } from \"managers\";\nimport type { OptimisticPendingType } from \"optimistic\";\nimport { applyOptimistic, getOptimisticResult, optimistic, settleOptimistic } from \"optimistic\";\nimport type { ExtractAdapterType, ExtractErrorType } from \"types\";\nimport { runUserCode } from \"utils\";\n\nimport type {\n OptimisticCallbackResult,\n OptimisticSendOptionType,\n ProgressEventType,\n RequestInstance,\n RequestJSON,\n RequestSendOptionsType,\n RetryTimeFunctionType,\n} from \"./request.types\";\n\ntype MappedResponse =\n | ResponseType<any, any, AdapterInstance>\n | Promise<ResponseType<any, any, AdapterInstance>>\n | undefined;\n\n/**\n * Turns query params given as a callback into data with the adapter's resolver, so a request never stores a function.\n * Without a resolver the value is kept as given.\n */\nexport const resolveQueryParams = <T>(\n client: { adapter: Pick<AdapterInstance, \"unstable_queryParamsResolver\"> },\n queryParams: T,\n): T => {\n const resolver = client.adapter.unstable_queryParamsResolver;\n if (typeof queryParams === \"function\" && resolver) {\n return resolver(queryParams as (...args: any[]) => unknown) as T;\n }\n return queryParams;\n};\n\nexport const scopeKey = (key: string, scope: string | null): string => {\n return scope ? `${scope}__${key}` : key;\n};\n\nexport const stringifyKey = (value: unknown): string => {\n try {\n if (typeof value === \"string\") {\n return value;\n }\n if (value === undefined || value === null) {\n return \"\";\n }\n const data = JSON.stringify(value);\n if (typeof data !== \"string\") {\n throw new TypeError();\n }\n return data;\n } catch {\n return \"\";\n }\n};\n\nexport const getProgressValue = ({ loaded, total }: ProgressEventType): number => {\n if (!loaded || !total) {\n return 0;\n }\n return Number(((loaded * 100) / total).toFixed(0));\n};\n\nexport const getRequestEta = (\n startDate: Date,\n progressDate: Date,\n { total, loaded }: ProgressEventType,\n): { sizeLeft: number; timeLeft: number | null } => {\n const timeElapsed = +progressDate - +startDate || 1;\n const uploadSpeed = loaded / timeElapsed;\n const totalValue = Math.max(total, loaded);\n const sizeLeft = totalValue - loaded;\n const estimatedTimeValue = uploadSpeed ? sizeLeft / uploadSpeed : null;\n const timeLeft = totalValue === loaded ? 0 : estimatedTimeValue;\n\n return { timeLeft, sizeLeft };\n};\n\nexport const getProgressData = (\n requestStartTime: Date,\n progressDate: Date,\n progressEvent: ProgressEventType,\n): ProgressType => {\n const { total, loaded } = progressEvent;\n if (Number.isNaN(total) || Number.isNaN(loaded)) {\n return {\n progress: 0,\n timeLeft: 0,\n sizeLeft: 0,\n total: 0,\n loaded: 0,\n startTimestamp: +requestStartTime,\n };\n }\n\n const { timeLeft, sizeLeft } = getRequestEta(requestStartTime, progressDate, progressEvent);\n\n return {\n progress: getProgressValue(progressEvent),\n timeLeft,\n sizeLeft,\n total,\n loaded,\n startTimestamp: +requestStartTime,\n };\n};\n\n// Keys\nexport const getSimpleKey = (request: RequestInstance | RequestJSON<RequestInstance>): string => {\n return `${request.method}_${request.requestOptions.endpoint}_${request.cancelable}`;\n};\n\n/**\n * Cache instance for individual request that collects individual requests responses from\n * the same endpoint (they may differ base on the custom key, endpoint params etc)\n * @param request\n * @param useInitialValues\n * @returns\n */\nexport const getRequestKey = (\n request: RequestInstance | RequestJSON<RequestInstance>,\n useInitialValues?: boolean,\n): string => {\n /**\n * Below stringified values allow to match the response by method, endpoint and query params.\n * That's because we have shared endpoint, but data with queryParams '?user=1' will not match regular request without queries.\n * We want both results to be cached in separate places to not override each other.\n *\n * Values to be stringified:\n *\n * endpoint: string;\n * queryParams: string;\n * params: string;\n */\n const methodKey = stringifyKey(request.method);\n const endpointKey = useInitialValues ? request.requestOptions.endpoint : stringifyKey(request.endpoint);\n const queryParamsKey = useInitialValues ? \"\" : stringifyKey(request.queryParams);\n\n return `${methodKey}_${endpointKey}_${queryParamsKey}`;\n};\n\nexport const getRequestDispatcher = <Request extends RequestInstance>(\n request: Request,\n dispatcherType: \"auto\" | \"fetch\" | \"submit\" = \"auto\",\n): [Dispatcher<ExtractAdapterType<Request>>, isFetchDispatcher: boolean] => {\n const { fetchDispatcher, submitDispatcher } = request.client;\n const isSafeRead = SAFE_HTTP_METHODS.includes(request.method as string);\n const isFetchDispatcher = (dispatcherType === \"auto\" && isSafeRead) || dispatcherType === \"fetch\";\n const dispatcher = isFetchDispatcher ? fetchDispatcher : submitDispatcher;\n\n return [dispatcher, isFetchDispatcher];\n};\n\n/**\n * Runs the response mapper of the request. Mapper is user code running in the middle of the response handling,\n * so its failure is logged and ends up as a failed response carrying the thrown value as the `error`.\n * Failures are always delivered through a promise, so sync and async mappers fail the same way.\n * @internal\n * @param request request with the optional response mapper\n * @param response response to be mapped\n * @returns mapped response, promise of it for async and failed mappers, `undefined` when there is no mapper\n */\nexport const runResponseMapper = <Request extends RequestInstance>(\n request: Request,\n response: ResponseType<any, any, AdapterInstance>,\n): MappedResponse => {\n const getFailedResponse = (error: unknown) => {\n request.client.logger.error({\n title: \"Response mapper failed\",\n type: \"system\",\n extra: { error, request, response },\n });\n\n return { ...response, data: null, error, success: false } as ResponseType<any, any, AdapterInstance>;\n };\n\n try {\n const mapping = request.unstable_responseMapper?.(response as ResponseType<any, any, ExtractAdapterType<Request>>);\n\n return mapping instanceof Promise ? mapping.catch(getFailedResponse) : mapping;\n } catch (error) {\n return Promise.resolve(getFailedResponse(error));\n }\n};\n\nexport const mapResponseForSend = async <Request extends RequestInstance>(\n request: Request,\n response: ResponseType<any, any, AdapterInstance>,\n): Promise<RequestResponseType<Request>> => {\n const mapping = runResponseMapper(request, response);\n\n if (mapping instanceof Promise) {\n return (await mapping) as RequestResponseType<Request>;\n }\n\n return (mapping || response) as RequestResponseType<Request>;\n};\n\nexport const sendRequest = async <Request extends RequestInstance>(\n request: Request,\n options?: RequestSendOptionsType<Request>,\n): Promise<RequestResponseType<Request>> => {\n const { client } = request;\n const { requestManager } = client;\n const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);\n\n let mutationContext: OptimisticCallbackResult<any> | undefined;\n let pendingOptimistic: OptimisticPendingType | undefined;\n // The per-call option replaces the optimistic callback of the request\n const optimisticSource = (options?.optimistic ?? request.optimistic) as\n | OptimisticSendOptionType<RequestInstance>\n | undefined;\n\n if (optimisticSource) {\n try {\n const result = Array.isArray(optimisticSource)\n ? optimisticSource\n : optimisticSource({\n request,\n client: request.client,\n payload: request.payload,\n params: request.params,\n queryParams: request.queryParams,\n optimistic,\n });\n // Synchronous callbacks change the cache within the send() call, async ones once they resolve\n mutationContext = getOptimisticResult(result instanceof Promise ? await result : result);\n } catch (error) {\n return {\n data: null,\n error: new Error(\n `Optimistic callback failed: ${error instanceof Error ? error.message : error}`,\n ) as unknown as ExtractErrorType<Request>,\n status: null,\n success: false,\n extra: client.adapter.defaultExtra,\n requestTimestamp: Date.now(),\n responseTimestamp: Date.now(),\n };\n }\n pendingOptimistic = applyOptimistic(client, mutationContext);\n }\n\n return new Promise<RequestResponseType<Request>>((resolve) => {\n // The dispatcher is done with the request - removal from the queue that follows is not a separate outcome\n let isResolved = false;\n let isDelivered = false;\n let isSettled = false;\n const requestId = dispatcher.add(request);\n const queryKey = scopeKey(request.queryKey, request.scope);\n const { $hooks } = request;\n\n // Failed attempts stay in the dispatcher queue when they are going to be sent again\n const getWillBeResent = ({ response, details }: RequestResponseEventType<Request>) => {\n if (response.success || details.isCanceled) {\n return false;\n }\n // One that was taken out of the queue while it was running (cleared queue) has just given its last response\n if (!dispatcher.getRequest(queryKey, requestId)) {\n return false;\n }\n return details.willRetry || (request.offline && details.isOffline);\n };\n\n // Settlement and delivery read the same event - the mapper has to run only once per response\n const mappings = new WeakMap<RequestResponseEventType<Request>, MappedResponse>();\n const getMapping = (values: RequestResponseEventType<Request>) => {\n if (!mappings.has(values)) {\n mappings.set(values, runResponseMapper(request, values.response));\n }\n return mappings.get(values);\n };\n\n // Attached ahead of `onBeforeSent`, so listeners added there already observe the settled cache\n const unmountSettlement = pendingOptimistic\n ? requestManager.events.onResponseById<Request>(requestId, (values) => {\n const pending = pendingOptimistic as OptimisticPendingType;\n const willBeResent = getWillBeResent(values);\n\n const settle = (response: ResponseType<any, any, AdapterInstance>) => {\n if (isSettled || (!response.success && willBeResent)) {\n return;\n }\n isSettled = true;\n\n if (values.details.isCanceled) {\n settleOptimistic(pending, { type: \"rollback\", reason: \"abort\", response, request });\n } else if (response.success) {\n settleOptimistic(pending, { type: \"success\", response, request });\n } else {\n settleOptimistic(pending, { type: \"rollback\", reason: \"error\", response, request });\n }\n };\n\n const mapping = getMapping(values);\n if (mapping instanceof Promise) {\n mapping.then(settle);\n } else {\n settle(mapping || values.response);\n }\n })\n : undefined;\n\n const beforeSentData = { requestId, request, mutationContext };\n runUserCode(() => options?.onBeforeSent?.(beforeSentData));\n runUserCode(() => $hooks.__emit(\"onBeforeSent\", beforeSentData));\n\n const unmountRequestStart = requestManager.events.onRequestStartById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n runUserCode(() => options?.onRequestStart?.(enriched));\n runUserCode(() => $hooks.__emit(\"onRequestStart\", enriched));\n });\n\n const unmountResponseStart = requestManager.events.onResponseStartById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n runUserCode(() => options?.onResponseStart?.(enriched));\n runUserCode(() => $hooks.__emit(\"onResponseStart\", enriched));\n });\n\n const unmountUpload = requestManager.events.onUploadProgressById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n runUserCode(() => options?.onUploadProgress?.(enriched));\n runUserCode(() => $hooks.__emit(\"onUploadProgress\", enriched));\n });\n\n const unmountDownload = requestManager.events.onDownloadProgressById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n runUserCode(() => options?.onDownloadProgress?.(enriched));\n runUserCode(() => $hooks.__emit(\"onDownloadProgress\", enriched));\n });\n\n // Failed attempts which are retried do not reach `onResponse` - this is how they are announced\n const unmountRetry = requestManager.events.onRetryById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n runUserCode(() => options?.onRetry?.(enriched));\n runUserCode(() => $hooks.__emit(\"onRetry\", enriched));\n });\n\n // When resolved\n const unmountResponse = requestManager.events.onResponseById<Request>(requestId, (values) => {\n const { response } = values;\n const willBeResent = getWillBeResent(values);\n isResolved = !willBeResent;\n const enrichedValues = { ...values, mutationContext };\n\n const mapping = getMapping(values);\n\n const handleResponse = (success: boolean, data: ResponseType<any, any, ExtractAdapterType<Request>>) => {\n // Retries and offline postponing end with another response we need to listen for\n if (isDelivered || (!success && willBeResent)) {\n return;\n }\n isDelivered = true;\n\n runUserCode(() => options?.onResponse?.(enrichedValues));\n runUserCode(() => $hooks.__emit(\"onResponse\", enrichedValues));\n resolve(data);\n\n // Unmount Listeners\n // eslint-disable-next-line @typescript-eslint/no-use-before-define, @typescript-eslint/no-use-before-define\n umountAll();\n };\n\n // Create async await ONLY when we make a promise mapper\n if (mapping instanceof Promise) {\n (async () => {\n const responseData = await mapping;\n\n const { success } = responseData;\n handleResponse(success, responseData as ResponseType<any, any, ExtractAdapterType<Request>>);\n })();\n }\n // For sync mapping operations we should not use async actions\n else {\n const data = mapping || response;\n const { success } = data;\n handleResponse(success, data);\n }\n });\n\n // When removed from queue storage we need to clean event listeners and return proper error\n const unmountRemoveQueueElement = requestManager.events.onRemoveById<Request>(requestId, (data) => {\n if (!isResolved) {\n isResolved = true;\n isDelivered = true;\n\n if (pendingOptimistic && !isSettled) {\n isSettled = true;\n settleOptimistic(pendingOptimistic, { type: \"rollback\", reason: \"removed\", request });\n }\n\n const enriched = { ...data, mutationContext };\n runUserCode(() => options?.onRemove?.(enriched));\n runUserCode(() => $hooks.__emit(\"onRemove\", enriched));\n resolve({\n data: null,\n status: null,\n success: false,\n error: getErrorMessage(\"deleted\") as unknown as ExtractErrorType<Request>,\n extra: request.client.adapter.defaultExtra,\n requestTimestamp: Date.now(),\n responseTimestamp: Date.now(),\n });\n\n // Unmount Listeners\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n umountAll();\n }\n });\n\n function umountAll() {\n unmountSettlement?.();\n unmountRequestStart();\n unmountResponseStart();\n unmountUpload();\n unmountDownload();\n unmountRetry();\n unmountResponse();\n unmountRemoveQueueElement();\n }\n });\n};\n\n/** Above this exponent `min * 2 ** attempt` is past any sane maximum, and a larger one only risks Infinity */\nconst MAX_BACKOFF_EXPONENT = 30;\n\n/**\n * Retry time that grows exponentially with every attempt: `min * 2 ** attempt`, never above `max`. With `jitter` (the\n * default) the delay is a random value from `min` up to that window, so the clients that failed together do not all\n * retry at the same moment.\n *\n * @example\n * client.createRequest()({ endpoint: \"/users\", retry: 5, retryTime: exponentialBackoff({ min: 500, max: 10_000 }) });\n */\nexport const exponentialBackoff = ({\n min = 500,\n max = 30_000,\n jitter = true,\n random = Math.random,\n}: {\n /** Delay of the first retry in milliseconds. @default 500 */\n min?: number;\n /** Longest delay in milliseconds. @default 30000 */\n max?: number;\n /** Spread the delays randomly between `min` and the exponential window. @default true */\n jitter?: boolean;\n /** Source of the randomness, for deterministic tests. @default Math.random */\n random?: () => number;\n} = {}): RetryTimeFunctionType => {\n return ({ attempt }) => {\n const floor = Math.max(0, min);\n const exponent = Math.min(Math.max(0, attempt), MAX_BACKOFF_EXPONENT);\n const exponential = floor * 2 ** exponent;\n\n if (!jitter) {\n return Math.min(max, exponential);\n }\n const window = Math.max(0, Math.min(max - floor, exponential));\n return Math.round(floor + random() * window);\n };\n};\n","import type { ResponseErrorType, ResponseSuccessType, ResponseType } from \"adapter\";\nimport type { ClientInstance } from \"client\";\nimport { Time } from \"constants/time.constants\";\nimport type { MockerConfigType, MockResponseType } from \"mocker\";\nimport type {\n ExtractAdapterType,\n ExtractClientAdapterType,\n ExtractClientGlobalError,\n ExtractEndpointType,\n ExtractParamsType,\n ExtractPayloadType,\n ExtractQueryParamsType,\n EmptyTypes,\n ExtractAdapterMethodType,\n ExtractAdapterOptionsType,\n HydrateDataType,\n SyncOrAsync,\n} from \"types\";\n\nimport type { RequestHooks } from \"./request.hooks\";\nimport { createRequestHooks } from \"./request.hooks\";\n/* eslint-disable max-lines */\nimport type {\n RequestSendOptionsType,\n ParamsType,\n RequestSendType,\n PayloadType,\n RequestJSON,\n RequestOptionsType,\n RetryTimeType,\n RequestConfigurationType,\n PayloadMapperType,\n RequestInstance,\n RequestMapper,\n ResponseMapper,\n ExtractUrlParams,\n RetryOnErrorCallbackType,\n OptimisticCallback,\n} from \"./request.types\";\nimport { mapResponseForSend, resolveQueryParams, sendRequest, scopeKey } from \"./request.utils\";\n\ntype ClientAdapterOptions<C extends ClientInstance> = ExtractAdapterOptionsType<ExtractClientAdapterType<C>>;\ntype ClientAdapterMethod<C extends ClientInstance> = ExtractAdapterMethodType<ExtractClientAdapterType<C>>;\ntype ClientRequestOptions<E, C extends ClientInstance> = RequestOptionsType<\n E,\n ClientAdapterOptions<C>,\n ClientAdapterMethod<C>\n>;\n\n/**\n * Request is a class that represents a request sent to the server. It contains all the necessary information to make a request, like endpoint, method, headers, data, and much more.\n * It is executed at any time via methods like `send` or `exec`.\n *\n * We can set it up with options like endpoint, method, headers and more.\n * We can choose some of advanced settings like cache, invalidation patterns, concurrency, retries and much, much more.\n *\n * @info We should not use this class directly in the standard development flow.\n * We can initialize it using the `createRequest` method on the **Client** class.\n *\n * @attention The most important thing about the request is that it keeps data in the format that can be dumped.\n * This is necessary for the persistence and different dispatcher storage types.\n * This class doesn't have any callback methods by design and communicate with dispatcher and cache by events.\n *\n * It should be serializable to JSON and deserializable back to the class.\n * Serialization should not affect the result of the request, so it's methods and functional part should be only syntax sugar for given runtime.\n */\n\nexport class Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint extends string,\n Client extends ClientInstance,\n HasPayload extends true | false = false,\n HasParams extends true | false = false,\n HasQuery extends true | false = false,\n MutationContext = undefined,\n> {\n endpoint: Endpoint;\n headers?: HeadersInit = undefined;\n auth: boolean;\n method: ClientAdapterMethod<Client>;\n params: ExtractUrlParams<Endpoint> | EmptyTypes;\n payload: PayloadType<Payload>;\n queryParams: QueryParams | EmptyTypes;\n options?: ClientAdapterOptions<Client> | undefined = undefined;\n cancelable: boolean;\n retry: number;\n retryTime: RetryTimeType;\n cacheTime: number;\n cache: boolean;\n staleTime: number;\n queued: boolean;\n offline: boolean;\n abortKey: string;\n cacheKey: string;\n queryKey: string;\n used: boolean;\n deduplicate: boolean;\n deduplicateTime: number | null;\n structuralSharing: boolean;\n scope: string | null;\n\n /**\n * Instance-level lifecycle hooks. These callbacks fire for every `send()` / `exec()` call\n * made on this request instance (and its clones), without needing to pass them to `send()` each time.\n * Useful for cross-cutting concerns like logging, analytics, or toast notifications.\n *\n * Each method registers a callback and returns an unsubscribe function.\n * Multiple listeners per hook are supported.\n */\n $hooks: RequestHooks<RequestInstance> = createRequestHooks();\n\n isMockerEnabled = false;\n\n static readonly OPTIONAL_FIELDS = [\n \"unstable_mock\",\n \"unstable_payloadMapper\",\n \"unstable_requestMapper\",\n \"unstable_responseMapper\",\n \"retryOnError\",\n \"optimistic\",\n ] as const;\n\n // The `= undefined` initializers below are load-bearing. Metro (React Native) compiles\n // class properties in loose mode, which drops field declarations that have no initializer,\n // and the SDK proxy relies on an `in` check to tell request properties apart from deeper\n // API path segments (see OPTIONAL_REQUEST_FIELDS in sdk/sdk.ts).\n unstable_mock?: {\n fn: (options: {\n request: RequestInstance;\n requestId: string;\n }) => MockResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;\n config: MockerConfigType;\n } = undefined;\n /** @internal */\n unstable_payloadMapper?: PayloadMapperType<Payload> = undefined;\n /** @internal */\n unstable_requestMapper?: RequestMapper<any, any> = undefined;\n /** @internal */\n unstable_responseMapper?: ResponseMapper<this, ResponseSuccessType<any, any> | ResponseErrorType<any, any>> =\n undefined;\n /** @internal */\n retryOnError?: RetryOnErrorCallbackType<RequestInstance> = undefined;\n /** @internal */\n optimistic?: OptimisticCallback<RequestInstance, any> = undefined;\n\n unstable_hasParams: HasParams = false as HasParams;\n unstable_hasPayload: HasPayload = false as HasPayload;\n unstable_hasQuery: HasQuery = false as HasQuery;\n unstable_hasMutationContext: MutationContext = undefined as MutationContext;\n\n private updatedAbortKey: boolean;\n private updatedCacheKey: boolean;\n private updatedQueryKey: boolean;\n\n constructor(\n readonly client: Client,\n readonly requestOptions: ClientRequestOptions<Endpoint, Client>,\n readonly initialRequestConfiguration?:\n | RequestConfigurationType<\n Payload,\n Endpoint extends string ? ExtractUrlParams<Endpoint> : never,\n QueryParams,\n Endpoint,\n ClientAdapterOptions<Client>,\n ClientAdapterMethod<Client>\n >\n | undefined,\n ) {\n const configuration: ClientRequestOptions<Endpoint, Client> = {\n ...(this.client.adapter.unstable_getRequestDefaults?.(requestOptions) as ClientRequestOptions<Endpoint, Client>),\n ...requestOptions,\n };\n const {\n endpoint,\n headers,\n auth = true,\n method = client.adapter.defaultMethod,\n options,\n cancelable = false,\n retry = 0,\n retryTime = 500,\n cacheTime = Time.MIN * 5,\n cache = true,\n staleTime = Time.MIN * 5,\n queued = false,\n offline = true,\n abortKey,\n cacheKey,\n queryKey,\n deduplicate = false,\n deduplicateTime = null,\n structuralSharing = true,\n } = configuration;\n this.endpoint = initialRequestConfiguration?.endpoint ?? endpoint;\n this.headers = initialRequestConfiguration?.headers ?? headers;\n this.auth = initialRequestConfiguration?.auth ?? auth;\n this.method = method as ExtractAdapterMethodType<ExtractClientAdapterType<Client>>;\n this.params = initialRequestConfiguration?.params;\n this.payload = initialRequestConfiguration?.payload;\n this.queryParams = resolveQueryParams(client, initialRequestConfiguration?.queryParams);\n this.options = initialRequestConfiguration?.options ?? options;\n this.cancelable = initialRequestConfiguration?.cancelable ?? cancelable;\n this.retry = initialRequestConfiguration?.retry ?? retry;\n this.retryTime = initialRequestConfiguration?.retryTime ?? retryTime;\n this.cacheTime = initialRequestConfiguration?.cacheTime ?? cacheTime;\n this.cache = initialRequestConfiguration?.cache ?? cache;\n this.staleTime = initialRequestConfiguration?.staleTime ?? staleTime;\n this.queued = initialRequestConfiguration?.queued ?? queued;\n this.offline = initialRequestConfiguration?.offline ?? offline;\n this.abortKey = initialRequestConfiguration?.abortKey ?? abortKey ?? this.client.unstable_abortKeyMapper(this);\n this.cacheKey = initialRequestConfiguration?.cacheKey ?? cacheKey ?? this.client.unstable_cacheKeyMapper(this);\n this.queryKey = initialRequestConfiguration?.queryKey ?? queryKey ?? this.client.unstable_queryKeyMapper(this);\n this.used = initialRequestConfiguration?.used ?? false;\n this.deduplicate = initialRequestConfiguration?.deduplicate ?? deduplicate;\n this.deduplicateTime = initialRequestConfiguration?.deduplicateTime ?? deduplicateTime;\n this.structuralSharing = initialRequestConfiguration?.structuralSharing ?? structuralSharing;\n this.scope = initialRequestConfiguration?.scope ?? null;\n this.updatedAbortKey = initialRequestConfiguration?.updatedAbortKey ?? false;\n this.updatedCacheKey = initialRequestConfiguration?.updatedCacheKey ?? false;\n this.updatedQueryKey = initialRequestConfiguration?.updatedQueryKey ?? false;\n }\n\n /** Set the request headers. Returns a cloned request with the new headers applied. */\n public setHeaders = (headers: HeadersInit) => {\n return this.clone({ headers });\n };\n\n /** Set whether authentication interceptors should run for this request. */\n public setAuth = (auth: boolean) => {\n return this.clone({ auth });\n };\n\n /** Set the URL path parameters (e.g., `:userId`). */\n public setParams = <P extends ExtractParamsType<this>>(params: P) => {\n return this.clone<HasPayload, P extends null ? false : true, HasQuery>({ params });\n };\n\n /** Set the request body payload. Passing `null` removes the payload set before. */\n public setPayload = <P extends Payload>(payload: P) => {\n return this.clone<P extends null ? false : true, HasParams, HasQuery>({\n payload,\n });\n };\n\n /** Set the query parameters appended to the URL. */\n public setQueryParams = (queryParams: QueryParams) => {\n return this.clone<HasPayload, HasParams, true>({ queryParams });\n };\n\n /** Set adapter-specific options (e.g., axios config, fetch init). */\n public setOptions = (options: ClientAdapterOptions<Client>) => {\n return this.clone<HasPayload, HasParams, true>({ options });\n };\n\n /**\n * Set a scope identifier for this request.\n * All keys (cache, queue, abort) are prefixed with this scope, isolating\n * the request from other scopes. In \"server\" client mode, setting a scope\n * also enables caching (which is otherwise disabled to prevent cross-request leaks).\n */\n public setScope = (scopeId: string) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n cloned.scope = scopeId;\n return cloned;\n };\n\n /** Set whether in-flight requests with the same abort key are cancelled when a new one is dispatched. */\n public setCancelable = (cancelable: boolean) => {\n return this.clone({ cancelable });\n };\n\n /** Set the number of retry attempts on failure. */\n public setRetry = (retry: ClientRequestOptions<Endpoint, Client>[\"retry\"]) => {\n return this.clone({ retry });\n };\n\n /** Set the delay in milliseconds between retry attempts, or a function that returns it for each attempt. */\n public setRetryTime = (retryTime: ClientRequestOptions<Endpoint, Client>[\"retryTime\"]) => {\n return this.clone({ retryTime });\n };\n\n /**\n * Set a callback that controls whether a failed request should be retried.\n * Called on each failed attempt before scheduling the next retry.\n * Return `true` to allow the retry, `false` to stop retrying immediately.\n */\n public setRetryOnError = (\n callback: RetryOnErrorCallbackType<\n Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>\n >,\n ) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n cloned.retryOnError = callback as RetryOnErrorCallbackType<RequestInstance>;\n return cloned;\n };\n\n /**\n * Configure optimistic update behavior for this request.\n * The callback runs before the request is sent and receives `{ request, client, payload, params, queryParams,\n * optimistic }`. A synchronous callback changes the cache within the `send()` call.\n *\n * Return an array of changes built with `optimistic()` - core applies them, runs their `.commit()` on success or\n * `.rollback()` on final failure, abort or queue removal, and refreshes the targets after the last pending mutation\n * on them. Or return an object with `updates`, `context` (available in lifecycle callbacks as `mutationContext`),\n * `rollback` (called once on failure, abort or queue removal), `invalidate` (requests invalidated on success),\n * `rollbackOnError` and `revalidate`.\n * Everything runs for every way of sending the request, not only inside of framework hooks.\n *\n * @example\n * toggleTodo.setOptimistic(({ params, payload }) => [optimistic(getTodos).patch(params.todoId, payload)]);\n */\n public setOptimistic = <Ctx = undefined>(callback: OptimisticCallback<this, Ctx>) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n cloned.optimistic = callback as OptimisticCallback<RequestInstance, any>;\n return cloned as unknown as Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint,\n Client,\n HasPayload,\n HasParams,\n HasQuery,\n Ctx\n >;\n };\n\n /** Set how long (in ms) the response remains in cache before being garbage collected. */\n public setCacheTime = (cacheTime: ClientRequestOptions<Endpoint, Client>[\"cacheTime\"]) => {\n return this.clone({ cacheTime });\n };\n\n /** Set whether this request should use the cache. */\n public setCache = (cache: ClientRequestOptions<Endpoint, Client>[\"cache\"]) => {\n return this.clone({ cache });\n };\n\n /** Set how long (in ms) cached data is considered fresh before triggering a revalidation. */\n public setStaleTime = (staleTime: ClientRequestOptions<Endpoint, Client>[\"staleTime\"]) => {\n return this.clone({ staleTime });\n };\n\n /** Set whether the request should be queued and executed sequentially rather than immediately. */\n public setQueued = (queued: boolean) => {\n return this.clone({ queued });\n };\n\n /** Override the abort key used to cancel this request. */\n public setAbortKey = (abortKey: string) => {\n return this.clone({ abortKey, updatedAbortKey: true });\n };\n\n /** Override the cache key used to store/retrieve the response. */\n public setCacheKey = (cacheKey: string) => {\n return this.clone({ cacheKey, updatedCacheKey: true });\n };\n\n /** Override the query key that identifies this request in the dispatcher queue. */\n public setQueryKey = (queryKey: string) => {\n return this.clone({ queryKey, updatedQueryKey: true });\n };\n\n /** Enable or disable request deduplication. When enabled, concurrent identical requests share a single response. */\n public setDeduplicate = (deduplicate: boolean) => {\n return this.clone({ deduplicate });\n };\n\n /** Set the time window (in ms) during which identical requests are deduplicated. */\n public setDeduplicateTime = (deduplicateTime: number) => {\n return this.clone({ deduplicateTime });\n };\n\n /** Enable or disable structural sharing - keeping references of unchanged parts of the response data in cache. */\n public setStructuralSharing = (structuralSharing: boolean) => {\n return this.clone({ structuralSharing });\n };\n\n /** Mark the request as used (prevents automatic refetching in hooks). */\n public setUsed = (used: boolean) => {\n return this.clone({ used });\n };\n\n /** Set whether the request should be stored in the offline queue when there is no network connection. */\n public setOffline = (offline: boolean) => {\n return this.clone({ offline });\n };\n\n /** Attach a mock handler to this request. When mocking is enabled, the handler is called instead of the real adapter. */\n public setMock = (\n fn: (options: {\n request: Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;\n requestId: string;\n }) => SyncOrAsync<\n MockResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>\n >,\n config: MockerConfigType = {},\n ) => {\n this.unstable_mock = { fn, config } as typeof this.unstable_mock;\n this.isMockerEnabled = true;\n return this;\n };\n\n /** Remove any attached mock handler and disable mocking for this request. */\n public clearMock = () => {\n this.unstable_mock = undefined;\n this.isMockerEnabled = false;\n return this;\n };\n\n /** Enable or disable the mocker for this request without removing the mock handler. */\n public setMockingEnabled = (isMockerEnabled: boolean) => {\n this.isMockerEnabled = isMockerEnabled;\n return this;\n };\n\n /**\n * Map data before it gets send to the server\n * @param payloadMapper\n * @returns\n */\n public setPayloadMapper = <MappedPayload extends any | Promise<any>>(\n payloadMapper: (data: Payload) => MappedPayload,\n ) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n\n cloned.unstable_payloadMapper = payloadMapper as typeof this.unstable_payloadMapper;\n\n return cloned;\n };\n\n /**\n * Map request before it gets send to the server\n * @param requestMapper mapper of the request\n * @returns new request\n */\n public setRequestMapper = <NewRequest extends RequestInstance>(requestMapper: RequestMapper<this, NewRequest>) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n\n cloned.unstable_requestMapper = requestMapper;\n\n return cloned;\n };\n\n /**\n * Map the response to the new interface\n * @param responseMapper our mapping callback\n * @returns new response\n */\n public setResponseMapper = <MappedResponse extends ResponseSuccessType<any, any> | ResponseErrorType<any, any>>(\n responseMapper?: ResponseMapper<this, MappedResponse>,\n ) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n\n cloned.unstable_responseMapper = responseMapper as typeof cloned.unstable_responseMapper;\n\n return cloned as unknown as Request<\n MappedResponse extends ResponseType<infer R, any, any> ? R : Response,\n Payload,\n QueryParams,\n MappedResponse extends ResponseType<any, infer E, any> ? E : LocalError,\n Endpoint,\n Client,\n HasPayload,\n HasParams,\n HasQuery,\n MutationContext\n >;\n };\n\n private paramsMapper = (params: ParamsType | null | undefined): Endpoint => {\n const { endpoint } = this.requestOptions;\n\n const stringEndpoint = String(endpoint);\n const names = params ? Object.keys(params) : [];\n if (!params || names.length === 0) {\n return stringEndpoint as Endpoint;\n }\n\n // Every `:` segment is replaced once, with the longest matching name. This way `:id` does not eat the beginning\n // of `:idx`, and a value is never parsed again - neither as another param nor as a replacement pattern like `$&`.\n const [start, ...segments] = stringEndpoint.split(\":\");\n const mapped = segments.map((segment) => {\n const name = names.reduce(\n (longest, current) => (segment.startsWith(current) && current.length > longest.length ? current : longest),\n \"\",\n );\n return name ? `${params[name]}${segment.slice(name.length)}` : `:${segment}`;\n });\n\n return [start, ...mapped].join(\"\") as Endpoint;\n };\n\n /** Serialize the request configuration into a plain JSON object for persistence or transfer. */\n public toJSON(): RequestJSON<this> {\n return {\n requestOptions: this.requestOptions as unknown as RequestOptionsType<\n ExtractEndpointType<this>,\n ExtractAdapterOptionsType<ExtractAdapterType<this>>,\n ExtractAdapterMethodType<ExtractAdapterType<this>>\n >,\n endpoint: this.endpoint as ExtractEndpointType<this>,\n headers: this.headers,\n auth: this.auth,\n // TODO: fix this type\n method: this.method as any,\n params: this.params as ExtractParamsType<this>,\n payload: this.payload as ExtractPayloadType<this>,\n queryParams: this.queryParams as ExtractQueryParamsType<this>,\n options: this.options,\n cancelable: this.cancelable,\n retry: this.retry,\n retryTime: this.retryTime,\n cacheTime: this.cacheTime,\n cache: this.cache,\n staleTime: this.staleTime,\n queued: this.queued,\n offline: this.offline,\n abortKey: this.abortKey,\n cacheKey: this.cacheKey,\n queryKey: this.queryKey,\n used: this.used,\n disableResponseInterceptors: this.requestOptions.disableResponseInterceptors,\n disableRequestInterceptors: this.requestOptions.disableRequestInterceptors,\n updatedAbortKey: this.updatedAbortKey,\n updatedCacheKey: this.updatedCacheKey,\n updatedQueryKey: this.updatedQueryKey,\n deduplicate: this.deduplicate,\n deduplicateTime: this.deduplicateTime,\n structuralSharing: this.structuralSharing,\n scope: this.scope,\n isMockerEnabled: this.isMockerEnabled,\n hasMock: !!this.unstable_mock,\n };\n }\n\n /** Create a new request instance with optional configuration overrides. Used internally by all setter methods. */\n public clone<\n NewData extends true | false = HasPayload,\n NewParams extends true | false = HasParams,\n NewQueryParams extends true | false = HasQuery,\n >(\n configuration?: RequestConfigurationType<\n Payload,\n (typeof this)[\"params\"],\n QueryParams,\n Endpoint,\n ClientAdapterOptions<Client>,\n ClientAdapterMethod<Client>\n >,\n ) {\n const json = this.toJSON();\n const initialRequestConfiguration: RequestConfigurationType<\n Payload,\n Endpoint extends string ? ExtractUrlParams<Endpoint> : never,\n QueryParams,\n Endpoint,\n ClientAdapterOptions<Client>,\n ClientAdapterMethod<Client>\n > = {\n ...json,\n ...configuration,\n options: configuration?.options || this.options,\n // A key given by hand is kept by all the next clones, an auto-generated one is generated again\n abortKey: configuration?.abortKey || (this.updatedAbortKey ? this.abortKey : undefined),\n cacheKey: configuration?.cacheKey || (this.updatedCacheKey ? this.cacheKey : undefined),\n queryKey: configuration?.queryKey || (this.updatedQueryKey ? this.queryKey : undefined),\n updatedAbortKey: !!configuration?.abortKey || this.updatedAbortKey,\n updatedCacheKey: !!configuration?.cacheKey || this.updatedCacheKey,\n updatedQueryKey: !!configuration?.queryKey || this.updatedQueryKey,\n endpoint: this.paramsMapper(configuration?.params || this.params),\n queryParams: configuration?.queryParams || this.queryParams,\n // Falsy payloads like `0`, `false` or an empty string are valid values, `null` removes the payload\n payload: configuration?.payload === null ? undefined : (configuration?.payload ?? this.payload),\n params: (configuration?.params || this.params) as\n | EmptyTypes\n | (Endpoint extends string ? ExtractUrlParams<Endpoint> : never),\n };\n\n const cloned = new Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint,\n Client,\n NewData,\n NewParams,\n NewQueryParams,\n MutationContext\n >(this.client, this.requestOptions, initialRequestConfiguration);\n\n // Inherit methods\n cloned.unstable_payloadMapper = this.unstable_payloadMapper;\n cloned.unstable_responseMapper = this.unstable_responseMapper as typeof cloned.unstable_responseMapper;\n cloned.unstable_requestMapper = this.unstable_requestMapper;\n cloned.retryOnError = this.retryOnError;\n\n cloned.unstable_mock = this.unstable_mock;\n cloned.isMockerEnabled = this.isMockerEnabled;\n cloned.optimistic = this.optimistic;\n cloned.$hooks = createRequestHooks(this.$hooks.__snapshot());\n\n return cloned;\n }\n\n /** Abort all in-flight requests sharing this request's abort key. */\n public abort = () => {\n const { requestManager } = this.client;\n requestManager.abortByKey(scopeKey(this.abortKey, this.scope));\n\n return this.clone();\n };\n\n /** Extract the current cache data for this request into a portable hydration payload (useful for SSR). */\n public dehydrate = (config?: {\n /** in case of using adapter without cache we can provide response to dehydrate */\n response?: ResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;\n /** override cache data */\n override?: boolean;\n }):\n | HydrateDataType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>\n | undefined => {\n const { response, override = true } = config || {};\n\n if (response) {\n return {\n override,\n cacheTime: this.cacheTime,\n staleTime: this.staleTime,\n cacheKey: this.cacheKey,\n scope: this.scope,\n timestamp: Date.now(),\n hydrated: true,\n cache: true,\n response,\n };\n }\n\n const cacheData = this.client.cache.get<Response, LocalError | ExtractClientGlobalError<Client>>(\n scopeKey(this.cacheKey, this.scope),\n );\n\n if (!cacheData) {\n return undefined;\n }\n\n return {\n override,\n cacheTime: this.cacheTime,\n staleTime: this.staleTime,\n cacheKey: this.cacheKey,\n scope: this.scope,\n timestamp: Date.now(),\n hydrated: true,\n cache: true,\n response: {\n data: cacheData.data,\n error: cacheData.error,\n status: cacheData.status,\n success: cacheData.success,\n extra: cacheData.extra,\n requestTimestamp: cacheData.requestTimestamp,\n responseTimestamp: cacheData.responseTimestamp,\n },\n };\n };\n\n /**\n * Read the response from cache data\n *\n * If it returns error and data at the same time, it means that latest request was failed\n * and we show previous data from cache together with error received from actual request\n */\n public read():\n | ResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>\n | undefined {\n const cacheData = this.client.cache.get<Response, LocalError | ExtractClientGlobalError<Client>>(\n scopeKey(this.cacheKey, this.scope),\n );\n\n if (cacheData) {\n return {\n data: cacheData.data,\n error: cacheData.error,\n status: cacheData.status,\n success: cacheData.success,\n extra: cacheData.extra,\n requestTimestamp: cacheData.requestTimestamp,\n responseTimestamp: cacheData.responseTimestamp,\n };\n }\n return undefined;\n }\n\n /**\n * Method to use the request WITHOUT adding it to cache and queues. This mean it will make simple request without queue side effects.\n * @param options\n * @disableReturns\n * @returns\n * ```tsx\n * Promise<[Data | null, Error | null, HttpStatus]>\n * ```\n */\n public exec: RequestSendType<this> = async (options?: RequestSendOptionsType<this>) => {\n const { adapter, requestManager } = this.client;\n const request = this.clone(options);\n\n const requestId = this.client.unstable_requestIdMapper(this);\n\n const scopedAbortKey = scopeKey(this.abortKey, this.scope);\n\n // Listen for aborting\n requestManager.addAbortController(scopedAbortKey, requestId);\n\n const response = await adapter.fetch(request, requestId);\n\n // Stop listening for aborting\n requestManager.removeAbortController(scopedAbortKey, requestId);\n\n // A throwing response mapper gives the error response, the same way as in `send()`\n return mapResponseForSend(request, response);\n };\n\n /**\n * Method used to perform requests with usage of cache and queues\n * @param options\n * @param requestCallback\n * @disableReturns\n * @returns\n * ```tsx\n * Promise<{ data: Data | null, error: Error | null, status: HttpStatus, ... }>\n * ```\n */\n public send: RequestSendType<this> = async (options?: RequestSendOptionsType<this>) => {\n const {\n dispatcherType: _dispatcherType,\n cachePolicy = \"network-only\",\n optimistic: _optimistic,\n ...configuration\n } = options || {};\n\n const request = this.clone(configuration) as unknown as this;\n\n const sendRequestOptions = options === undefined ? undefined : { ...options, cachePolicy: undefined };\n\n if (cachePolicy === \"network-only\") {\n return sendRequest(request, sendRequestOptions);\n }\n\n const cached = request.read();\n\n if (cachePolicy === \"cache-first\") {\n if (cached) {\n return mapResponseForSend(request, cached);\n }\n return sendRequest(request, sendRequestOptions);\n }\n\n // revalidate\n if (cached) {\n const resolved = await mapResponseForSend(request, cached);\n // Background revalidation; promise from send() already resolved with cache snapshot\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n sendRequest(request, sendRequestOptions);\n return resolved;\n }\n\n return sendRequest(request, sendRequestOptions);\n };\n\n /** Reconstruct a Request instance from a previously serialized JSON representation. */\n static fromJSON = <\n NewResponse,\n NewPayload,\n NewQueryParams,\n NewLocalError,\n NewEndpoint extends string,\n NewClient extends ClientInstance,\n NewHasPayload extends true | false = false,\n NewHasParams extends true | false = false,\n NewHasQuery extends true | false = false,\n >(\n client: NewClient,\n json: RequestJSON<\n Request<\n NewResponse,\n NewPayload,\n NewQueryParams,\n NewLocalError,\n NewEndpoint,\n NewClient,\n NewHasPayload,\n NewHasParams,\n NewHasQuery\n >\n >,\n ) => {\n return new Request<\n NewResponse,\n NewPayload,\n NewQueryParams,\n NewLocalError,\n NewEndpoint,\n NewClient,\n NewHasPayload,\n NewHasParams,\n NewHasQuery\n >(client, json.requestOptions, json);\n };\n}\n","import type { AdapterInstance, ResponseType } from \"adapter\";\nimport type {\n CacheOptionsType,\n CacheAsyncStorageType,\n CacheStorageType,\n CacheValueType,\n CacheSetState,\n RequestCacheType,\n} from \"cache\";\nimport { getCacheData, getCacheEvents, replaceEqualDeep } from \"cache\";\nimport type { ClientInstance } from \"client\";\nimport type { ResponseDetailsType, LoggerMethods } from \"managers\";\nimport type { RequestInstance } from \"request\";\nimport { Request, scopeKey } from \"request\";\nimport type { ExtractAdapterType, ExtractErrorType, ExtractResponseType } from \"types\";\nimport { EventEmitter } from \"utils\";\n\n/** Timers can't wait longer than 2^31-1 ms (~24.8 days) - a longer delay overflows and fires immediately */\nconst MAX_TIMER_DELAY = 2_147_483_647;\n\n/**\n * Cache class handles the data exchange with the dispatchers.\n *\n * @note\n * Keys used to save the values are created dynamically on the Request class\n *\n */\nexport class Cache<Adapter extends AdapterInstance> {\n public emitter = new EventEmitter();\n public events: ReturnType<typeof getCacheEvents>;\n\n public storage: CacheStorageType;\n public lazyStorage?: CacheAsyncStorageType = undefined;\n public version: string;\n public garbageCollectors = new Map<string, ReturnType<typeof setTimeout>>();\n private logger: LoggerMethods;\n private client: ClientInstance<{ adapter: Adapter }>;\n\n constructor(public options?: CacheOptionsType) {\n const { storage = new Map<string, CacheValueType>(), lazyStorage, version = \"0.0.1\" } = options ?? {};\n\n this.emitter?.setMaxListeners(1000);\n this.events = getCacheEvents(this.emitter);\n\n this.storage = storage;\n this.version = version;\n this.lazyStorage = lazyStorage;\n }\n\n /** Initialize the cache with a client reference, set up logging, and start garbage collection. */\n initialize = (client: ClientInstance<{ adapter: Adapter }>) => {\n this.client = client;\n this.logger = client.loggerManager.initialize(client, \"Cache\");\n\n // Going back from offline should re-trigger garbage collection\n client.appManager.events.onOnline(() => {\n [...this.storage.keys()].forEach(this.scheduleGarbageCollector);\n });\n\n [...this.storage.keys()].forEach(this.scheduleGarbageCollector);\n\n return this;\n };\n\n /**\n * Set the cache data to the storage\n * @param request\n * @param response\n * @returns\n */\n set = <Request extends RequestCacheType<RequestInstance>>(\n request: Request,\n response: CacheSetState<\n ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>> &\n ResponseDetailsType\n > & { hydrated?: boolean },\n ): void => {\n this.logger.debug({ title: \"Processing cache response\", type: \"system\", extra: { request, response } });\n const { cacheKey, cache, staleTime, cacheTime, scope } = request;\n const storageKey = scopeKey(cacheKey, scope);\n const previousCacheData = this.storage.get<\n ExtractResponseType<Request>,\n ExtractErrorType<Request>,\n ExtractAdapterType<Request>\n >(storageKey);\n\n // Once refresh error occurs we don't want to override already valid data in our cache with the thrown error\n // We need to check it against cache and return last valid data we have\n const processedResponse = typeof response === \"function\" ? response(previousCacheData || null) : response;\n const data = getCacheData(previousCacheData, processedResponse);\n\n // Keep references of the unchanged data parts, so deeply equal responses don't produce new objects\n if (request.structuralSharing !== false && previousCacheData) {\n data.data = replaceEqualDeep(previousCacheData.data, data.data);\n }\n\n const newCacheData: CacheValueType<any, any, ExtractAdapterType<Request>> = {\n ...data,\n scope,\n staleTime,\n version: this.version,\n cacheKey,\n cacheTime,\n cached: !!request.cache,\n };\n\n const isServerMode = this.client.mode === \"server\";\n const isCachingAllowed = cache && (!isServerMode || !!(request as any).scope);\n\n // Only success data is valid for the cache store\n if (processedResponse.success && isCachingAllowed) {\n this.logger.debug({ title: \"Saving response to cache storage\", type: \"system\", extra: { request, data } });\n this.storage.set<Response, Error, ExtractAdapterType<Request>>(storageKey, newCacheData);\n this.runLazyStorage(\"set\", storageKey, (lazyStorage) =>\n lazyStorage.set<Response, Error, ExtractAdapterType<Request>>(storageKey, newCacheData),\n );\n this.client.triggerPlugins(\"onCacheItemChange\", {\n cache: this,\n cacheKey,\n prevData: (previousCacheData || null) as CacheValueType<any, any, AdapterInstance>,\n newData: newCacheData as CacheValueType<any, any, AdapterInstance>,\n });\n\n this.scheduleGarbageCollector(storageKey);\n } else {\n // If request should not use cache - just emit response data\n this.logger.debug({ title: \"Prevented saving response to cache\", type: \"system\", extra: { request, data } });\n }\n\n this.logger.debug({ title: \"Emitting cache response\", type: \"system\", extra: { request, data } });\n this.events.emitCacheData<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>(\n newCacheData,\n );\n };\n\n /**\n * Update the cache data with partial response data. The `responseTimestamp` is set to the time of the update, so\n * the `cacheTime` and `staleTime` count from the update. Use `set` to store the data with another timestamp.\n * @param request\n * @param partialResponse\n * @returns\n */\n update = <Request extends RequestCacheType<RequestInstance>>(\n request: Request,\n partialResponse: CacheSetState<\n Partial<\n ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>> &\n ResponseDetailsType\n >\n >,\n ): void => {\n this.logger.debug({ title: \"Processing cache update\", type: \"system\", extra: { request, partialResponse } });\n const { cacheKey, scope } = request;\n const storageKey = scopeKey(cacheKey, scope);\n const cachedData = this.storage.get<\n ExtractResponseType<Request>,\n ExtractErrorType<Request>,\n ExtractAdapterType<Request>\n >(storageKey);\n\n const processedResponse =\n typeof partialResponse === \"function\" ? partialResponse(cachedData || null) : partialResponse;\n if (cachedData) {\n // The updated data is as old as the update - the cache and stale times count from now. Callbacks usually\n // spread the previous value, so its timestamp is replaced as well.\n this.set(request, { ...cachedData, ...processedResponse, responseTimestamp: Date.now() });\n }\n };\n\n /**\n * Get particular record from storage by cacheKey. It will trigger lazyStorage to emit lazy load event for reading it's data.\n * @param cacheKey\n * @returns\n */\n get = <Response, Error>(cacheKey: string): CacheValueType<Response, Error, Adapter> | undefined => {\n this.getLazyResource<Response, Error>(cacheKey);\n const cachedData = this.storage.get<Response, Error, Adapter>(cacheKey);\n\n // Data saved by another cache version is never returned - the lazy resource check above removes it\n if (cachedData && cachedData.version !== this.version) {\n return undefined;\n }\n return cachedData;\n };\n\n /**\n * Get sync storage keys, lazyStorage keys will not be included\n * @returns\n */\n keys = (): string[] => {\n const values = this.storage.keys();\n\n return [...values];\n };\n\n /**\n * Delete record from storages and trigger invalidation event\n * @param cacheKey\n */\n delete = (cacheKey: string): void => {\n this.logger.debug({ title: \"Deleting cache element\", type: \"system\", extra: { cacheKey } });\n // Removed element has nothing left to collect - pending collector would only emit the deletion once again\n clearTimeout(this.garbageCollectors.get(cacheKey));\n this.garbageCollectors.delete(cacheKey);\n\n // Listeners are subscribed with the cache key of the request, scoped elements are stored under another key\n const listenersKey = this.storage.get(cacheKey)?.cacheKey ?? cacheKey;\n this.storage.delete(cacheKey);\n this.runLazyStorage(\"delete\", cacheKey, (lazyStorage) => lazyStorage.delete(cacheKey));\n\n this.client.triggerPlugins(\"onCacheItemDelete\", {\n cache: this,\n cacheKey,\n });\n\n this.events.emitDelete(cacheKey, false, listenersKey);\n };\n\n /**\n * Invalidate cache by cacheKey or partial matching with RegExp\n * It emits invalidation event for each matching cacheKey and sets staleTime to 0 to indicate out of time cache\n * Called without arguments it invalidates every cached element.\n * @param cacheKeys - cacheKey or Request instance or RegExp for partial matching (defaults to all elements)\n */\n invalidate = (cacheKeys: string | RegExp | RequestInstance | (string | RegExp | RequestInstance)[] = /.*/) => {\n this.logger.debug({ title: \"Revalidating cache element\", type: \"system\", extra: { cacheKeys } });\n\n const onInvalidate = (key: string | RegExp | RequestInstance) => {\n const keys = [...this.storage.keys()];\n const handleInvalidation = (invalidateStorageKey: string, notifyCacheKey: string = invalidateStorageKey) => {\n const value = this.storage.get(invalidateStorageKey);\n if (value) {\n this.storage.set(invalidateStorageKey, { ...value, staleTime: 0 });\n }\n\n this.client.triggerPlugins(\"onCacheItemInvalidate\", {\n cache: this,\n cacheKey: notifyCacheKey,\n });\n\n // Listeners are subscribed with the cache key of the request, scoped elements are stored under another key.\n // The key of the element goes as the event data, so they can tell the scopes apart.\n const listenersKey =\n notifyCacheKey === invalidateStorageKey ? (value?.cacheKey ?? notifyCacheKey) : notifyCacheKey;\n this.events.emitInvalidation(invalidateStorageKey, false, listenersKey);\n };\n\n if (key instanceof Request) {\n handleInvalidation(scopeKey(key.cacheKey, key.scope), key.cacheKey);\n } else if (typeof key === \"string\") {\n handleInvalidation(key);\n } else if (keys.length > 0) {\n // Global and sticky expressions remember the position of the last match, which would skip some of the keys\n const matcher = new RegExp(key.source, key.flags.replaceAll(/[gy]/g, \"\"));\n keys.forEach((entityKey) => {\n if (matcher.test(entityKey)) {\n handleInvalidation(entityKey);\n }\n });\n }\n };\n\n if (Array.isArray(cacheKeys)) {\n cacheKeys.forEach(onInvalidate.bind(this));\n } else {\n onInvalidate.bind(this)(cacheKeys);\n }\n };\n\n /**\n * Used to receive data from lazy storage\n * @param cacheKey\n */\n getLazyResource = async <Response, Error>(\n cacheKey: string,\n ): Promise<CacheValueType<Response, Error, Adapter> | undefined> => {\n const data = await this.runLazyStorage(\"get\", cacheKey, (lazyStorage) =>\n lazyStorage.get<Response, Error, Adapter>(cacheKey),\n );\n const syncData = this.storage.get<Response, Error, Adapter>(cacheKey);\n\n // No data in lazy storage\n if (data) {\n const now = Date.now();\n const isNewestData = syncData ? syncData.responseTimestamp < data.responseTimestamp : true;\n // Storages based on JSON turn Infinity into null - such data never gets stale\n const isStaleData = data.staleTime === null ? false : data.staleTime <= now - data.responseTimestamp;\n const isValidLazyData = data.version === this.version;\n // Collectors do not survive the application restart, so outdated data has to be removed once we meet it\n const isExpiredData = this.client.appManager.isOnline && this.getTimeLeft(data, now) < 0;\n\n if (!isValidLazyData || isExpiredData) {\n this.runLazyStorage(\"delete\", cacheKey, (lazyStorage) => lazyStorage.delete(cacheKey));\n }\n if (isNewestData && !isStaleData && isValidLazyData && !isExpiredData) {\n this.storage.set<Response, Error, Adapter>(cacheKey, data);\n // Data loaded to the sync storage is collected the same way as the data set directly\n this.scheduleGarbageCollector(cacheKey);\n // Data events are emitted with the request cacheKey, which differs from the storage key for scoped requests\n this.events.emitCacheData<Response, Error, Adapter>({\n ...data,\n cacheKey: typeof data.cacheKey === \"string\" ? data.cacheKey : cacheKey,\n cached: true,\n });\n return data;\n }\n }\n\n const isValidData = syncData?.version === this.version;\n if (syncData && !isValidData) {\n this.delete(cacheKey);\n return undefined;\n }\n return syncData;\n };\n\n /**\n * Used to receive keys from lazy storage only\n */\n getLazyKeys = async () => {\n const keys = (await this.lazyStorage?.keys()) || [];\n\n return [...new Set(keys)];\n };\n\n /**\n * Used to receive deduplicated keys from both sync storage and lazy storage\n */\n getAllKeys = async () => {\n const keys = await this.lazyStorage?.keys();\n const asyncKeys = [...(keys || [])];\n const syncKeys = [...this.storage.keys()];\n\n return [...new Set([...asyncKeys, ...syncKeys])];\n };\n\n /**\n * Schedule garbage collection for given key\n * @param cacheKey\n * @returns\n */\n scheduleGarbageCollector = (cacheKey: string) => {\n // We need to make sure that all of the values will be removed, also that we have the proper data\n const cacheData = this.storage.get(cacheKey);\n\n // Clear running garbage collectors for given key\n clearTimeout(this.garbageCollectors.get(cacheKey));\n this.garbageCollectors.delete(cacheKey);\n\n // Garbage collect\n if (cacheData) {\n const timeLeft = this.getTimeLeft(cacheData, Date.now());\n // null\n if (cacheData.cacheTime === null) {\n this.logger.debug({ title: \"Cache time is null\", type: \"system\", extra: { cacheKey } });\n }\n // Infinity\n else if (timeLeft === Infinity) {\n this.logger.debug({ title: \"Cache time is Infinite\", type: \"system\", extra: { cacheKey } });\n }\n // Run garbage collector\n else if (timeLeft >= 0) {\n // Longer delays are split into parts, as timers fire immediately when the delay is too big for them\n const delay = Math.min(timeLeft, MAX_TIMER_DELAY);\n this.garbageCollectors.set(\n cacheKey,\n setTimeout(() => {\n this.garbageCollectors.delete(cacheKey);\n if (delay < timeLeft) {\n this.scheduleGarbageCollector(cacheKey);\n } else if (this.client.appManager.isOnline) {\n this.logger.info({ title: \"Garbage collecting cache data\", type: \"system\", extra: { cacheKey } });\n this.delete(cacheKey);\n }\n }, delay),\n );\n }\n // Delete if value is stale and we are online\n else if (this.client.appManager.isOnline) {\n this.logger.info({ title: \"Garbage collecting cache data\", type: \"system\", extra: { cacheKey } });\n this.delete(cacheKey);\n }\n }\n };\n\n /**\n * Time left to the garbage collection of the cache element. Returns Infinity for elements stored forever\n * and a negative value for outdated elements or elements without valid times.\n */\n private getTimeLeft = (cacheData: Pick<CacheValueType, \"cacheTime\" | \"responseTimestamp\">, now: number): number => {\n const { cacheTime, responseTimestamp } = cacheData;\n // Storages based on JSON turn Infinity into null\n if (cacheTime === null || (typeof cacheTime === \"number\" && !Number.isFinite(cacheTime))) {\n return Infinity;\n }\n const timeLeft = cacheTime + responseTimestamp - now;\n // Missing times can't be scheduled, such element is treated as outdated\n return Number.isNaN(timeLeft) ? -1 : timeLeft;\n };\n\n /**\n * Lazy storage is an external resource (IndexedDB, AsyncStorage etc.) - its failures are logged, they must not\n * break the cache flow nor end up as unhandled promise rejections.\n */\n private runLazyStorage = async <Result>(\n action: \"get\" | \"set\" | \"delete\" | \"clear\",\n cacheKey: string,\n callback: (lazyStorage: CacheAsyncStorageType) => Promise<Result>,\n ): Promise<Result | undefined> => {\n if (!this.lazyStorage) {\n return undefined;\n }\n try {\n return await callback(this.lazyStorage);\n } catch (error) {\n this.logger?.error({\n title: `Lazy storage \"${action}\" failed`,\n type: \"system\",\n extra: { cacheKey, error },\n });\n return undefined;\n }\n };\n\n /**\n * Clear cache storages - the memory and the lazy one. Data left in the lazy storage would be loaded back\n * by the next read, for example for the next user after a logout.\n */\n clear = async (): Promise<void> => {\n this.garbageCollectors.forEach((timeout) => clearTimeout(timeout));\n this.garbageCollectors.clear();\n this.storage.clear();\n\n await this.runLazyStorage(\"clear\", \"*\", async (lazyStorage) => {\n const keys = [...(await lazyStorage.keys())];\n // One element that can't be removed must not keep the others in the storage\n const results = await Promise.allSettled(keys.map((key) => lazyStorage.delete(key)));\n // The type guard keeps older compilers (docs generation) narrowing the result to the rejected one\n const failed = results.find((result): result is PromiseRejectedResult => result.status === \"rejected\");\n if (failed) {\n throw failed.reason;\n }\n });\n };\n}\n","import type { ResponseDetailsType } from \"managers\";\nimport type { RequestInstance } from \"request\";\nimport type { ExtractAdapterResolvedType } from \"types\";\n\nexport const getCacheData = <T extends RequestInstance>(\n previousResponse: ExtractAdapterResolvedType<T> | undefined,\n response: ExtractAdapterResolvedType<T> & ResponseDetailsType,\n): ExtractAdapterResolvedType<T> & ResponseDetailsType => {\n const { data, success } = response;\n\n const previousData = !success && previousResponse ? previousResponse.data : null;\n // Only missing data falls back to the previous one - falsy responses like `0`, `false` or `\"\"` are valid data\n const computedData = data ?? previousData;\n\n return { ...response, data: computedData };\n};\n\nexport const getInvalidateKey = (): string => {\n return `invalidate`;\n};\nexport const getInvalidateByKey = (key: string): string => {\n return `${key}_invalidate`;\n};\nexport const getDeleteKey = (): string => {\n return `delete`;\n};\nexport const getDeleteByKey = (key: string): string => {\n return `${key}_delete`;\n};\nexport const getCacheByKey = (key: string): string => {\n return `${key}_cache`;\n};\nexport const getCacheKey = (): string => {\n return `cache`;\n};\n\n/**\n * Check if value is a plain object (object literal or `Object.create(null)`).\n * Class instances, Dates, Maps, Blobs etc. are not plain objects.\n */\nexport const isPlainObject = (value: unknown): value is Record<string, unknown> => {\n if (Object.prototype.toString.call(value) !== \"[object Object]\") {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === null || prototype === Object.prototype;\n};\n\nconst isPlainArray = (value: unknown): value is unknown[] => {\n return Array.isArray(value) && Object.keys(value).length === value.length;\n};\n\n/**\n * Structures nested deeper than this are not compared - it keeps extremely deep data from overflowing the call stack.\n */\nconst STRUCTURAL_SHARING_MAX_DEPTH = 500;\n\n/**\n * @param ancestors containers of `next` that are being compared right now - their number is the current depth\n * and meeting one of them again means a cycle\n */\nconst shareEqualParts = <T>(prev: unknown, next: T, ancestors: Set<unknown>): T => {\n if (Object.is(prev, next)) {\n return prev as T;\n }\n\n const isArray = isPlainArray(prev) && isPlainArray(next);\n if (!isArray && !(isPlainObject(prev) && isPlainObject(next))) {\n return next;\n }\n\n // Circular and extremely deep structures are not traversed further\n if (ancestors.size > STRUCTURAL_SHARING_MAX_DEPTH || ancestors.has(next)) {\n return next;\n }\n ancestors.add(next);\n\n const prevItems = prev as Record<string, unknown>;\n const nextItems = next as Record<string, unknown>;\n const prevKeys = Object.keys(prevItems);\n const nextKeys = Object.keys(nextItems);\n const copy: Record<string, unknown> = isArray ? ([] as unknown as Record<string, unknown>) : {};\n\n let equalItems = 0;\n nextKeys.forEach((key) => {\n const prevValue = prevItems[key];\n const nextValue = nextItems[key];\n const value = shareEqualParts(prevValue, nextValue, ancestors);\n copy[key] = value;\n // undefined values are equal only when the key existed before\n // eslint-disable-next-line prefer-object-has-own -- Object.hasOwn is not available in older runtimes\n if (Object.is(value, prevValue) && (value !== undefined || Object.prototype.hasOwnProperty.call(prevItems, key))) {\n equalItems += 1;\n }\n });\n\n ancestors.delete(next);\n\n return (prevKeys.length === nextKeys.length && equalItems === prevKeys.length ? prev : copy) as T;\n};\n\n/**\n * Structural sharing - returns `next` with every part that is deeply equal to `prev` replaced by the `prev` reference.\n * When both values are deeply equal the `prev` reference is returned, so consumers can rely on `===` checks.\n * Only plain objects and arrays are traversed, other values are compared with `Object.is`.\n * Circular references and extremely deep structures are not traversed - such parts are taken from `next` as they are.\n * @param prev previous value\n * @param next incoming value\n * @returns `next` sharing unchanged references with `prev`\n */\nexport const replaceEqualDeep = <T>(prev: unknown, next: T): T => {\n return shareEqualParts(prev, next, new Set());\n};\n","import type { AdapterInstance } from \"adapter\";\nimport type { CacheValueType } from \"cache\";\nimport { getInvalidateByKey, getInvalidateKey, getCacheByKey, getCacheKey, getDeleteKey, getDeleteByKey } from \"cache\";\nimport type EventEmitter from \"events\";\n\n/** Create the cache event emitters and listeners for data changes, invalidation, and deletion. */\nexport const getCacheEvents = (emitter: EventEmitter) => ({\n /**\n * Set cache data\n * @param data\n */\n emitCacheData: <Response, Error, Adapter extends AdapterInstance>(\n data: CacheValueType<Response, Error, Adapter> & { cached: boolean },\n isTriggeredExternally = false,\n ): void => {\n emitter.emit(getCacheKey(), data, isTriggeredExternally);\n emitter.emit(getCacheByKey(data.cacheKey), data, isTriggeredExternally);\n },\n /**\n * Invalidate cache values event\n * @param cacheKey key of the invalidated element - the event data\n * @param isTriggeredExternally event comes from outside of the cache (for example from devtools)\n * @param listenersKey key the by-key listeners are subscribed with. Scoped elements are stored under\n * `scopeKey(cacheKey, scope)`, while their listeners use the `cacheKey` of the request\n */\n emitInvalidation: (cacheKey: string, isTriggeredExternally = false, listenersKey = cacheKey): void => {\n emitter.emit(getInvalidateKey(), cacheKey, isTriggeredExternally);\n // Key goes as the event data, so the external trigger flag stays at its place for the emit observers\n emitter.emit(getInvalidateByKey(listenersKey), cacheKey, isTriggeredExternally);\n },\n /**\n * Delete of cache values\n * @param cacheKey key of the deleted element - the event data\n * @param isTriggeredExternally event comes from outside of the cache (for example from devtools)\n * @param listenersKey key the by-key listeners are subscribed with. Scoped elements are stored under\n * `scopeKey(cacheKey, scope)`, while their listeners use the `cacheKey` of the request\n */\n emitDelete: (cacheKey: string, isTriggeredExternally = false, listenersKey = cacheKey): void => {\n emitter.emit(getDeleteKey(), cacheKey, isTriggeredExternally);\n // Key goes as the event data, so the external trigger flag stays at its place for the emit observers\n emitter.emit(getDeleteByKey(listenersKey), cacheKey, isTriggeredExternally);\n },\n /**\n * Cache data listener for all keys\n * @param callback\n * @returns\n */\n onData: <Response, Error, Adapter extends AdapterInstance>(\n callback: (data: CacheValueType<Response, Error, Adapter> & { cached: boolean }) => void,\n ): VoidFunction => {\n emitter.on(getCacheKey(), callback);\n return () => emitter.removeListener(getCacheKey(), callback);\n },\n /**\n * Cache data listener filtered by a specific cache key\n * @param cacheKey\n * @param callback\n * @returns\n */\n onDataByKey: <Response, Error, Adapter extends AdapterInstance>(\n cacheKey: string,\n callback: (data: CacheValueType<Response, Error, Adapter>) => void,\n ): VoidFunction => {\n emitter.on(getCacheByKey(cacheKey), callback);\n return () => emitter.removeListener(getCacheByKey(cacheKey), callback);\n },\n /**\n * Cache invalidation listener\n * @param callback\n * @returns\n */\n onInvalidate: (callback: (cacheKey: string) => void): VoidFunction => {\n emitter.on(getInvalidateKey(), callback);\n return () => emitter.removeListener(getInvalidateKey(), callback);\n },\n /**\n * Cache invalidation listener filtered by the cache key of the request.\n * Requests of every scope share that key - the callback receives the key of the invalidated element\n * (`scopeKey(cacheKey, scope)`), which tells the scopes apart.\n * @param cacheKey\n * @param callback\n * @returns\n */\n onInvalidateByKey: (cacheKey: string, callback: (invalidatedKey: string) => void): VoidFunction => {\n emitter.on(getInvalidateByKey(cacheKey), callback);\n return () => emitter.removeListener(getInvalidateByKey(cacheKey), callback);\n },\n /** Cache deletion listener for all keys */\n onDelete: (callback: (cacheKey: string) => void): VoidFunction => {\n emitter.on(getDeleteKey(), callback);\n return () => emitter.removeListener(getDeleteKey(), callback);\n },\n /**\n * Cache deletion listener filtered by the cache key of the request.\n * Requests of every scope share that key - the callback receives the key of the deleted element\n * (`scopeKey(cacheKey, scope)`), which tells the scopes apart.\n */\n onDeleteByKey: (cacheKey: string, callback: (deletedKey: string) => void): VoidFunction => {\n emitter.on(getDeleteByKey(cacheKey), callback);\n return () => emitter.removeListener(getDeleteByKey(cacheKey), callback);\n },\n});\n","export enum DispatcherMode {\n ONE_BY_ONE = \"one-by-one\",\n ALL_AT_ONCE = \"all-at-once\",\n PREVIOUS_CANCELED = \"previous-canceled\",\n DEDUPLICATED = \"deduplicated\",\n}\n","import type { QueueDataType, RunningRequestsChangeType } from \"dispatcher\";\nimport {\n getDispatcherChangeKey,\n getDispatcherChangeByKey,\n getDispatcherStatusKey,\n getDispatcherStatusByKey,\n getDispatcherDrainedKey,\n getDispatcherDrainedByKey,\n getDispatcherRunningKey,\n getDispatcherRunningByKey,\n} from \"dispatcher\";\nimport type EventEmitter from \"events\";\nimport type { RequestInstance } from \"request\";\n\nexport const getDispatcherEvents = (emitter: EventEmitter) => ({\n emitDrained: <Request extends RequestInstance>(\n values: QueueDataType<Request>,\n isTriggeredExternally?: boolean,\n ): void => {\n emitter.emit(getDispatcherDrainedKey(), values, isTriggeredExternally);\n emitter.emit(getDispatcherDrainedByKey(values.queryKey), values, isTriggeredExternally);\n },\n emitQueueStatusChanged: <Request extends RequestInstance>(\n values: QueueDataType<Request>,\n isTriggeredExternally?: boolean,\n ): void => {\n emitter.emit(getDispatcherStatusKey(), values, isTriggeredExternally);\n emitter.emit(getDispatcherStatusByKey(values.queryKey), values, isTriggeredExternally);\n },\n emitQueueChanged: <Request extends RequestInstance>(\n values: QueueDataType<Request>,\n isTriggeredExternally?: boolean,\n ): void => {\n emitter.emit(getDispatcherChangeKey(), values, isTriggeredExternally);\n emitter.emit(getDispatcherChangeByKey(values.queryKey), values, isTriggeredExternally);\n },\n emitRunningRequestsChanged: (values: RunningRequestsChangeType, isTriggeredExternally?: boolean): void => {\n emitter.emit(getDispatcherRunningKey(), values, isTriggeredExternally);\n emitter.emit(getDispatcherRunningByKey(values.queryKey), values, isTriggeredExternally);\n },\n /**\n * When queue becomes empty\n * @param callback\n * @returns\n */\n onDrained: <Request extends RequestInstance>(callback: (values: QueueDataType<Request>) => void): VoidFunction => {\n emitter.on(getDispatcherDrainedKey(), callback);\n return () => emitter.removeListener(getDispatcherDrainedKey(), callback);\n },\n /**\n * When queue becomes empty\n * @param queryKey\n * @param callback\n * @returns\n */\n onDrainedByKey: <Request extends RequestInstance>(\n queryKey: string,\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherDrainedByKey(queryKey), callback);\n return () => emitter.removeListener(getDispatcherDrainedByKey(queryKey), callback);\n },\n /**\n * When queue status change from enabled to paused or vice versa\n * @param callback\n * @returns\n */\n onQueueStatusChange: <Request extends RequestInstance>(\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherStatusKey(), callback);\n return () => emitter.removeListener(getDispatcherStatusKey(), callback);\n },\n /**\n * When queue status change from enabled to paused or vice versa\n * @param queryKey\n * @param callback\n * @returns\n */\n onQueueStatusChangeByKey: <Request extends RequestInstance>(\n queryKey: string,\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherStatusByKey(queryKey), callback);\n return () => emitter.removeListener(getDispatcherStatusByKey(queryKey), callback);\n },\n /**\n * When new elements are added or removed from the queue\n * @param queryKey\n * @param callback\n * @returns\n */\n onQueueChange: <Request extends RequestInstance>(\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherChangeKey(), callback);\n return () => emitter.removeListener(getDispatcherChangeKey(), callback);\n },\n /**\n * When new elements are added or removed from the queue\n * @param queryKey\n * @param callback\n * @returns\n */\n onQueueChangeByKey: <Request extends RequestInstance>(\n queryKey: string,\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherChangeByKey(queryKey), callback);\n return () => emitter.removeListener(getDispatcherChangeByKey(queryKey), callback);\n },\n /**\n * When requests start or stop running (sent, finished, canceled or cleared)\n * @param callback\n * @returns\n */\n onRunningRequestsChange: (callback: (values: RunningRequestsChangeType) => void): VoidFunction => {\n emitter.on(getDispatcherRunningKey(), callback);\n return () => emitter.removeListener(getDispatcherRunningKey(), callback);\n },\n /**\n * When requests start or stop running (sent, finished, canceled or cleared) for given queryKey\n * @param queryKey\n * @param callback\n * @returns\n */\n onRunningRequestsChangeByKey: (\n queryKey: string,\n callback: (values: RunningRequestsChangeType) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherRunningByKey(queryKey), callback);\n return () => emitter.removeListener(getDispatcherRunningByKey(queryKey), callback);\n },\n});\n","/* eslint-disable max-lines */\nimport type { AdapterInstance, RequestResponseType } from \"adapter\";\nimport { getErrorMessage } from \"adapter\";\nimport type { ClientInstance } from \"client\";\nimport type {\n QueueDataType,\n DispatcherAsyncStorageType,\n DispatcherOptionsType,\n DispatcherStorageType,\n ResolvedQueueDataType,\n ResolvedQueueItemType,\n RunningRequestValueType,\n} from \"dispatcher\";\nimport { getRequestType, canRetryRequest, getDispatcherEvents, DispatcherMode } from \"dispatcher\";\nimport type { ResponseDetailsType, LoggerMethods } from \"managers\";\nimport { isStaleOptimisticResponse } from \"optimistic\";\nimport type { RequestInstance, RequestJSON } from \"request\";\nimport { Request, scopeKey } from \"request\";\nimport { EventEmitter, throwOutsideLifecycle } from \"utils\";\n\n/**\n * Dispatcher controls and manages the requests that are going to be executed with adapter. It manages them based on the options provided with request.\n * This class can also run them with different modes like deduplication, cancelation, queueing or run-all-at-once mode. With it's help we can pause,\n * stop, start and cancel requests.\n */\nexport class Dispatcher<Adapter extends AdapterInstance> {\n public emitter = new EventEmitter();\n public events = getDispatcherEvents(this.emitter);\n public storage: DispatcherStorageType = new Map<string, QueueDataType<any>>();\n\n private requestCount = new Map<string, number>();\n private runningRequests = new Map<string, RunningRequestValueType[]>();\n /** Failed requests waiting for their next attempt, by requestId */\n private retryTimers = new Map<string, ReturnType<typeof setTimeout>>();\n /** Requests which got their response and are still in the queue while their listeners run */\n private answeredRequests = new Set<string>();\n /** Order in which the requests were sent - responses can come back in another one */\n private sentCount = 0;\n /** Cache element (by its storage key) to the order number of the request whose data it holds */\n private cachedOrder = new Map<string, number>();\n\n /** Sends the queue restored from the storage once the client is configured */\n private startTimer: ReturnType<typeof setTimeout> | undefined;\n /** Operations of the lazy storage run one after another, so it always ends with the latest state of the queues */\n private lazyOperations: Promise<void> = Promise.resolve();\n\n private logger: LoggerMethods;\n private client: ClientInstance<{ adapter: Adapter }>;\n\n constructor(public options?: DispatcherOptionsType) {\n this.emitter?.setMaxListeners(1000);\n\n if (this.options?.storage) {\n this.storage = this.options.storage;\n }\n if (this.options?.lazyStorage) {\n this.storage = this.withLazyStorage(this.storage, this.options.lazyStorage);\n }\n }\n\n // *********************************************************************\n // *********************************************************************\n // Lazy storage\n // *********************************************************************\n // *********************************************************************\n\n /**\n * Lazy storage is an external resource - its failures are logged, they must not take the requests down\n */\n private runLazyOperation = (action: string, queryKey: string | null, operation: () => Promise<void> | void) => {\n this.lazyOperations = this.lazyOperations.then(async () => {\n try {\n await operation();\n } catch (error) {\n this.logger?.error({ title: `Lazy storage \"${action}\" failed`, type: \"system\", extra: { queryKey, error } });\n }\n });\n };\n\n /**\n * Snapshot of the queue as JSON data - taken right away, as the queue objects change after the write is scheduled\n */\n private getLazyQueueData = (queue: QueueDataType): QueueDataType => {\n return JSON.parse(\n JSON.stringify({\n ...queue,\n requests: queue.requests.map((item) => ({\n ...item,\n request: this.isRequestJSON(item.request) ? item.request : item.request.toJSON(),\n })),\n }),\n );\n };\n\n /**\n * The sync storage stays the source of truth, its changes are written through to the lazy storage\n */\n private withLazyStorage = (\n storage: DispatcherStorageType,\n lazyStorage: DispatcherAsyncStorageType,\n ): DispatcherStorageType => ({\n get: (key) => storage.get(key),\n keys: () => storage.keys(),\n entries: () => storage.entries(),\n set: (key, data) => {\n storage.set(key, data);\n const snapshot = this.getLazyQueueData(data as QueueDataType);\n this.runLazyOperation(\"set\", key, () => lazyStorage.set(key, snapshot));\n },\n delete: (key) => {\n storage.delete(key);\n this.runLazyOperation(\"delete\", key, () => lazyStorage.delete(key));\n },\n clear: () => {\n storage.clear();\n this.runLazyOperation(\"clear\", null, async () => {\n const keys = [...(await lazyStorage.keys())];\n await Promise.all(keys.map((key) => lazyStorage.delete(key)));\n });\n },\n });\n\n /**\n * Reads the queues persisted by the previous run. Persisted requests are older than the ones added since the start,\n * so they go first. Requests already in the queue are not added twice.\n */\n private restoreLazyQueues = (lazyStorage: DispatcherAsyncStorageType) => {\n this.runLazyOperation(\"restore\", null, async () => {\n const keys = [...(await lazyStorage.keys())];\n const persistedQueues = await Promise.all(keys.map(async (key) => [key, await lazyStorage.get(key)] as const));\n\n persistedQueues.forEach(([queryKey, persisted]) => {\n if (!persisted?.requests.length) {\n return;\n }\n const queue = this.getQueue(queryKey);\n const knownIds = new Set(queue.requests.map((item) => item.requestId));\n const restored = persisted.requests\n .filter((item) => !knownIds.has(item.requestId))\n .map((item) => ({\n ...item,\n request: this.isRequestJSON(item.request) ? this.client.fromJSON(item.request) : item.request,\n }));\n\n if (restored.length) {\n this.setQueue(queryKey, { ...queue, requests: [...restored, ...queue.requests] });\n this.flushQueue(queryKey);\n }\n });\n });\n };\n\n // eslint-disable-next-line class-methods-use-this\n private isRequestJSON = (\n request: RequestInstance | RequestJSON<RequestInstance>,\n ): request is RequestJSON<RequestInstance> => {\n return !(request instanceof Request);\n };\n\n initialize = (client: ClientInstance<{ adapter: Adapter }>) => {\n this.client = client;\n this.logger = client.loggerManager.initialize(client, \"Dispatcher\");\n\n // Going back from offline should re-trigger all requests\n this.client.appManager.events.onOnline(() => {\n this.flush();\n });\n\n // A queue restored from a persistent storage (e.g. the requests left by the previous page load) has to be sent\n // on start. It waits for the next task, so the configuration chained after the client constructor - adapter,\n // interceptors, plugins - applies to the restored requests too.\n if (this.options?.lazyStorage) {\n this.restoreLazyQueues(this.options.lazyStorage);\n }\n\n clearTimeout(this.startTimer);\n if (this.getQueuesKeys().length) {\n this.startTimer = setTimeout(() => {\n this.startTimer = undefined;\n this.flush();\n });\n }\n\n return this;\n };\n\n // *********************************************************************\n // *********************************************************************\n // Queue\n // *********************************************************************\n // *********************************************************************\n\n /**\n * Start request handling by queryKey\n */\n start = (queryKey: string) => {\n // Change status to running\n const queue = this.getQueue(queryKey);\n\n // Start the queue when its stopped\n queue.stopped = false;\n this.setQueue(queryKey, queue);\n this.flushQueue(queryKey);\n this.client.triggerPlugins(\"onDispatcherQueueRunning\", { dispatcher: this, queue, status: \"running\" });\n this.events.emitQueueStatusChanged(queue);\n };\n\n /**\n * Pause request queue, but do not cancel already started requests\n */\n pause = (queryKey: string) => {\n // Change state to stopped\n const queue = this.getQueue(queryKey);\n\n queue.stopped = true;\n this.setQueue(queryKey, queue);\n this.client.triggerPlugins(\"onDispatcherQueueRunning\", { dispatcher: this, queue, status: \"paused\" });\n this.events.emitQueueStatusChanged(queue);\n };\n\n /**\n * Stop request queue and cancel all started requests - those will be treated like not started\n */\n stop = (queryKey: string) => {\n // Change state to stopped\n const queue = this.getQueue(queryKey);\n\n queue.stopped = true;\n this.setQueue(queryKey, queue);\n\n // Cancel running requests\n this.cancelRunningRequests(queryKey);\n this.client.triggerPlugins(\"onDispatcherQueueRunning\", { dispatcher: this, queue, status: \"stopped\" });\n this.events.emitQueueStatusChanged(queue);\n };\n\n /**\n * Return all queue keys currently tracked by the dispatcher storage\n */\n getQueuesKeys = () => {\n return [...this.storage.keys()];\n };\n\n /**\n * Return queue state object.\n * Automatically reconstructs any serialized (JSON) requests back into\n * proper Request class instances so the rest of the pipeline can rely on\n * having a real `RequestInstance`.\n */\n getQueue = <R extends RequestInstance = RequestInstance>(queryKey: string): ResolvedQueueDataType<R> => {\n const initialQueueState: ResolvedQueueDataType<R> = { queryKey, requests: [], stopped: false };\n const storedEntity = this.storage.get<R>(queryKey);\n\n if (!storedEntity) {\n return initialQueueState;\n }\n\n const resolvedRequests: ResolvedQueueItemType<R>[] = storedEntity.requests.map((item) => {\n if (this.isRequestJSON(item.request)) {\n return { ...item, request: this.client.fromJSON(item.request as RequestJSON<RequestInstance>) as unknown as R };\n }\n return item as ResolvedQueueItemType<R>;\n });\n\n return { ...storedEntity, requests: resolvedRequests };\n };\n\n /**\n * Return request from queue state\n */\n getRequest = <Request extends RequestInstance = RequestInstance>(queryKey: string, requestId: string) => {\n const initialQueueState: QueueDataType<Request> = { queryKey, requests: [], stopped: false };\n const storedEntity = this.storage.get<Request>(queryKey) || initialQueueState;\n\n return storedEntity.requests.find((req) => req.requestId === requestId);\n };\n\n /**\n * Get value of the active queue status based on the stopped status\n */\n getIsActiveQueue = (queryKey: string) => {\n const queue = this.getQueue(queryKey);\n const hasAvailableRequests = queue.requests.some((req) => !req.stopped);\n const isRunningQueue = !queue.stopped;\n return hasAvailableRequests && isRunningQueue;\n };\n\n /**\n * Add new element to storage\n */\n addQueueItem = <Request extends RequestInstance = RequestInstance>(\n queryKey: string,\n element: ResolvedQueueItemType<Request>,\n ) => {\n const queue = this.getQueue<Request>(queryKey);\n queue.requests.push(element);\n\n this.client.triggerPlugins(\"onDispatcherItemAdded\", { dispatcher: this, queue, queueItem: element });\n\n this.setQueue<Request>(queryKey, queue);\n };\n\n /**\n * Set new queue storage value\n */\n setQueue = <Request extends RequestInstance = RequestInstance>(\n queryKey: string,\n queue: ResolvedQueueDataType<Request>,\n ) => {\n this.storage.set<Request>(queryKey, queue as QueueDataType<Request>);\n\n // Emit Queue Changes\n this.client.triggerPlugins(\"onDispatcherQueueCreated\", { dispatcher: this, queue });\n this.events.emitQueueChanged(queue);\n\n return queue;\n };\n\n /**\n * Clear requests from queue cache\n */\n clearQueue = (queryKey: string) => {\n return this.removeQueueItems(\n queryKey,\n this.getRunningRequests(queryKey).map((running) => running.requestId),\n );\n };\n\n /**\n * Empty the queue. Requests listed in `answeredIds` are running or were just canceled, so they still report\n * their own response. All the others would never be heard of again - those are reported as removed.\n */\n private removeQueueItems = (queryKey: string, answeredIds: string[]) => {\n const queue = this.getQueue(queryKey);\n const newQueue = { queryKey, requests: [], stopped: queue.stopped };\n this.storage.set(queryKey, newQueue);\n\n // Emit Queue Changes\n this.client.triggerPlugins(\"onDispatcherQueueCleared\", { dispatcher: this, queue: newQueue });\n this.events.emitQueueChanged(newQueue);\n this.emitRemovedItems(queue.requests, answeredIds);\n this.events.emitDrained(newQueue);\n\n return newQueue;\n };\n\n private emitRemovedItems = (items: ResolvedQueueItemType[], answeredIds: string[]) => {\n items.forEach((item) => {\n this.cancelRetry(item.requestId);\n\n if (!answeredIds.includes(item.requestId)) {\n this.client.requestManager.events.emitRemove({\n requestId: item.requestId,\n request: item.request,\n resolved: item.resolved,\n });\n }\n });\n };\n\n /**\n * A request can be sent when it is not in flight, not held by `stopRequest`, not waiting for its retry,\n * not just answered and - for the requests kept for later with the `offline` option - when there is a connection.\n * Nothing is sent while the page unloads - the browser would cancel it right away.\n */\n private canPerformRequest = (item: ResolvedQueueItemType, runningIds: Set<string>) => {\n const isWaitingForNetwork = !this.client.appManager.isOnline && item.request.offline;\n\n return (\n !this.client.appManager.isUnloading &&\n !item.stopped &&\n !isWaitingForNetwork &&\n !this.retryTimers.has(item.requestId) &&\n !this.answeredRequests.has(item.requestId) &&\n !runningIds.has(item.requestId)\n );\n };\n\n /**\n * Method used to flush the queue requests\n */\n flushQueue = async (queryKey: string) => {\n const queue = this.getQueue(queryKey);\n const runningRequests = this.getRunningRequests(queryKey);\n const queueItem = queue.requests.find((request) => !request.stopped);\n\n const isStopped = queue && queue.stopped;\n const isOffline = !this.client.appManager.isOnline;\n const isConcurrent = !queueItem?.request.queued;\n const isInactive = runningRequests.length === 0;\n const isEmpty = !queueItem;\n\n // When there are no requests to flush, when its stopped, there is running request\n // or there is no request to trigger - we don't want to perform actions\n if (isStopped || isEmpty) {\n this.logger.debug({ title: \"Skipping queue trigger\", type: \"system\", extra: { isStopped, isOffline, isEmpty } });\n } else if (isConcurrent) {\n // Collected once - looking for every request in the list of the running ones gets slow with a long queue\n const runningIds = new Set(runningRequests.map((running) => running.requestId));\n queue.requests.forEach((element) => {\n if (this.canPerformRequest(element, runningIds)) {\n runningIds.add(element.requestId);\n this.performRequest(element);\n }\n });\n }\n // One by one - the first request holds the queue also while it waits for its retry or for the network\n else if (isInactive && this.canPerformRequest(queueItem, new Set())) {\n await this.performRequest(queueItem);\n this.flushQueue(queryKey);\n }\n };\n\n /**\n * Flush all available requests from all queues\n */\n flush = async () => {\n const keys = this.getQueuesKeys();\n\n // eslint-disable-next-line no-restricted-syntax\n for (const key of keys) {\n const storageItem = this.getQueue(key);\n\n if (storageItem) {\n this.flushQueue(key);\n }\n }\n };\n\n /**\n * Clear all running requests and storage\n */\n clear = () => {\n clearTimeout(this.startTimer);\n this.startTimer = undefined;\n const keys = this.getQueuesKeys();\n // Running requests are canceled and report it on their own, the waiting ones are reported as removed\n const removed = keys.map((queryKey) => ({\n items: this.getQueue(queryKey).requests,\n answeredIds: this.getRunningRequests(queryKey).map((running) => running.requestId),\n }));\n keys.forEach((queryKey) => this.cancelRunningRequests(queryKey));\n\n [...this.runningRequests.keys()].forEach((queryKey) => this.setRunningRequests(queryKey, []));\n this.runningRequests.clear();\n this.cachedOrder.clear();\n this.storage.clear();\n removed.forEach(({ items, answeredIds }) => this.emitRemovedItems(items, answeredIds));\n this.client.triggerPlugins(\"onDispatcherCleared\", { dispatcher: this });\n };\n\n /**\n * Drop the scheduled retry of the request\n */\n private cancelRetry = (requestId: string) => {\n const timer = this.retryTimers.get(requestId);\n if (timer === undefined) {\n return false;\n }\n\n clearTimeout(timer);\n return this.retryTimers.delete(requestId);\n };\n\n // *********************************************************************\n // *********************************************************************\n // Requests\n // *********************************************************************\n // *********************************************************************\n\n /**\n * Start particular request\n */\n startRequest = (queryKey: string, requestId: string) => {\n // Change status to running\n const queue = this.getQueue(queryKey);\n const request = queue.requests.find((element) => element.requestId === requestId);\n\n // Start the queue when its stopped\n if (request) {\n request.stopped = false;\n this.setQueue(queryKey, queue);\n this.flushQueue(queryKey);\n this.events.emitQueueStatusChanged(queue);\n }\n };\n\n /**\n * Stop particular request\n */\n stopRequest = (queryKey: string, requestId: string) => {\n // Change state to stopped\n const queue = this.getQueue(queryKey);\n const request = queue.requests.find((element) => element.requestId === requestId);\n\n if (request) {\n request.stopped = true;\n this.setQueue(queryKey, queue);\n\n // Cancel running requests\n this.cancelRunningRequest(queryKey, requestId);\n this.events.emitQueueStatusChanged(queue);\n }\n };\n\n /**\n * Get currently running requests from all queryKeys\n */\n getAllRunningRequests = () => {\n return [...this.runningRequests.values()].flat();\n };\n\n /**\n * Get currently running requests\n */\n getRunningRequests = (queryKey: string) => {\n return this.runningRequests.get(queryKey) || [];\n };\n\n /**\n * Get running request by id\n */\n getRunningRequest = (queryKey: string, requestId: string) => {\n const runningRequests = this.getRunningRequests(queryKey);\n return runningRequests.find((req) => req.requestId === requestId);\n };\n\n /**\n * Single place for changing the running requests - notifies about the change\n */\n private setRunningRequests = (queryKey: string, runningRequests: RunningRequestValueType[]) => {\n const previousRequests = this.getRunningRequests(queryKey);\n if (runningRequests.length > 0) {\n this.runningRequests.set(queryKey, runningRequests);\n } else {\n // Do not keep an empty list for every queryKey that was ever used\n this.runningRequests.delete(queryKey);\n }\n if (\n previousRequests.length !== runningRequests.length ||\n previousRequests.some((req, i) => req !== runningRequests[i])\n ) {\n this.events.emitRunningRequestsChanged({ queryKey, runningRequests });\n }\n };\n\n /**\n * Add request to the running requests list\n */\n addRunningRequest = (queryKey: string, requestId: string, request: RequestInstance): RunningRequestValueType => {\n const newRunningRequest = { requestId, request, timestamp: Date.now() };\n this.setRunningRequests(queryKey, [...this.getRunningRequests(queryKey), newRunningRequest]);\n return newRunningRequest;\n };\n\n /**\n * Get the value based on the currently running requests\n */\n hasRunningRequests = (queryKey: string) => {\n return this.getRunningRequests(queryKey).length > 0;\n };\n\n /**\n * Check if request is currently processing\n */\n hasRunningRequest = (queryKey: string, requestId: string) => {\n const runningRequests = this.getRunningRequests(queryKey);\n return !!runningRequests.some((req) => req.requestId === requestId);\n };\n\n /**\n * Cancel all started requests, but do NOT remove it from main storage\n */\n cancelRunningRequests = (queryKey: string) => {\n this.runningRequests.get(queryKey)?.forEach((req) => {\n const ak = scopeKey(req.request.abortKey, req.request.scope);\n this.client.requestManager.abortByRequestId(ak, req.requestId);\n });\n this.deleteRunningRequests(queryKey);\n };\n /**\n * Cancel started request, but do NOT remove it from main storage\n */\n cancelRunningRequest = (queryKey: string, requestId: string) => {\n const requests = this.getRunningRequests(queryKey).filter((request) => {\n if (request.requestId === requestId) {\n const ak = scopeKey(request.request.abortKey, request.request.scope);\n this.client.requestManager.abortByRequestId(ak, request.requestId);\n return false;\n }\n return true;\n });\n\n this.setRunningRequests(queryKey, requests);\n };\n\n /**\n * Delete all started requests, but do NOT clear it from queue and do NOT cancel them\n */\n deleteRunningRequests = (queryKey: string) => {\n this.setRunningRequests(queryKey, []);\n };\n\n /**\n * Delete request by id, but do NOT clear it from queue and do NOT cancel them\n */\n deleteRunningRequest = (queryKey: string, requestId: string) => {\n const runningRequests = this.getRunningRequests(queryKey);\n this.setRunningRequests(\n queryKey,\n runningRequests.filter((req) => req.requestId !== requestId),\n );\n };\n\n /**\n * Get count of requests from the same queryKey\n */\n getQueueRequestCount = (queryKey: string) => {\n return this.requestCount.get(queryKey) || 0;\n };\n\n /**\n * Add request count to the queryKey\n */\n incrementQueueRequestCount = (queryKey: string) => {\n const count = this.requestCount.get(queryKey) || 0;\n this.requestCount.set(queryKey, count + 1);\n };\n\n /**\n * Create storage element from request\n */\n // eslint-disable-next-line class-methods-use-this\n createStorageItem = <R extends RequestInstance>(request: R): ResolvedQueueItemType<R> => {\n const requestId = this.client.unstable_requestIdMapper(request);\n return {\n requestId,\n timestamp: Date.now(),\n request,\n retries: 0,\n stopped: false,\n resolved: false,\n };\n };\n\n // *********************************************************************\n // *********************************************************************\n // Dispatching\n // *********************************************************************\n // *********************************************************************\n\n /**\n * Add request to the dispatcher handler\n */\n add = (request: RequestInstance) => {\n const queryKey = scopeKey(request.queryKey, request.scope);\n\n // Create dump of the request to allow storing it in localStorage, AsyncStorage or any other\n // This way we don't save the Class but the instruction of the request to be done\n const storageItem = this.createStorageItem(request);\n const { requestId } = storageItem;\n\n const queue = this.getQueue(queryKey);\n const [latestRequest] = queue.requests.slice(-1);\n const requestType = getRequestType(request, latestRequest);\n\n this.logger.debug({ title: \"Adding request to queue\", type: \"system\", extra: { requestType, request, requestId } });\n\n switch (requestType) {\n case DispatcherMode.ONE_BY_ONE: {\n // Requests will go one by one\n this.addQueueItem(queryKey, storageItem);\n this.flushQueue(queryKey);\n return requestId;\n }\n case DispatcherMode.PREVIOUS_CANCELED: {\n // Cancel all previous on-going requests\n const canceledIds = this.getRunningRequests(queryKey).map((running) => running.requestId);\n this.cancelRunningRequests(queryKey);\n this.removeQueueItems(queryKey, canceledIds);\n this.addQueueItem(queryKey, storageItem);\n this.flushQueue(queryKey);\n return requestId;\n }\n case DispatcherMode.DEDUPLICATED: {\n this.client.requestManager.events.emitDeduplicated({\n request: latestRequest.request,\n requestId,\n deduplicatedRequest: request,\n });\n // Return the running requestId to fulfill the events\n return latestRequest.requestId;\n }\n default: {\n this.addQueueItem(queryKey, storageItem);\n this.flushQueue(queryKey);\n return requestId;\n }\n }\n };\n\n /**\n * Delete from the storage and cancel request\n */\n delete = (queryKey: string, requestId: string, abortKey: string) => {\n this.logger.debug({ title: \"Deleting request\", type: \"system\", extra: { queryKey, requestId, abortKey } });\n const queue = this.getQueue(queryKey);\n const queueItem = queue.requests.find((req) => req.requestId === requestId);\n\n if (!queueItem) {\n return;\n }\n\n queue.requests = queue.requests.filter((req) => req.requestId !== requestId);\n this.storage.set(queryKey, queue);\n this.cancelRetry(requestId);\n\n // Clean controllers\n if (this.hasRunningRequest(queryKey, requestId)) {\n this.deleteRunningRequest(queryKey, requestId);\n this.client.requestManager.abortByRequestId(abortKey, requestId);\n }\n\n // Emit Queue Changes\n this.client.triggerPlugins(\"onDispatcherItemDeleted\", { queue, dispatcher: this, queueItem });\n\n this.events.emitQueueChanged(queue);\n this.client.requestManager.events.emitRemove({\n requestId,\n request: queueItem.request,\n resolved: queueItem.resolved,\n });\n\n if (queue.requests.length === 0) {\n this.client.triggerPlugins(\"onDispatcherQueueDrained\", { queue, dispatcher: this });\n this.events.emitDrained(queue);\n }\n\n return queue;\n };\n\n /**\n * Save the number of used attempts on the queued request\n */\n private setQueueItemRetries = (queryKey: string, requestId: string, retries: number) => {\n const queue = this.getQueue(queryKey);\n const queueItem = queue.requests.find((item) => item.requestId === requestId);\n\n if (queueItem) {\n queueItem.retries = retries;\n this.storage.set(queryKey, queue);\n }\n };\n\n /**\n * The `retryOnError` callback belongs to the user - when it throws, the request is not retried\n */\n private getShouldRetryOnError = (request: RequestInstance, response: RequestResponseType<any>) => {\n if (!request.retryOnError) {\n return true;\n }\n try {\n return !!request.retryOnError(response);\n } catch (error) {\n this.logger.error({ title: \"The retryOnError callback failed\", type: \"system\", extra: { error, request } });\n return false;\n }\n };\n\n /**\n * Delay of the next attempt from the `retryTime` of the request. The function form belongs to the user - when it\n * throws, the request is not retried (`null`). Anything but a positive finite delay retries right away.\n */\n private getRetryDelay = (request: RequestInstance, attempt: number, response: RequestResponseType<any>) => {\n const { retryTime } = request;\n let delay: unknown = retryTime;\n if (typeof retryTime === \"function\") {\n try {\n delay = retryTime({ attempt, response });\n } catch (error) {\n this.logger.error({ title: \"The retryTime callback failed\", type: \"system\", extra: { error, request } });\n return null;\n }\n }\n return typeof delay === \"number\" && Number.isFinite(delay) && delay > 0 ? delay : 0;\n };\n\n /**\n * Request can run for some time, once it's done, we have to check if it's successful or if it was aborted\n * It can be different once the previous call was set as cancelled and removed from queue before this request got resolved\n */\n performRequest = async (storageItem: ResolvedQueueItemType) => {\n const { request, requestId } = storageItem;\n this.logger.debug({ title: \"Performing request\", type: \"system\", extra: { request, requestId } });\n\n const { retry, queryKey: rawQueryKey, abortKey: rawAbortKey, offline, scope } = request;\n const queryKey = scopeKey(rawQueryKey, scope);\n const abortKey = scopeKey(rawAbortKey, scope);\n const { adapter, requestManager, cache, appManager } = this.client;\n\n const canRetry = canRetryRequest(storageItem.retries, retry);\n // When offline not perform any request\n const isOffline = !appManager.isOnline && offline;\n // When request with this id was triggered again\n const isAlreadyRunning = this.hasRunningRequest(queryKey, requestId);\n const isStopped = storageItem.stopped;\n\n if (isOffline || isAlreadyRunning || isStopped) {\n return this.logger.warning({\n title: \"Unable to perform request\",\n type: \"system\",\n extra: { isOffline, isAlreadyRunning, isStopped },\n });\n }\n\n // Additionally keep the running request to possibly abort it later\n const runningRequest = this.addRunningRequest(queryKey, requestId, request);\n this.sentCount += 1;\n const sentOrder = this.sentCount;\n\n // Propagate the loading to all connected hooks\n requestManager.events.emitLoading({\n request,\n requestId,\n loading: true,\n isRetry: !!storageItem.retries,\n isOffline,\n });\n\n // Trigger Request\n this.incrementQueueRequestCount(queryKey);\n // Listen for aborting\n requestManager.addAbortController(abortKey, requestId);\n\n const response: RequestResponseType<any> = await adapter.fetch(request, requestId);\n\n // TODO: improve this\n // eslint-disable-next-line no-param-reassign\n storageItem.resolved = true;\n // Read before the controller is dropped - adapters may map the abort error into any shape (GraphQL uses arrays)\n const isAbortedByUser = requestManager.isCanceled(abortKey, requestId);\n // Stop listening for aborting\n requestManager.removeAbortController(abortKey, requestId);\n // Do not continue the request handling when it got stopped and request was unsuccessful\n // Or when the request was aborted/canceled\n const isOfflineResponseStatus = !appManager.isOnline;\n // If there is no running request with this id, it means it was cancelled and removed during send\n const isCancelMessage = getErrorMessage(\"abort\").message === response.error?.message;\n const isCanceled = !this.hasRunningRequest(queryKey, requestId) || isAbortedByUser || isCancelMessage;\n // The browser cancels the requests of an unloading page - the failure says nothing about the request itself\n const isUnloadFailure = !response.success && appManager.isUnloading;\n\n // Remove running request, must be called after isCancelled\n this.deleteRunningRequest(queryKey, requestId);\n\n // The request is no longer running, but it stays in the queue until its response is handled below. Listeners\n // of the response can add requests to this queue - flushing it must not send the answered request again.\n this.answeredRequests.add(requestId);\n try {\n // A request removed from the queue while it was running (cleared queue) has nothing left to retry\n const isQueued = !!this.getRequest(queryKey, requestId);\n const canRetryResponse =\n !response.success && canRetry && isQueued && !isCanceled && !isOfflineResponseStatus && !isUnloadFailure;\n const retryDelay =\n canRetryResponse && this.getShouldRetryOnError(request, response)\n ? this.getRetryDelay(request, storageItem.retries, response)\n : null;\n const willRetry = retryDelay !== null;\n\n const requestDetails: ResponseDetailsType = {\n isCanceled,\n isOffline: isOfflineResponseStatus,\n retries: storageItem.retries,\n willRetry,\n addedTimestamp: storageItem.timestamp,\n triggerTimestamp: runningRequest.timestamp,\n requestTimestamp: response.requestTimestamp,\n responseTimestamp: response.responseTimestamp,\n };\n\n // A throwing listener must not leave the request in the queue forever (and block all the queued ones behind it)\n const notify = (callback: VoidFunction) => {\n try {\n callback();\n } catch (error) {\n this.logger.error({\n title: \"Response listener failed\",\n type: \"system\",\n extra: { error, request, requestId },\n });\n throwOutsideLifecycle(error);\n }\n };\n\n // Global response emitter to handle request execution\n notify(() => requestManager.events.emitResponse({ request, requestId, response, details: requestDetails }));\n\n // Turn off loading\n notify(() =>\n requestManager.events.emitLoading({\n request,\n requestId,\n loading: false,\n isRetry: !!storageItem.retries,\n isOffline,\n }),\n );\n\n // Requests of one cache key can answer in another order than they were sent. Once the data of a request is in\n // the cache, a response of a request sent before it is outdated - it must not replace that data.\n const storageKey = scopeKey(request.cacheKey, scope);\n const isOutdated = (this.cachedOrder.get(storageKey) ?? 0) > sentOrder;\n // A pending optimistic change on the key makes the response stale - the refresh after it supplies current data.\n // Always checked, so a fetch marked as stale is released even when its response is skipped for another reason.\n let isStaleOptimistic = false;\n notify(() => {\n isStaleOptimistic = isStaleOptimisticResponse(this.client, request, requestId);\n });\n\n if (isOutdated) {\n this.logger.debug({\n title: \"Response of a request sent before the cached one, skipping the cache\",\n type: \"system\",\n extra: { requestId, request, response },\n });\n } else if (isStaleOptimistic) {\n this.logger.debug({\n title: \"Response started before a pending optimistic change settled, skipping the cache\",\n type: \"system\",\n extra: { requestId, request, response },\n });\n } else {\n if (response.success) {\n this.cachedOrder.set(storageKey, sentOrder);\n }\n // Cache event to emit the data inside and store it\n notify(() => cache.set(request, { ...response, ...requestDetails }));\n }\n this.logger.debug({\n title: \"Dispatcher processing response\",\n type: \"system\",\n extra: { requestId, request, response, details: requestDetails },\n });\n\n // On cancelled\n if (isCanceled) {\n const queue = this.getQueue(queryKey);\n const queueItem = queue.requests.find((req) => req.requestId === requestId);\n\n // do not remove cancelled request as it may be result of manual queue pause\n // if abort was done without stop action we can remove request\n if (!queue.stopped && !queueItem?.stopped) {\n this.logger.debug({ title: \"Request paused\", type: \"system\", extra: { response, requestDetails, request } });\n return this.delete(queryKey, requestId, abortKey);\n }\n return this.logger.debug({\n title: \"Request canceled\",\n type: \"system\",\n extra: { response, requestDetails, request },\n });\n }\n // On page unload - the request stays in the queue, a persistent storage sends it again on the next start\n if (isUnloadFailure) {\n return this.logger.debug({\n title: \"Page is unloading, keeping the request for the next start\",\n type: \"system\",\n extra: { response, requestDetails, request },\n });\n }\n // On offline\n if (!response.success && isOfflineResponseStatus) {\n // if we don't want to keep offline request - just delete them\n if (!offline) {\n this.logger.warning({\n title: \"Removing non-offline request\",\n type: \"system\",\n extra: { response, requestDetails, request },\n });\n return this.delete(queryKey, requestId, abortKey);\n }\n // do not remove request from store as we want to re-send it later\n return this.logger.debug({\n title: \"Awaiting for network restoration\",\n type: \"system\",\n extra: { response, requestDetails, request },\n });\n }\n // On success\n if (response.success) {\n this.delete(queryKey, requestId, abortKey);\n return this.logger.debug({\n title: \"Successful response, removing request from queue.\",\n type: \"system\",\n extra: {\n response,\n requestDetails,\n request,\n },\n });\n }\n // On retry\n if (willRetry) {\n this.logger.debug({ title: \"Waiting for retry\", type: \"system\", extra: { response, requestDetails, request } });\n const retries = storageItem.retries + 1;\n // The attempts are counted on the queued item - whatever sends it next (the timer below, a new request\n // flushing the queue, the network coming back, the queue being started) continues from this number\n this.setQueueItemRetries(queryKey, requestId, retries);\n // Only the latest failure schedules the retry\n this.cancelRetry(requestId);\n // Perform retry once request is failed\n const retryTimer = setTimeout(async () => {\n this.retryTimers.delete(requestId);\n const queueItem = this.getRequest(queryKey, requestId);\n\n // Dispatcher methods cancel this timer, so the item was taken directly from the storage and nobody announced it\n if (!queueItem) {\n this.logger.debug({\n title: \"Request no longer in queue, skipping retry\",\n type: \"request\",\n extra: { response, requestDetails, request, requestId },\n });\n requestManager.events.emitRemove({ requestId, request, resolved: storageItem.resolved });\n return;\n }\n // Stopped while waiting - it will be sent again when the request gets started\n if (queueItem.stopped) {\n return;\n }\n\n this.logger.warning({\n title: \"Error response, performing retry\",\n type: \"request\",\n extra: { response, requestDetails, request, requestId },\n });\n await this.performRequest({\n ...storageItem,\n retries,\n });\n // Let the queue go on when it was held by this request\n this.flushQueue(queryKey);\n }, retryDelay);\n this.retryTimers.set(requestId, retryTimer);\n // Announced once the retry is scheduled - listeners see the request waiting for it\n notify(() =>\n requestManager.events.emitRetry({\n request,\n requestId,\n response,\n details: requestDetails,\n retry: retries,\n delay: retryDelay,\n }),\n );\n } else {\n if (request.retry) {\n this.logger.error({\n title: \"All retries have been used. Removing request from queue.\",\n type: \"request\",\n extra: { response, requestDetails, request, requestId },\n });\n }\n this.delete(queryKey, requestId, abortKey);\n }\n } finally {\n this.answeredRequests.delete(requestId);\n // A request which stays in the queue was skipped by the flushes made from its listeners - for example\n // the one of the network coming back - so it gets its chance now\n if (this.getRequest(queryKey, requestId)) {\n this.flushQueue(queryKey);\n }\n }\n };\n}\n","import type { ResolvedQueueItemType } from \"dispatcher\";\nimport { DispatcherMode } from \"dispatcher\";\nimport type { RequestInstance } from \"request\";\n\n// Events\n\nexport const getDispatcherDrainedKey = (): string => {\n return `drained-event`;\n};\nexport const getDispatcherDrainedByKey = (key: string): string => {\n return `${key}-drained-event`;\n};\nexport const getDispatcherStatusKey = (): string => {\n return `status-event`;\n};\nexport const getDispatcherStatusByKey = (key: string): string => {\n return `${key}-status-event`;\n};\nexport const getDispatcherChangeKey = (): string => {\n return `change-event`;\n};\nexport const getDispatcherChangeByKey = (key: string): string => {\n return `${key}-change-event`;\n};\nexport const getDispatcherRunningKey = (): string => {\n return `running-event`;\n};\nexport const getDispatcherRunningByKey = (key: string): string => {\n return `${key}-running-event`;\n};\n\n// Requesting\n\nexport const getIsEqualTimestamp = (currentTimestamp: number, threshold: number, queueTimestamp?: number): boolean => {\n if (!queueTimestamp) {\n return false;\n }\n return queueTimestamp - currentTimestamp <= threshold;\n};\n\nexport const canRetryRequest = (currentRetries: number, retry: number | undefined) => {\n if (retry && currentRetries < retry) {\n return true;\n }\n return false;\n};\n\nconst isInDeduplicateRange = (request: RequestInstance, latestRequest: ResolvedQueueItemType) => {\n if (request.deduplicateTime) {\n return Date.now() - latestRequest.timestamp <= request.deduplicateTime;\n }\n return true;\n};\n\nexport const getRequestType = (request: RequestInstance, latestRequest: ResolvedQueueItemType | undefined) => {\n const { queued, cancelable, deduplicate, used } = request;\n const canDeduplicate = latestRequest ? isInDeduplicateRange(request, latestRequest) : false;\n // Only join requests that are genuinely still ongoing. A resolved item already emitted its\n // response (a late joiner would wait forever), and a stopped item may never fire at all.\n const isOngoing = latestRequest ? !latestRequest.resolved && !latestRequest.stopped : false;\n\n if (queued) {\n return DispatcherMode.ONE_BY_ONE;\n }\n if (cancelable) {\n return DispatcherMode.PREVIOUS_CANCELED;\n }\n // A request marked with setUsed(true) is an intentional resend, like the auth interceptor\n // retrying after a token refresh. Deduplicating it against the original in-flight request\n // would deadlock: the retry would wait for a response that is blocked on the interceptor.\n if (canDeduplicate && isOngoing && deduplicate && !used) {\n return DispatcherMode.DEDUPLICATED;\n }\n return DispatcherMode.ALL_AT_ONCE;\n};\n","import { Time } from \"constants/time.constants\";\n\nimport type { HttpAdapterExtraType } from \"./http-adapter.types\";\n\nexport const defaultTimeout = Time.SEC * 5;\n\n/**\n * Default `extra` of the `HttpAdapter`. It holds the response headers, so it starts empty and is used until a response\n * arrives, and for requests that fail before the server answers.\n */\nexport const httpExtra: HttpAdapterExtraType = {\n headers: {},\n};\n\n/**\n * @deprecated Use `httpExtra`. The `HttpAdapter` sends requests with `fetch`, not `XMLHttpRequest`.\n */\nexport const xhrExtra: HttpAdapterExtraType = httpExtra;\n","import type { QueryParamsType, QueryParamType, QueryParamValuesType } from \"adapter\";\nimport { getErrorMessage } from \"adapter\";\nimport { stringifyDefaultOptions } from \"client\";\nimport type { RequestInstance } from \"request\";\nimport type { ExtractErrorType, EmptyTypes } from \"types\";\n\nimport type { BufferEncoding, QueryStringifyOptionsType } from \"./http-adapter.types\";\n\n// Utils\n\nexport const getResponseHeaders = (headersString: string): Record<string, string> => {\n const arr = headersString.trim().split(/[\\r\\n]+/);\n\n const headers: Record<string, string> = {};\n arr.forEach((line) => {\n const parts = line.split(\": \");\n const header = parts.shift();\n const value = parts.join(\": \");\n if (header) {\n headers[header] = value;\n }\n });\n\n return headers;\n};\n\n// Responses\n\nexport const parseResponse = (response: string | unknown) => {\n try {\n return JSON.parse(response as string);\n } catch {\n return response;\n }\n};\n\nexport const handleResponse = (responseChunks: any[], responseType: string, responseEncoding: BufferEncoding) => {\n const bufferedResponse = Buffer.concat(responseChunks);\n switch (responseType) {\n case \"arraybuffer\": {\n return bufferedResponse;\n }\n case \"json\": {\n return parseResponse(bufferedResponse.toString(responseEncoding));\n }\n default: {\n return bufferedResponse.toString(responseEncoding);\n }\n }\n};\n\nexport const parseErrorResponse = <T extends RequestInstance>(response: unknown): ExtractErrorType<T> => {\n return response ? parseResponse(response) : (getErrorMessage() as ExtractErrorType<T>);\n};\n\n// Stringify\n\nconst isValidValue = (options: QueryStringifyOptionsType) => {\n return (value: QueryParamType) => {\n const { skipNull, skipEmptyString } = options;\n\n if (skipEmptyString && value === undefined) {\n return false;\n }\n if (skipEmptyString && value === \"\") {\n return false;\n }\n if (skipNull && value === null) {\n return false;\n }\n return true;\n };\n};\n\nconst encodeValue = (\n value: string,\n { encode, strict }: Pick<QueryStringifyOptionsType, \"encode\" | \"strict\">,\n): string => {\n if (encode && strict) {\n return encodeURIComponent(value).replaceAll(/[!'()*]/g, (s) => `%${s.codePointAt(0)!.toString(16).toUpperCase()}`);\n }\n if (encode) {\n return encodeURIComponent(value);\n }\n return value;\n};\n\nconst parseValue = (value: QueryParamValuesType, options: QueryStringifyOptionsType): string => {\n if (value instanceof Date) {\n return options.dateParser?.(value) || value.toISOString();\n }\n\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n return options.objectParser?.(value) || JSON.stringify(value);\n }\n\n return String(value);\n};\n\nconst encodeParams = (key: string, value: QueryParamType, options: QueryStringifyOptionsType) => {\n const shouldSkip = !isValidValue(options)(value);\n\n if (!key || shouldSkip) {\n return \"\";\n }\n\n return `${encodeValue(key, options)}=${encodeValue(parseValue(value as QueryParamValuesType, options), options)}`;\n};\n\nconst encodeArray = (key: string, array: QueryParamValuesType[], options: QueryStringifyOptionsType): string => {\n const { arrayFormat, arraySeparator } = options;\n const separator = arraySeparator || \"|\";\n const encodedKey = encodeValue(key, options);\n\n return array\n .filter(isValidValue(options))\n .reduce<string[]>((acc, value, index) => {\n const encodedValue = encodeValue(parseValue(value, options), options);\n\n switch (arrayFormat) {\n case \"index\": {\n acc.push(`${encodedKey}[${encodeValue(String(index), options)}]=${encodedValue}`);\n break;\n }\n case \"bracket\": {\n acc.push(`${encodedKey}[]=${encodedValue}`);\n break;\n }\n case \"comma\": {\n const keyValue = (acc.length === 0 && `${encodedKey}=`) || \"\";\n return [[...acc, `${keyValue}${encodedValue}`].join(\",\")];\n }\n case \"separator\": {\n const keyValue = (acc.length === 0 && `${encodedKey}=`) || \"\";\n return [[...acc, `${keyValue}${encodedValue}`].join(separator)];\n }\n case \"bracket-separator\": {\n const keyValue = (acc.length === 0 && `${encodedKey}[]=`) || \"\";\n return [[...acc, `${keyValue}${encodedValue}`].join(separator)];\n }\n default: {\n acc.push(`${encodedKey}=${encodedValue}`);\n }\n }\n\n return acc;\n }, [])\n .join(\"&\");\n};\n\nexport const stringifyQueryParams = (\n queryParams: QueryParamsType | string | EmptyTypes,\n options?: QueryStringifyOptionsType,\n): string => {\n // Merge with defaults so a partial config (e.g. `{ arrayFormat: \"comma\" }`) keeps encoding and skipping enabled\n const config: QueryStringifyOptionsType = { ...stringifyDefaultOptions, ...options };\n\n if (!queryParams || Object.keys(queryParams).length === 0) {\n return \"\";\n }\n\n if (typeof queryParams === \"string\") {\n const hasQuestionMark = queryParams[0] === \"?\";\n return hasQuestionMark ? queryParams : `?${queryParams}`;\n }\n\n const stringified = Object.entries(queryParams)\n .map(([key, value]): string => {\n if (Array.isArray(value)) {\n return encodeArray(key, value, config);\n }\n\n return encodeParams(key, value, config);\n })\n .filter(Boolean)\n .join(\"&\");\n\n if (stringified) {\n return `?${stringified}`;\n }\n return \"\";\n};\n","import type { QueryParamsType } from \"adapter\";\nimport { HttpMethods, SAFE_HTTP_METHODS } from \"constants/http.constants\";\nimport type { HttpMethodsType, HttpStatusType } from \"types\";\n\nimport { Adapter } from \"../adapter/adapter\";\nimport { defaultTimeout, httpExtra } from \"./http-adapter.constants\";\nimport type { HttpAdapterExtraType, FetchAdapterOptionsType, FetchResponseType } from \"./http-adapter.types\";\nimport { parseErrorResponse, parseResponse, stringifyQueryParams } from \"./http-adapter.utils\";\n\nconst defaultExtra = httpExtra;\n\n/**\n * Size in bytes of a body that fetch sends as it is. Form data and streams get their size from the browser while they\n * are sent, so it is unknown up front.\n */\nconst getBodySize = (body: unknown): number | undefined => {\n if (typeof body === \"string\") return new Blob([body]).size;\n if (typeof Blob !== \"undefined\" && body instanceof Blob) return body.size;\n if (body instanceof ArrayBuffer) return body.byteLength;\n if (ArrayBuffer.isView(body)) return body.byteLength;\n if (typeof URLSearchParams !== \"undefined\" && body instanceof URLSearchParams) {\n return new Blob([body.toString()]).size;\n }\n return undefined;\n};\n\n/**\n * Body of a successful response in the shape picked with the `responseType` option\n */\nconst readResponseBody = (bytes: Uint8Array, responseType: FetchResponseType | undefined, contentType: string | null) => {\n switch (responseType) {\n case \"arrayBuffer\": {\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n }\n case \"blob\": {\n return new Blob([bytes as BlobPart], { type: contentType ?? \"\" });\n }\n case \"text\": {\n return new TextDecoder().decode(bytes);\n }\n default: {\n return parseResponse(new TextDecoder().decode(bytes));\n }\n }\n};\n\nexport const getAdapter = () =>\n new Adapter<\n FetchAdapterOptionsType,\n HttpMethodsType,\n HttpStatusType,\n HttpAdapterExtraType,\n QueryParamsType | string | null,\n undefined,\n string\n >({\n name: \"http\",\n defaultMethod: HttpMethods.GET,\n defaultExtra,\n systemErrorStatus: 0 as number,\n systemErrorExtra: defaultExtra,\n })\n .setQueryParamsMapper(stringifyQueryParams)\n // Safe reads (GET, QUERY) deduplicate by default: concurrent identical requests collapse\n // into one network call. Explicit `deduplicate` in request options still wins.\n .setRequestDefaults((options) => {\n const method = options.method ?? HttpMethods.GET;\n if (SAFE_HTTP_METHODS.includes(method)) {\n return { deduplicate: true };\n }\n return {};\n })\n .setFetcher(\n async ({\n request,\n url,\n endpoint,\n queryParams,\n adapterOptions,\n headers,\n payload,\n onError,\n onResponseEnd,\n onTimeoutError,\n onRequestEnd,\n createAbortListener,\n getAbortController,\n onResponseProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onSuccess,\n }) => {\n const { method } = request;\n const fullUrl = `${url}${endpoint}${queryParams}`;\n\n const controller = getAbortController();\n const {\n timeout: timeoutMs = defaultTimeout,\n streaming = false,\n responseType,\n ...restOptions\n } = adapterOptions || {};\n\n let timedOut = false;\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n // Abort listener handles user-initiated aborts (e.g. request.abort())\n // For fetch, onAbort is a no-op since the signal is already passed to fetch()\n const unmountListener = createAbortListener({\n status: 0,\n extra: defaultExtra,\n });\n\n if (timeoutMs > 0 && controller) {\n timeoutId = setTimeout(() => {\n timedOut = true;\n unmountListener();\n controller.abort();\n }, timeoutMs);\n }\n\n const body = payload && method !== \"GET\" && method !== \"HEAD\" ? (payload as BodyInit) : undefined;\n const bodySize = getBodySize(body);\n\n onBeforeRequest();\n onRequestStart(bodySize ? { total: bodySize, loaded: 0 } : undefined);\n\n try {\n const init: RequestInit = {\n method,\n headers: headers as Record<string, string>,\n signal: controller?.signal,\n ...restOptions,\n };\n\n if (body) {\n init.body = body;\n }\n\n const response = await fetch(fullUrl, init);\n\n // Fetch has no upload events. The response is the first sign that the whole body was sent.\n onRequestEnd();\n\n // The timeout covers the whole exchange - a body that stops arriving has to end with the timeout error.\n // Only a streamed body is handed over to the user as soon as the headers arrive.\n if (timeoutId && streaming && response.body) {\n clearTimeout(timeoutId);\n }\n\n onResponseStart();\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n const extra: HttpAdapterExtraType = { headers: responseHeaders };\n const { status } = response;\n\n if (streaming && response.body) {\n onResponseEnd();\n unmountListener();\n\n if (response.ok) {\n onSuccess({ data: response.body as any, status, extra });\n } else {\n const errorBody = await response.text();\n const error = parseErrorResponse(errorBody);\n onError({ error, status, extra });\n }\n } else {\n // The body is read as bytes from the stream. Without a stream reader (e.g. React Native) it is read with\n // the method matching the response type - text for the default one, so nothing more than text is needed.\n let body: { bytes: Uint8Array } | { text: string } | { data: Blob | ArrayBuffer };\n\n if (response.body && typeof response.body.getReader === \"function\") {\n const reader = response.body.getReader();\n // Fetch gives the decompressed body, while Content-Length tells the size of the encoded one - the total\n // of an encoded body is unknown\n const contentEncoding = response.headers.get(\"content-encoding\");\n const isEncoded = !!contentEncoding && contentEncoding !== \"identity\";\n const contentLength = isEncoded ? 0 : parseInt(response.headers.get(\"content-length\") || \"0\", 10);\n let receivedLength = 0;\n const chunks: Uint8Array[] = [];\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n // eslint-disable-next-line no-await-in-loop\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n chunks.push(value);\n receivedLength += value.length;\n onResponseProgress({ total: contentLength || receivedLength, loaded: receivedLength } as ProgressEvent);\n }\n\n const allChunks = new Uint8Array(receivedLength);\n let position = 0;\n // eslint-disable-next-line no-restricted-syntax\n for (const chunk of chunks) {\n allChunks.set(chunk, position);\n position += chunk.length;\n }\n body = { bytes: allChunks };\n } else if (response.ok && responseType === \"blob\") {\n body = { data: await response.blob() };\n } else if (response.ok && responseType === \"arrayBuffer\") {\n body = { data: await response.arrayBuffer() };\n } else {\n body = { text: await response.text() };\n }\n\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n onResponseEnd();\n unmountListener();\n\n const getText = () => (\"text\" in body ? body.text : new TextDecoder().decode(\"bytes\" in body ? body.bytes : undefined));\n\n if (response.ok) {\n let data: unknown;\n if (\"data\" in body) {\n data = body.data;\n } else if (\"bytes\" in body) {\n data = readResponseBody(body.bytes, responseType, response.headers.get(\"content-type\"));\n } else {\n data = responseType === \"text\" ? body.text : parseResponse(body.text);\n }\n onSuccess({ data, status, extra });\n } else {\n const error = parseErrorResponse(getText());\n onError({ error, status, extra });\n }\n }\n } catch (error: any) {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n unmountListener();\n\n if (controller?.signal?.aborted) {\n if (timedOut) {\n onTimeoutError({ status: 0, extra: defaultExtra });\n }\n return;\n }\n\n onError({ error, status: 0, extra: defaultExtra });\n }\n },\n );\n","import type { HttpAdapterType } from \"http-adapter/http-adapter.types\";\n\nimport { getAdapter } from \"./http-adapter.fetch\";\n\nexport const HttpAdapter = (): HttpAdapterType => {\n return getAdapter();\n};\n","import type { AppManagerOptionsType } from \"managers\";\nimport { appManagerInitialOptions, getAppManagerEvents, hasDocument, onWindowEvent } from \"managers\";\nimport { EventEmitter } from \"utils\";\n\n/**\n * App manager handles main application states - focus and online. Those two values can answer questions:\n * - Is the tab or current view instance focused and visible for user?\n * - Is our application online or offline?\n * With the app manager it is not a problem to get the valid answer for this question.\n *\n * @caution\n * Make sure to apply valid focus/online handlers for different environments like for example for native mobile applications.\n */\nexport class AppManager {\n emitter = new EventEmitter();\n events = getAppManagerEvents(this.emitter);\n\n isBrowser: boolean;\n isOnline: boolean;\n isFocused: boolean;\n /**\n * True while the browser page is being unloaded (closed, reloaded or navigated away). The browser cancels the\n * requests in flight then - their failures are not real answers, so the dispatcher keeps them for the next start.\n */\n isUnloading = false;\n\n private unmountCallbacks: VoidFunction[] = [];\n private hasFocusUpdate = false;\n private hasOnlineUpdate = false;\n\n constructor(public options?: AppManagerOptionsType) {\n this.emitter?.setMaxListeners(1000);\n const {\n initiallyFocused = appManagerInitialOptions.initiallyFocused,\n initiallyOnline = appManagerInitialOptions.initiallyOnline,\n } = this.options || appManagerInitialOptions;\n\n this.setInitialFocus(initiallyFocused);\n this.setInitialOnline(initiallyOnline);\n\n this.isBrowser = hasDocument();\n }\n\n /**\n * Subscribes to the environment focus and network changes. Calling it again replaces the previous subscriptions,\n * so the listeners are never registered twice.\n */\n initialize = () => {\n const { focusEvent = appManagerInitialOptions.focusEvent, onlineEvent = appManagerInitialOptions.onlineEvent } =\n this.options || appManagerInitialOptions;\n\n this.unmount();\n\n [\n focusEvent(this.setFocused),\n onlineEvent(this.setOnline),\n onWindowEvent(\"pagehide\", () => {\n this.isUnloading = true;\n }),\n // The page can come back from the back-forward cache\n onWindowEvent(\"pageshow\", () => {\n this.isUnloading = false;\n }),\n ].forEach((unmount) => {\n if (typeof unmount === \"function\") {\n this.unmountCallbacks.push(unmount);\n }\n });\n };\n\n /**\n * Removes the environment listeners registered by `initialize()`. Listeners added with `events` are kept.\n */\n unmount = () => {\n const callbacks = this.unmountCallbacks;\n this.unmountCallbacks = [];\n callbacks.forEach((unmount) => unmount());\n };\n\n private setInitialFocus = (initValue: Exclude<AppManagerOptionsType[\"initiallyFocused\"], undefined>) => {\n this.isFocused = this.readInitialValue(initValue, (isFocused) => {\n // The environment could report the state in the meantime - it is more recent than the initial value\n if (!this.hasFocusUpdate && isFocused !== this.isFocused) {\n this.setFocused(isFocused);\n }\n });\n };\n\n private setInitialOnline = (initValue: Exclude<AppManagerOptionsType[\"initiallyOnline\"], undefined>) => {\n this.isOnline = this.readInitialValue(initValue, (isOnline) => {\n // The environment could report the state in the meantime - it is more recent than the initial value\n if (!this.hasOnlineUpdate && isOnline !== this.isOnline) {\n this.setOnline(isOnline);\n }\n });\n };\n\n /**\n * Reads the initial state from a value or a getter. Synchronous getters apply right away, so there is no moment\n * with a wrong value. Asynchronous ones start with `false` and apply once resolved - the change is emitted like\n * any other, so the modules waiting for the focus or the network get notified.\n * A getter which throws or rejects leaves the state unknown, so it falls back to `true` - just like the defaults do.\n */\n private readInitialValue = (\n initValue: boolean | (() => boolean | Promise<boolean>),\n onResolved: (value: boolean) => void,\n ): boolean => {\n if (typeof initValue !== \"function\") {\n return initValue;\n }\n\n try {\n const value = initValue();\n if (typeof value === \"boolean\") {\n return value;\n }\n\n Promise.resolve(value).then(\n (resolved) => onResolved(resolved),\n () => onResolved(true),\n );\n return false;\n } catch {\n return true;\n }\n };\n\n setFocused = (isFocused: boolean) => {\n this.hasFocusUpdate = true;\n this.isFocused = isFocused;\n\n if (isFocused) {\n this.events.emitFocus();\n } else {\n this.events.emitBlur();\n }\n };\n\n setOnline = (isOnline: boolean) => {\n this.hasOnlineUpdate = true;\n this.isOnline = isOnline;\n\n if (isOnline) {\n this.events.emitOnline();\n } else {\n this.events.emitOffline();\n }\n };\n}\n","export const hasWindow = () => {\n try {\n return Boolean(window && window.addEventListener);\n } catch {\n /* istanbul ignore next */\n return false;\n }\n};\n\nexport const hasDocument = () => {\n try {\n return Boolean(hasWindow() && window.document && window.document.addEventListener);\n } catch {\n /* istanbul ignore next */\n return false;\n }\n};\n\n/**\n * Reads the current network state from the browser. Falls back to `true` when it is unknown - e.g. in Node.js or\n * React Native, where `navigator.onLine` is not available.\n */\nexport const isNavigatorOnline = () => {\n try {\n return typeof navigator.onLine === \"boolean\" ? navigator.onLine : true;\n } catch {\n /* istanbul ignore next */\n return true;\n }\n};\n\nexport const onWindowEvent = <K extends keyof WindowEventMap>(\n key: K,\n listener: (this: Window, ev: WindowEventMap[K]) => any,\n options?: boolean | AddEventListenerOptions | undefined,\n): VoidFunction => {\n /* istanbul ignore next */\n if (hasWindow()) {\n // Keep the target - the cleanup has to reach the same object, even when the global one is already gone\n const target = window;\n target.addEventListener(key, listener, options);\n return () => target.removeEventListener(key, listener, options);\n }\n /* istanbul ignore next */\n return () => null;\n};\n\nexport const onDocumentEvent = <K extends keyof DocumentEventMap>(\n key: K,\n listener: (this: Document, ev: DocumentEventMap[K]) => any,\n options?: boolean | AddEventListenerOptions | undefined,\n): VoidFunction => {\n /* istanbul ignore next */\n if (hasDocument()) {\n // Keep the target - the cleanup has to reach the same object, even when the global one is already gone\n const target = window.document;\n target.addEventListener(key, listener, options);\n return () => target.removeEventListener(key, listener, options);\n }\n /* istanbul ignore next */\n return () => null;\n};\n","import type EventEmitter from \"events\";\nimport { AppEvents } from \"managers\";\n\n/** Create event emitters and listeners for application-level focus, blur, online, and offline state changes. */\nexport const getAppManagerEvents = (emitter: EventEmitter) => ({\n /** Emit when the application window gains focus */\n emitFocus: (): void => {\n emitter.emit(AppEvents.FOCUS);\n },\n /** Emit when the application window loses focus */\n emitBlur: (): void => {\n emitter.emit(AppEvents.BLUR);\n },\n /** Emit when the application transitions to online state */\n emitOnline: (): void => {\n emitter.emit(AppEvents.ONLINE);\n },\n /** Emit when the application transitions to offline state */\n emitOffline: (): void => {\n emitter.emit(AppEvents.OFFLINE);\n },\n /** Listen for focus events */\n onFocus: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.FOCUS, callback);\n return () => emitter.removeListener(AppEvents.FOCUS, callback);\n },\n /** Listen for blur events */\n onBlur: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.BLUR, callback);\n return () => emitter.removeListener(AppEvents.BLUR, callback);\n },\n /** Listen for online state transitions */\n onOnline: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.ONLINE, callback);\n return () => emitter.removeListener(AppEvents.ONLINE, callback);\n },\n /** Listen for offline state transitions */\n onOffline: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.OFFLINE, callback);\n return () => emitter.removeListener(AppEvents.OFFLINE, callback);\n },\n});\n","import type { AppManagerOptionsType } from \"managers\";\nimport type { RequiredKeys } from \"types\";\n\nimport { onWindowEvent, onDocumentEvent, isNavigatorOnline } from \"./app.manager.utils\";\n\n/** Document is visible unless the browser reports it as hidden - when the state is unknown we assume it is visible */\nconst isDocumentVisible = () => {\n try {\n return window.document.visibilityState !== \"hidden\";\n } catch {\n /* istanbul ignore next */\n return true;\n }\n};\n\nexport enum AppEvents {\n FOCUS = \"focus\",\n BLUR = \"blur\",\n ONLINE = \"online\",\n OFFLINE = \"offline\",\n}\n\nexport const appManagerInitialOptions: RequiredKeys<AppManagerOptionsType> = {\n initiallyFocused: true,\n initiallyOnline: isNavigatorOnline,\n focusEvent: (setFocused) => {\n // Visibility changes in both directions - hidden document means the application lost the focus\n const unmountVisibility = onDocumentEvent(\"visibilitychange\", () => setFocused(isDocumentVisible()));\n const unmountFocus = onWindowEvent(\"focus\", () => setFocused(true));\n const unmountBlur = onWindowEvent(\"blur\", () => setFocused(false));\n\n return () => {\n unmountVisibility();\n unmountFocus();\n unmountBlur();\n };\n },\n onlineEvent: (setOnline) => {\n const unmountOnline = onWindowEvent(\"online\", () => setOnline(true));\n const unmountOffline = onWindowEvent(\"offline\", () => setOnline(false));\n\n return () => {\n unmountOnline();\n unmountOffline();\n };\n },\n};\n","import { getRequestManagerEvents } from \"managers\";\nimport { EventEmitter } from \"utils\";\n\n/**\n * **Request Manager** is used to emit `request lifecycle events` like - request start, request end, upload and download progress.\n * It is also the place of `request aborting` system, here we store all the keys and controllers that are isolated for each client instance.\n */\nexport class RequestManager {\n emitter = new EventEmitter();\n events = getRequestManagerEvents(this.emitter);\n\n constructor() {\n this.emitter?.setMaxListeners(1000);\n }\n\n abortControllers = new Map<string, Map<string, AbortController>>();\n /** Controllers aborted through this manager, i.e. by the user and not by an adapter's own timeout */\n private canceledControllers = new WeakSet<AbortController>();\n\n addAbortController = (abortKey: string, requestId: string) => {\n let abortGroup = this.abortControllers.get(abortKey);\n if (!abortGroup) {\n const newAbortGroup = new Map();\n abortGroup = newAbortGroup;\n this.abortControllers.set(abortKey, newAbortGroup);\n }\n\n const abortController = abortGroup.get(requestId);\n if (!abortController || abortController.signal.aborted) {\n abortGroup.set(requestId, new AbortController());\n }\n };\n\n getAbortController = (abortKey: string, requestId: string) => {\n return this.abortControllers.get(abortKey)?.get(requestId);\n };\n\n removeAbortController = (abortKey: string, requestId: string) => {\n const abortGroup = this.abortControllers.get(abortKey);\n abortGroup?.delete(requestId);\n\n // Do not keep an empty group for every abortKey (and every scope) that was ever used\n if (abortGroup?.size === 0) {\n this.abortControllers.delete(abortKey);\n }\n };\n\n // Aborting\n\n useAbortController = (abortKey: string, requestId: string) => {\n const controller = this.abortControllers.get(abortKey)?.get(requestId);\n if (controller) {\n this.canceledControllers.add(controller);\n controller.abort();\n }\n };\n\n /**\n * Whether the request was aborted on purpose (`request.abort()`, `abortByKey`...). Tells canceled requests apart\n * from failed ones whatever shape the adapter gives its errors.\n */\n isCanceled = (abortKey: string, requestId: string) => {\n const controller = this.abortControllers.get(abortKey)?.get(requestId);\n return !!controller && this.canceledControllers.has(controller);\n };\n\n abortByKey = (abortKey: string) => {\n const controllers = this.abortControllers.get(abortKey);\n\n if (controllers) {\n const entries = [...controllers.entries()];\n entries.forEach(([key]) => {\n this.useAbortController(abortKey, key);\n });\n }\n };\n\n abortByRequestId = (abortKey: string, requestId: string) => {\n this.useAbortController(abortKey, requestId);\n };\n\n abortAll = () => {\n const entries = [...this.abortControllers.entries()];\n entries.forEach(([abortKey, value]) => {\n const controllers = [...value.entries()];\n controllers.forEach(([requestId]) => {\n this.useAbortController(abortKey, requestId);\n });\n });\n };\n}\n","// Events\n\nexport const getLoadingKey = (): string => `loading-event-any`;\nexport const getLoadingByQueryKey = (queryKey: string): string => `${queryKey}-loading-event`;\nexport const getLoadingByCacheKey = (cacheKey: string): string => `${cacheKey}-loading-cache-event`;\nexport const getLoadingByIdKey = (id: string): string => `${id}-loading-event-by-id`;\nexport const getRemoveKey = (): string => `remove-event-any`;\nexport const getRemoveByQueryKey = (queryKey: string): string => `${queryKey}-remove-event`;\nexport const getRemoveByIdKey = (id: string): string => `${id}-remove-event-by-id`;\nexport const getAbortKey = () => `request-abort-any`;\nexport const getAbortByAbortKey = (abortKey: string) => `${abortKey}-request-abort`;\nexport const getAbortByIdKey = (id: string) => `${id}-request-abort-by-id`;\nexport const getResponseKey = () => `response-any`;\nexport const getResponseByCacheKey = (cacheKey: string) => `${cacheKey}-response`;\nexport const getResponseByIdKey = (id: string) => `${id}-response-by-id`;\nexport const getRequestStartKey = () => `request-start-any`;\nexport const getRequestStarByQueryKey = (queryKey: string) => `${queryKey}-request-start`;\nexport const getRequestStartByIdKey = (id: string) => `${id}-request-start-by-id`;\nexport const getResponseStartKey = () => `response-start-any`;\nexport const getResponseStartByQueryKey = (queryKey: string) => `${queryKey}-response-start`;\nexport const getResponseStartByIdKey = (id: string) => `${id}-response-start-by-id`;\nexport const getUploadProgressKey = () => `request-progress-any`;\nexport const getUploadProgressByQueryKey = (queryKey: string) => `${queryKey}-request-progress`;\nexport const getUploadProgressByIdKey = (id: string) => `${id}-request-progress-by-id`;\nexport const getDownloadProgressKey = () => `response-progress-any`;\nexport const getDownloadProgressByQueryKey = (queryKey: string) => `${queryKey}-response-progress`;\nexport const getDownloadProgressByIdKey = (id: string) => `${id}-response-progress-by-id`;\nexport const getRetryKey = () => `request-retry-any`;\nexport const getRetryByQueryKey = (queryKey: string) => `${queryKey}-request-retry`;\nexport const getRetryByIdKey = (id: string) => `${id}-request-retry-by-id`;\nexport const getRequestDeduplicatedKey = () => `request-deduplicated-any`;\nexport const getRequestDeduplicatedByQueryKey = (queryKey: string) => `${queryKey}-query-request-deduplicated`;\nexport const getRequestDeduplicatedByCacheKey = (cacheKey: string) => `${cacheKey}-cache-request-deduplicated`;\nexport const getRequestDeduplicatedByIdKey = (id: string) => `${id}-request-deduplicated-by-id`;\n","import type { AdapterInstance } from \"adapter\";\nimport type { Client } from \"client\";\n/* eslint-disable max-params */\nimport type EventEmitter from \"events\";\nimport type {\n RequestEventType,\n RequestLoadingEventType,\n RequestProgressEventType,\n RequestResponseEventType,\n RequestRemovedEventType,\n RequestDeduplicatedEventType,\n RequestRetryEventType,\n} from \"managers\";\nimport {\n getRequestStarByQueryKey,\n getResponseStartByQueryKey,\n getDownloadProgressByQueryKey,\n getUploadProgressByQueryKey,\n getResponseByIdKey,\n getAbortByAbortKey,\n getAbortByIdKey,\n getResponseByCacheKey,\n getUploadProgressByIdKey,\n getDownloadProgressByIdKey,\n getResponseStartByIdKey,\n getRequestStartByIdKey,\n getLoadingByQueryKey,\n getLoadingByIdKey,\n getRemoveByQueryKey,\n getRemoveByIdKey,\n getLoadingKey,\n getRequestStartKey,\n getUploadProgressKey,\n getDownloadProgressKey,\n getResponseKey,\n getAbortKey,\n getRemoveKey,\n getResponseStartKey,\n getLoadingByCacheKey,\n getRequestDeduplicatedKey,\n getRequestDeduplicatedByIdKey,\n getRequestDeduplicatedByCacheKey,\n getRequestDeduplicatedByQueryKey,\n getRetryKey,\n getRetryByIdKey,\n getRetryByQueryKey,\n} from \"managers\";\nimport type { RequestInstance } from \"request\";\nimport type { ExtendRequest } from \"types\";\n\n/** Create event emitters and listeners for the request lifecycle: loading, progress, response, retry, abort, deduplication, and removal. */\nexport const getRequestManagerEvents = (emitter: EventEmitter) => ({\n /**\n * Emitters\n */\n\n /** Emit when a request is deduplicated (skipped because an identical one is in-flight) */\n emitDeduplicated: (data: RequestDeduplicatedEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getRequestDeduplicatedKey(), data, isTriggeredExternally);\n emitter.emit(getRequestDeduplicatedByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getRequestDeduplicatedByCacheKey(data.request.cacheKey), data, isTriggeredExternally);\n emitter.emit(getRequestDeduplicatedByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit loading state changes for a request */\n emitLoading: (data: RequestLoadingEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getLoadingKey(), data, isTriggeredExternally);\n emitter.emit(getLoadingByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getLoadingByCacheKey(data.request.cacheKey), data, isTriggeredExternally);\n emitter.emit(getLoadingByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit when a request starts being sent */\n emitRequestStart: (data: RequestEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getRequestStartKey(), data, isTriggeredExternally);\n emitter.emit(getRequestStartByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getRequestStarByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n /** Emit when the response starts being received */\n emitResponseStart: (data: RequestEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getResponseStartKey(), data, isTriggeredExternally);\n emitter.emit(getResponseStartByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getResponseStartByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit upload progress updates */\n emitUploadProgress: (data: RequestProgressEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getUploadProgressKey(), data, isTriggeredExternally);\n emitter.emit(getUploadProgressByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getUploadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n /** Emit download progress updates */\n emitDownloadProgress: (data: RequestProgressEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getDownloadProgressKey(), data, isTriggeredExternally);\n emitter.emit(getDownloadProgressByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getDownloadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit when a response is received */\n emitResponse: <Adapter extends AdapterInstance>(\n data: RequestResponseEventType<ExtendRequest<RequestInstance, { client: Client<any, Adapter> }>>,\n isTriggeredExternally = false,\n ): void => {\n emitter.emit(getResponseKey(), data, isTriggeredExternally);\n emitter.emit(getResponseByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getResponseByCacheKey(data.request.cacheKey), data, isTriggeredExternally);\n },\n\n /** Emit when a failed attempt schedules a retry - after its response, before the wait for the next attempt */\n emitRetry: (data: RequestRetryEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getRetryKey(), data, isTriggeredExternally);\n emitter.emit(getRetryByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getRetryByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit when a request is aborted */\n emitAbort: (data: RequestEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getAbortKey(), data, isTriggeredExternally);\n emitter.emit(getAbortByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getAbortByAbortKey(data.request.abortKey), data, isTriggeredExternally);\n },\n\n /** Emit when a request is removed from the dispatcher queue */\n emitRemove: (data: RequestRemovedEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getRemoveKey(), data, isTriggeredExternally);\n emitter.emit(getRemoveByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getRemoveByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /**\n * Listeners\n */\n\n /** Listen for deduplicated request events */\n onDeduplicated: <T extends RequestInstance>(\n callback: (data: RequestDeduplicatedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestDeduplicatedKey(), callback);\n return () => emitter.removeListener(getRequestDeduplicatedKey(), callback);\n },\n onDeduplicatedByQueue: <T extends RequestInstance>(\n queryKey: string,\n callback: (data: RequestDeduplicatedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestDeduplicatedByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getRequestDeduplicatedByQueryKey(queryKey), callback);\n },\n onDeduplicatedByCache: <T extends RequestInstance>(\n cacheKey: string,\n callback: (data: RequestDeduplicatedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestDeduplicatedByCacheKey(cacheKey), callback);\n return () => emitter.removeListener(getRequestDeduplicatedByCacheKey(cacheKey), callback);\n },\n onDeduplicatedById: <T extends RequestInstance>(\n requestId: string,\n callback: (data: RequestDeduplicatedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestDeduplicatedByIdKey(requestId), callback);\n return () => emitter.removeListener(getRequestDeduplicatedByIdKey(requestId), callback);\n },\n\n // Loading\n onLoading: <T extends RequestInstance>(callback: (data: RequestLoadingEventType<T>) => void): VoidFunction => {\n emitter.on(getLoadingKey(), callback);\n return () => emitter.removeListener(getLoadingKey(), callback);\n },\n onLoadingByQueue: <T extends RequestInstance>(\n queryKey: string,\n callback: (data: RequestLoadingEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getLoadingByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getLoadingByQueryKey(queryKey), callback);\n },\n onLoadingByCache: <T extends RequestInstance>(\n cacheKey: string,\n callback: (data: RequestLoadingEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getLoadingByCacheKey(cacheKey), callback);\n return () => emitter.removeListener(getLoadingByCacheKey(cacheKey), callback);\n },\n onLoadingById: <T extends RequestInstance>(\n requestId: string,\n callback: (data: RequestLoadingEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getLoadingByIdKey(requestId), callback);\n return () => emitter.removeListener(getLoadingByIdKey(requestId), callback);\n },\n\n // Request Start\n onRequestStart: <T extends RequestInstance>(callback: (details: RequestEventType<T>) => void): VoidFunction => {\n emitter.on(getRequestStartKey(), callback);\n return () => emitter.removeListener(getRequestStartKey(), callback);\n },\n onRequestStartByQueue: <T extends RequestInstance>(\n queryKey: string,\n callback: (details: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestStarByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getRequestStarByQueryKey(queryKey), callback);\n },\n onRequestStartById: <T extends RequestInstance>(\n requestId: string,\n callback: (details: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestStartByIdKey(requestId), callback);\n return () => emitter.removeListener(getRequestStartByIdKey(requestId), callback);\n },\n\n // Response Start\n onResponseStart: <T extends RequestInstance>(callback: (details: RequestEventType<T>) => void): VoidFunction => {\n emitter.on(getResponseStartKey(), callback);\n return () => emitter.removeListener(getResponseStartKey(), callback);\n },\n onResponseStartByQueue: <T extends RequestInstance>(\n queryKey: string,\n callback: (details: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseStartByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getResponseStartByQueryKey(queryKey), callback);\n },\n onResponseStartById: <T extends RequestInstance>(\n requestId: string,\n callback: (details: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseStartByIdKey(requestId), callback);\n return () => emitter.removeListener(getResponseStartByIdKey(requestId), callback);\n },\n\n // Progress\n onUploadProgress: <T extends RequestInstance = RequestInstance>(\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getUploadProgressKey(), callback);\n return () => emitter.removeListener(getUploadProgressKey(), callback);\n },\n onUploadProgressByQueue: <T extends RequestInstance = RequestInstance>(\n queryKey: string,\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getUploadProgressByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getUploadProgressByQueryKey(queryKey), callback);\n },\n onUploadProgressById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getUploadProgressByIdKey(requestId), callback);\n return () => emitter.removeListener(getUploadProgressByIdKey(requestId), callback);\n },\n\n onDownloadProgress: <T extends RequestInstance = RequestInstance>(\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getDownloadProgressKey(), callback);\n return () => emitter.removeListener(getDownloadProgressKey(), callback);\n },\n onDownloadProgressByQueue: <T extends RequestInstance = RequestInstance>(\n queryKey: string,\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getDownloadProgressByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getDownloadProgressByQueryKey(queryKey), callback);\n },\n onDownloadProgressById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getDownloadProgressByIdKey(requestId), callback);\n return () => emitter.removeListener(getDownloadProgressByIdKey(requestId), callback);\n },\n\n // Response\n onResponse: <T extends RequestInstance>(callback: (data: RequestResponseEventType<T>) => void): VoidFunction => {\n emitter.on(getResponseKey(), callback);\n return () => emitter.removeListener(getResponseKey(), callback);\n },\n onResponseByCache: <T extends RequestInstance>(\n cacheKey: string,\n callback: (data: RequestResponseEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseByCacheKey(cacheKey), callback);\n return () => emitter.removeListener(getResponseByCacheKey(cacheKey), callback);\n },\n onResponseById: <T extends RequestInstance>(\n requestId: string,\n callback: (data: RequestResponseEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseByIdKey(requestId), callback);\n return () => emitter.removeListener(getResponseByIdKey(requestId), callback);\n },\n\n // Abort\n onAbort: <T extends RequestInstance = RequestInstance>(\n callback: (request: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getAbortKey(), callback);\n return () => emitter.removeListener(getAbortKey(), callback);\n },\n onAbortByKey: <T extends RequestInstance = RequestInstance>(\n abortKey: string,\n callback: (request: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getAbortByAbortKey(abortKey), callback);\n return () => emitter.removeListener(getAbortByAbortKey(abortKey), callback);\n },\n onAbortById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getAbortByIdKey(requestId), callback);\n return () => emitter.removeListener(getAbortByIdKey(requestId), callback);\n },\n\n // Retry\n /** Listen to every scheduled retry - the event carries the failed response, the retry number and its delay */\n onRetry: <T extends RequestInstance = RequestInstance>(\n callback: (data: RequestRetryEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRetryKey(), callback);\n return () => emitter.removeListener(getRetryKey(), callback);\n },\n /** Listen to the retries scheduled by the requests of the queue */\n onRetryByQueue: <T extends RequestInstance = RequestInstance>(\n queryKey: string,\n callback: (data: RequestRetryEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRetryByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getRetryByQueryKey(queryKey), callback);\n },\n /** Listen to the retries scheduled by one request */\n onRetryById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestRetryEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRetryByIdKey(requestId), callback);\n return () => emitter.removeListener(getRetryByIdKey(requestId), callback);\n },\n\n // Remove\n onRemove: <T extends RequestInstance = RequestInstance>(\n callback: (data: RequestRemovedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRemoveKey(), callback);\n return () => emitter.removeListener(getRemoveKey(), callback);\n },\n onRemoveByQueue: <T extends RequestInstance = RequestInstance>(\n queryKey: string,\n callback: (data: RequestRemovedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRemoveByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getRemoveByQueryKey(queryKey), callback);\n },\n onRemoveById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestRemovedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRemoveByIdKey(requestId), callback);\n return () => emitter.removeListener(getRemoveByIdKey(requestId), callback);\n },\n});\n","import type { ClientInstance } from \"client\";\nimport EventEmitter from \"events\";\nimport type { LogLevel, LoggerArgs, LoggerOptionsType, LoggerType, LoggerMethods } from \"managers\";\nimport { logger, logLevelOrder } from \"managers\";\n\n/**\n * This class is used across the Hyper Fetch library to provide unified logging system with necessary setup per each client.\n * We can set up the logging level based on available values. This manager enable to initialize the logging instance per individual module\n * like Client, Request etc. Which can give you better feedback on the logging itself.\n */\nexport class LoggerManager {\n logger: LoggerType;\n level: LogLevel;\n modules: string[] | undefined;\n\n public emitter = new EventEmitter();\n\n private client: Pick<ClientInstance, \"debug\">;\n\n constructor(private options?: LoggerOptionsType) {\n this.emitter?.setMaxListeners(1000);\n this.logger = this.options?.logger || logger;\n this.level = this.options?.level || \"warning\";\n this.modules = this.options?.modules;\n }\n\n setSeverity = (level: LogLevel) => {\n this.level = level;\n };\n\n setModules = (modules: string[] | undefined) => {\n this.modules = modules;\n };\n\n initialize = (client: Pick<ClientInstance, \"debug\">, module: string): LoggerMethods => {\n this.client = client;\n\n // Modules keep their logger methods for the whole lifetime. When they come from the logger manager of the client,\n // the logs have to follow the manager currently assigned to it - otherwise `client.setLogger()` would affect\n // only the modules initialized later.\n const getClientManager = () => (client as Partial<Pick<ClientInstance, \"loggerManager\">>).loggerManager;\n const isClientManager = getClientManager() === this;\n\n const log: LoggerType = (data) => {\n const clientManager = getClientManager();\n const manager = isClientManager && clientManager instanceof LoggerManager ? clientManager : this;\n manager.log(data, client);\n };\n\n return {\n error: (data) => log({ ...data, level: \"error\", module }),\n warning: (data) => log({ ...data, level: \"warning\", module }),\n info: (data) => log({ ...data, level: \"info\", module }),\n debug: (data) => log({ ...data, level: \"debug\", module }),\n };\n };\n\n private log = (data: LoggerArgs, client: Pick<ClientInstance, \"debug\"> = this.client) => {\n if (!client.debug) {\n return;\n }\n // Level is the least severe type of the logs to show - logs of this level and the more severe ones are printed\n if (logLevelOrder.indexOf(this.level) < logLevelOrder.indexOf(data.level)) {\n return;\n }\n if (this.modules && !this.modules.includes(data.module)) {\n return;\n }\n this.logger(data);\n };\n}\n","/* eslint-disable no-console */\nimport type { LoggerType } from \"managers\";\nimport { loggerColors, loggerStyles } from \"managers\";\n\nexport const getTime = () => {\n const d = new Date();\n return `${d.toLocaleTimeString()}`;\n};\n\nconst getModuleName = (data: Parameters<LoggerType>[0]) => {\n if (data.type === \"request\" || data.type === \"response\") {\n return `${data.extra.request.endpoint}`;\n }\n return `[${data.module}]`;\n};\n\n// Logger\nexport const logger: LoggerType = (log) => {\n const styles = loggerStyles[log.level];\n const color = loggerColors[log.level];\n const message = `%c[${getTime()}]%c${log.title}%c${getModuleName(log)}`;\n\n const style1 = `${styles}${color}font-weight:600;border-radius: 4px 0 0 4px;`;\n const style2 = `${styles}${color}font-weight:600;`;\n const style3 = `${styles}font-weight:normal;border-radius: 0 4px 4px 0;`;\n\n if (log.extra ? Object.keys(log.extra)?.length : false) {\n console.groupCollapsed(message, style1, style2, style3);\n console.log(log.extra);\n console.groupEnd();\n } else {\n console.log(message, styles);\n }\n};\n","import type { LogLevel } from \"./logger.manager.types\";\n\nexport const logLevelOrder: LogLevel[] = [\"error\", \"warning\", \"info\", \"debug\"];\n\nconst defaultStyles = \"padding:2px 5px;\";\n\nexport const loggerStyles: Record<LogLevel, string> = {\n error: `${defaultStyles};background:#db252520;`,\n warning: `${defaultStyles};background:#e1941e20;`,\n info: `${defaultStyles};background:#1e74e120;`,\n debug: `${defaultStyles};background:#00000020;`,\n};\n\nexport const loggerColors: Record<LogLevel, string> = {\n error: \"color:#ff3737;\",\n warning: \"color:#ffc107;\",\n info: \"color:#34a8ff;\",\n debug: \"color:#cccccc;\",\n};\n","import type { ResponseType } from \"adapter\";\nimport type { RequestInstance } from \"request\";\nimport type { ExtendRequest, ExtractClientAdapterType } from \"types\";\n\nimport type {\n ClientInstance,\n ClientMode,\n ClientModeOption,\n RequestInterceptorType,\n ResponseInterceptorType,\n} from \"./client.types\";\n\n/** Picks effective {@link ClientMode}: explicit override, else environment detection. */\nexport function resolveClientMode(modeOption: ClientModeOption | undefined): ClientMode {\n if (modeOption === \"client\" || modeOption === \"server\") {\n return modeOption;\n }\n\n const inBrowser = typeof window !== \"undefined\" && typeof document !== \"undefined\";\n if (inBrowser) {\n return \"client\";\n }\n\n return \"server\";\n}\n\nexport const interceptRequest = async (interceptors: RequestInterceptorType[], request: RequestInstance) => {\n let newRequest = request;\n if (!request.requestOptions.disableRequestInterceptors) {\n // eslint-disable-next-line no-restricted-syntax\n for (const interceptor of interceptors) {\n // Interceptors create a pipeline - each one receives the request returned by the previous one\n // eslint-disable-next-line no-await-in-loop\n newRequest = (await interceptor(newRequest)) as RequestInstance;\n if (!newRequest) {\n throw new Error(\"Request modifier must return request\");\n }\n }\n }\n return newRequest;\n};\n\nexport const interceptResponse = async <GlobalErrorType, Client extends ClientInstance>(\n interceptors: ResponseInterceptorType<Client>[],\n response: ResponseType<any, GlobalErrorType, ExtractClientAdapterType<Client>>,\n request: ExtendRequest<RequestInstance, { client: Client }>,\n) => {\n let newResponse = response;\n if (!request.requestOptions.disableResponseInterceptors) {\n // eslint-disable-next-line no-restricted-syntax\n for (const interceptor of interceptors) {\n // Interceptors create a pipeline - each one receives the response returned by the previous one\n // eslint-disable-next-line no-await-in-loop\n newResponse = await interceptor(newResponse, request);\n if (!newResponse) {\n throw new Error(\"Response modifier must return data\");\n }\n }\n }\n return newResponse;\n};\n","import type { AdapterInstance, ResponseType } from \"adapter\";\nimport { Cache } from \"cache\";\nimport type {\n ClientErrorType,\n ClientInstance,\n ClientMode,\n ClientOptionsType,\n RequestGenericType,\n RequestInterceptorType,\n ResponseInterceptorType,\n} from \"client\";\nimport { Dispatcher } from \"dispatcher\";\nimport type { HttpAdapterType } from \"http-adapter\";\nimport { parseResponse, HttpAdapter } from \"http-adapter\";\nimport type { LogLevel } from \"managers\";\nimport { AppManager, LoggerManager, RequestManager } from \"managers\";\nimport { resetOptimisticState } from \"optimistic\";\nimport type { PluginInstance, PluginMethodParameters, PluginMethods } from \"plugin\";\nimport type {\n ExtractEndpointPayloadType,\n ExtractEndpointResponseType,\n RequestInstance,\n RequestJSON,\n RequestOptionsType,\n} from \"request\";\nimport { getRequestKey, getSimpleKey, Request, scopeKey } from \"request\";\nimport type {\n EmptyTypes,\n TypeWithDefaults,\n ExtractAdapterMethodType,\n ExtractAdapterOptionsType,\n ExtractAdapterQueryParamsType,\n ExtractAdapterEndpointType,\n ExtractUnionAdapter,\n HydrateDataType,\n HydrationOptions,\n ExtractAdapterDefaultQueryParamsType,\n ExtractAdapterRequestOptionsType,\n} from \"types\";\nimport { getUniqueRequestId, throwOutsideLifecycle } from \"utils\";\n\nimport { interceptRequest, interceptResponse, resolveClientMode } from \"./client.utils\";\n\n/**\n * Response interceptors run when the adapter is already done, so nothing else can handle their failure.\n * A throwing or rejecting interceptor ends the request with the error response - the same way as failing request\n * interceptors do - instead of leaving it pending forever.\n */\nconst interceptResponseSafely = async <GlobalErrorType, Adapter extends AdapterInstance>({\n client,\n interceptors,\n response,\n request,\n}: {\n client: Client<any, Adapter>;\n interceptors: ResponseInterceptorType<ClientInstance>[];\n response: ResponseType<any, GlobalErrorType, Adapter>;\n request: RequestInstance;\n}): Promise<ResponseType<any, GlobalErrorType, Adapter>> => {\n try {\n return (await interceptResponse<GlobalErrorType, ClientInstance>(\n interceptors,\n response as ResponseType<any, GlobalErrorType, AdapterInstance>,\n request,\n )) as ResponseType<any, GlobalErrorType, Adapter>;\n } catch (error) {\n const { adapter } = client;\n client.logger.error({ title: \"Response interceptor failed\", type: \"system\", extra: { error, request } });\n\n return {\n data: null,\n error: adapter.unstable_internalErrorMapping(error as Parameters<Adapter[\"unstable_internalErrorMapping\"]>[0]),\n status: adapter.systemErrorStatus,\n success: false,\n extra: adapter.systemErrorExtra,\n requestTimestamp: response.requestTimestamp,\n responseTimestamp: response.responseTimestamp,\n };\n }\n};\n\n/**\n * **Client** is a class that allows you to configure the connection with the server and then use it to create\n * requests. It allows you to set global defaults for the requests configuration, query params configuration.\n * It is also orchestrator for all of the HyperFetch modules like Cache, Dispatcher, AppManager, LoggerManager,\n * RequestManager and more.\n */\nexport class Client<\n GlobalErrorType extends ClientErrorType = Error,\n Adapter extends AdapterInstance = HttpAdapterType,\n> {\n url: string;\n readonly mode: ClientMode;\n public debug: boolean;\n\n // Private\n unstable_onErrorCallbacks: ResponseInterceptorType<ClientInstance>[] = [];\n unstable_onSuccessCallbacks: ResponseInterceptorType<ClientInstance>[] = [];\n unstable_onResponseCallbacks: ResponseInterceptorType<ClientInstance>[] = [];\n unstable_onAuthCallbacks: RequestInterceptorType[] = [];\n unstable_onRequestCallbacks: RequestInterceptorType[] = [];\n\n // Managers\n loggerManager: LoggerManager = new LoggerManager();\n requestManager: RequestManager = new RequestManager();\n appManager: AppManager;\n\n // Config\n adapter: Adapter;\n cache: Cache<Adapter>;\n fetchDispatcher: Dispatcher<Adapter>;\n submitDispatcher: Dispatcher<Adapter>;\n isMockerEnabled = true;\n\n // Registered requests effect\n plugins: PluginInstance[] = [];\n\n /** @internal */\n unstable_abortKeyMapper: (request: RequestInstance) => string = getSimpleKey;\n\n /** @internal */\n unstable_cacheKeyMapper: (request: RequestInstance) => string = getRequestKey;\n\n /** @internal */\n unstable_queryKeyMapper: (request: RequestInstance) => string = getRequestKey;\n\n /** @internal */\n unstable_requestIdMapper: (request: RequestInstance) => string = getUniqueRequestId;\n\n // Logger\n logger = this.loggerManager.initialize(this, \"Client\");\n\n constructor(public options: ClientOptionsType<Client<GlobalErrorType, Adapter>>) {\n const { url, appManager, cache, fetchDispatcher, submitDispatcher, mode: modeOption } = this.options;\n this.url = url;\n this.mode = resolveClientMode(modeOption);\n this.adapter = HttpAdapter() as Adapter;\n\n this.appManager = appManager?.() || new AppManager();\n this.cache = cache?.() || new Cache();\n this.fetchDispatcher = fetchDispatcher?.() || new Dispatcher();\n this.submitDispatcher = submitDispatcher?.() || new Dispatcher();\n\n // IMPORTANT: Do not change initialization order as it's crucial for dependencies injection\n this.adapter.initialize(this);\n this.appManager.initialize();\n this.cache.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n this.fetchDispatcher.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n this.submitDispatcher.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n }\n\n /**\n * Set the base url used by the next requests - e.g. when switching tenants, regions or environments at runtime.\n * Cache keys don't include the base url, so data cached for the previous url stays in place unless you pass\n * `invalidate: true`. Pass `abort: true` to cancel the requests that are still in progress for the previous url.\n * @param url new base url\n * @param options.abort abort all ongoing requests\n * @param options.invalidate invalidate the cache (and requests aborted by `abort`), so active consumers refetch\n */\n setUrl = (url: string, options: { abort?: boolean; invalidate?: boolean } = {}): Client<GlobalErrorType, Adapter> => {\n if (url === this.url) {\n return this;\n }\n\n const { abort = false, invalidate = false } = options;\n const runningRequests = this.fetchDispatcher.getAllRunningRequests().map(({ request }) => request);\n\n this.url = url;\n\n if (abort) {\n this.requestManager.abortAll();\n }\n if (invalidate) {\n this.cache.invalidate();\n // Aborted requests never land in the cache, so the full invalidation above would not notify their consumers\n if (abort && runningRequests.length > 0) {\n this.cache.invalidate(runningRequests);\n }\n }\n\n return this;\n };\n\n /**\n * This method enables the logger usage and display the logs in console\n */\n setDebug = (enabled: boolean): Client<GlobalErrorType, Adapter> => {\n this.debug = enabled;\n return this;\n };\n\n /**\n * Set the logger severity of the messages displayed to the console\n */\n setLogLevel = (severity: LogLevel): Client<GlobalErrorType, Adapter> => {\n this.loggerManager.setSeverity(severity);\n return this;\n };\n\n /**\n * Set the new logger instance to the Client\n */\n setLogger = (callback: (Client: ClientInstance) => LoggerManager): Client<GlobalErrorType, Adapter> => {\n this.loggerManager = callback(this);\n this.logger = this.loggerManager.initialize(this, \"Client\");\n return this;\n };\n\n /**\n * Set globally if mocking should be enabled or disabled for all client requests.\n * @param isMockerEnabled\n */\n setEnableGlobalMocking = (isMockerEnabled: boolean) => {\n this.isMockerEnabled = isMockerEnabled;\n return this;\n };\n\n /**\n * Set custom http adapter to handle graphql, rest, firebase or others\n */\n setAdapter = <NewAdapter extends AdapterInstance>(adapter: NewAdapter): Client<GlobalErrorType, NewAdapter> => {\n this.adapter = adapter as unknown as Adapter;\n this.adapter.initialize(this);\n return this as unknown as Client<GlobalErrorType, NewAdapter>;\n };\n\n /**\n * Method of manipulating requests before sending the request. We can for example add custom header with token to the request which request had the auth set to true.\n */\n onAuth = (callback: RequestInterceptorType): Client<GlobalErrorType, Adapter> => {\n this.unstable_onAuthCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing listeners on auth.\n * */\n removeOnAuthInterceptors = (callbacks: RequestInterceptorType[]): Client<GlobalErrorType, Adapter> => {\n this.unstable_onAuthCallbacks = this.unstable_onAuthCallbacks.filter((callback) => !callbacks.includes(callback));\n return this;\n };\n\n /**\n * Method for intercepting error responses. It can be used for example to refresh tokens.\n */\n onError = <ErrorType = null>(\n callback: ResponseInterceptorType<ClientInstance, any, ErrorType | GlobalErrorType>,\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onErrorCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing listeners on error.\n * */\n removeOnErrorInterceptors = (\n callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[],\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onErrorCallbacks = this.unstable_onErrorCallbacks.filter((callback) => !callbacks.includes(callback));\n return this;\n };\n\n /**\n * Method for intercepting success responses.\n */\n onSuccess = <ErrorType = null>(\n callback: ResponseInterceptorType<ClientInstance, any, ErrorType | GlobalErrorType>,\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onSuccessCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing listeners on success.\n * */\n removeOnSuccessInterceptors = (\n callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[],\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onSuccessCallbacks = this.unstable_onSuccessCallbacks.filter(\n (callback) => !callbacks.includes(callback),\n );\n return this;\n };\n\n /**\n * Method of manipulating requests before sending the request.\n */\n onRequest = (callback: RequestInterceptorType): Client<GlobalErrorType, Adapter> => {\n this.unstable_onRequestCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing listeners on request.\n * */\n removeOnRequestInterceptors = (callbacks: RequestInterceptorType[]): Client<GlobalErrorType, Adapter> => {\n this.unstable_onRequestCallbacks = this.unstable_onRequestCallbacks.filter(\n (callback) => !callbacks.includes(callback),\n );\n return this;\n };\n\n /**\n * Method for intercepting any responses.\n */\n onResponse = <ErrorType = null>(\n callback: ResponseInterceptorType<ClientInstance, any, ErrorType | GlobalErrorType>,\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onResponseCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing response interceptors.\n * */\n removeOnResponseInterceptors = (\n callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[],\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onResponseCallbacks = this.unstable_onResponseCallbacks.filter(\n (callback) => !callbacks.includes(callback),\n );\n return this;\n };\n\n /**\n * Add persistent plugins which trigger on the request lifecycle\n */\n addPlugin = (plugin: PluginInstance) => {\n this.plugins.push(plugin);\n\n plugin.initialize(this);\n plugin.trigger(\"onMount\", { client: this });\n\n return this;\n };\n\n /**\n * Remove plugins from Client\n */\n removePlugin = (plugin: PluginInstance) => {\n const pluginCount = this.plugins.length;\n this.plugins = this.plugins.filter((p) => p !== plugin);\n\n if (this.plugins.length !== pluginCount) {\n plugin.trigger(\"onUnmount\", { client: this });\n }\n\n return this;\n };\n\n triggerPlugins = <Key extends keyof PluginMethods<Client>>(key: Key, data: PluginMethodParameters<Key, Client>) => {\n if (this.plugins.length === 0) {\n return this;\n }\n\n this.plugins.forEach((plugin) => {\n try {\n plugin.trigger(key, data);\n } catch (error) {\n // Plugins only observe the lifecycle - a failing one can't break the requests, the cache or other plugins\n this.logger.error({\n title: `Plugin \"${plugin.name}\" failed`,\n type: \"system\",\n extra: { plugin: plugin.name, method: key, error },\n });\n throwOutsideLifecycle(error);\n }\n });\n\n return this;\n };\n\n /**\n * Key setters\n */\n\n /** Set a custom mapper that generates the abort key used to cancel in-flight requests. */\n setAbortKeyMapper = (callback: (request: RequestInstance) => string) => {\n this.unstable_abortKeyMapper = callback;\n return this;\n };\n /** Set a custom mapper that generates the cache key used to store and retrieve cached responses. */\n setCacheKeyMapper = (callback: (request: RequestInstance) => string) => {\n this.unstable_cacheKeyMapper = callback;\n return this;\n };\n /** Set a custom mapper that generates the query key used to identify requests in the dispatcher queue. */\n setQueryKeyMapper = (callback: (request: RequestInstance) => string) => {\n this.unstable_queryKeyMapper = callback;\n return this;\n };\n /** Set a custom mapper that generates the unique request ID for deduplication and tracking. */\n setRequestIdMapper = (callback: (request: RequestInstance) => string) => {\n this.unstable_requestIdMapper = callback;\n return this;\n };\n\n /**\n * Helper used by http adapter to apply the modifications on response error\n * @private\n */\n unstable_modifyAuth = async (request: RequestInstance) => interceptRequest(this.unstable_onAuthCallbacks, request);\n\n /**\n * Private helper to run async pre-request processing\n * @private\n */\n unstable_modifyRequest = async (request: RequestInstance) =>\n interceptRequest(this.unstable_onRequestCallbacks, request);\n\n /**\n * Private helper to run async on-error response processing\n * @private\n */\n unstable_modifyErrorResponse = async (\n response: ResponseType<any, GlobalErrorType, Adapter>,\n request: RequestInstance,\n ) =>\n interceptResponseSafely<GlobalErrorType, Adapter>({\n client: this,\n interceptors: this.unstable_onErrorCallbacks,\n response,\n request,\n });\n\n /**\n * Private helper to run async on-success response processing\n * @private\n */\n unstable_modifySuccessResponse = async (\n response: ResponseType<any, GlobalErrorType, Adapter>,\n request: RequestInstance,\n ) =>\n interceptResponseSafely<GlobalErrorType, Adapter>({\n client: this,\n interceptors: this.unstable_onSuccessCallbacks,\n response,\n request,\n });\n\n /**\n * Private helper to run async response processing\n * @private\n */\n unstable_modifyResponse = async (response: ResponseType<any, GlobalErrorType, Adapter>, request: RequestInstance) =>\n interceptResponseSafely<GlobalErrorType, Adapter>({\n client: this,\n interceptors: this.unstable_onResponseCallbacks,\n response,\n request,\n });\n\n /**\n * Reconstruct a Request class instance from its serialized JSON form.\n * Useful when dispatcher storage serializes queue data (e.g. MMKV, AsyncStorage)\n * and the deserialized request loses its class identity.\n */\n fromJSON = <RequestProperties extends RequestGenericType<ExtractAdapterQueryParamsType<Adapter>> = {}>(\n json: RequestJSON<RequestInstance>,\n ) => {\n type DefaultQueryParams = ExtractAdapterDefaultQueryParamsType<Adapter>;\n\n type Response = TypeWithDefaults<RequestProperties, \"response\", undefined>;\n type Payload = TypeWithDefaults<RequestProperties, \"payload\", undefined>;\n type LocalError = TypeWithDefaults<RequestProperties, \"error\", GlobalErrorType>;\n type QueryParams = TypeWithDefaults<RequestProperties, \"queryParams\", DefaultQueryParams, never>;\n type Endpoint = TypeWithDefaults<RequestProperties, \"endpoint\", string>;\n\n return Request.fromJSON(this as unknown as ClientInstance, json) as unknown as Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint extends string ? Endpoint : string,\n Client<GlobalErrorType, Adapter>\n >;\n };\n\n /**\n * Clears the Client instance and remove all listeners on it's dependencies\n */\n clear = () => {\n const { appManager, cache, fetchDispatcher, submitDispatcher } = this.options;\n\n // Queued and ongoing requests are removed while their listeners still exist - it aborts the ongoing ones\n // and resolves the pending `send()` promises, which otherwise would never settle\n [this.fetchDispatcher, this.submitDispatcher].forEach((dispatcher) => {\n dispatcher.getQueuesKeys().forEach((queryKey) => {\n dispatcher.getQueue(queryKey).requests.forEach(({ request, requestId }) => {\n dispatcher.delete(queryKey, requestId, scopeKey(request.abortKey, request.scope));\n });\n });\n });\n // Requests sent outside of the dispatchers\n this.requestManager.abortAll();\n\n this.requestManager.abortControllers.clear();\n resetOptimisticState(this);\n this.fetchDispatcher.clear();\n this.submitDispatcher.clear();\n this.cache.clear();\n\n this.requestManager.emitter.removeAllListeners();\n this.fetchDispatcher.emitter.removeAllListeners();\n this.submitDispatcher.emitter.removeAllListeners();\n this.cache.emitter.removeAllListeners();\n this.appManager.unmount();\n // App manager can be shared between the clears, so the listeners of the removed modules have to go away\n this.appManager.emitter.removeAllListeners();\n\n this.cache = cache?.() || new Cache();\n this.appManager = appManager?.() || new AppManager();\n this.fetchDispatcher = fetchDispatcher?.() || new Dispatcher();\n this.submitDispatcher = submitDispatcher?.() || new Dispatcher();\n\n // DO NOT CHANGE INITIALIZATION ORDER\n this.appManager.initialize();\n this.cache.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n this.fetchDispatcher.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n this.submitDispatcher.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n };\n\n /**\n * Hydrate your SSR cache data\n * @param hydrationData\n * @param options\n */\n hydrate = (\n hydrationData: (HydrateDataType | EmptyTypes)[],\n options?: Partial<HydrationOptions> | ((item: HydrateDataType) => Partial<HydrationOptions>),\n ) => {\n hydrationData?.forEach((item) => {\n if (!item) {\n return;\n }\n\n const { cacheKey, scope, response, ...fallbackOptions } = item;\n const defaults = {\n cache: true,\n override: true,\n } satisfies Partial<HydrationOptions>;\n const config =\n typeof options === \"function\"\n ? { ...defaults, ...fallbackOptions, ...options(item) }\n : { ...defaults, ...fallbackOptions, ...options };\n\n if (!config.override) {\n const cachedData = this.cache.get(scopeKey(cacheKey, scope));\n if (cachedData) {\n return;\n }\n }\n\n const parsedData = parseResponse(response);\n this.cache.set(\n { ...config, cacheKey, scope },\n {\n // Hydrated responses did not go through the dispatcher, so the request details get their neutral values\n retries: 0,\n isCanceled: false,\n isOffline: false,\n willRetry: false,\n addedTimestamp: parsedData?.requestTimestamp,\n triggerTimestamp: parsedData?.requestTimestamp,\n ...parsedData,\n hydrated: true,\n },\n );\n });\n };\n\n /**\n * Create requests based on the Client setup\n *\n * @template Response Your response\n */\n createRequest = <RequestProperties extends RequestGenericType<ExtractAdapterQueryParamsType<Adapter>> = {}>(\n /**\n * `createRequest` must be initialized twice(currying).\n *\n * ✅ Good:\n * ```ts\n * const request = createRequest<RequestProperties>()(params)\n * ```\n * ⛔ Bad:\n * ```ts\n * const request = createRequest<RequestProperties>(params)\n * ```\n *\n * We are using currying to achieve auto generated types for the endpoint string.\n *\n * This solution will be removed once https://github.com/microsoft/TypeScript/issues/10571 get resolved.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _USE_DOUBLE_INITIALIZATION?: never,\n ) => {\n type DefaultQueryParams = ExtractAdapterDefaultQueryParamsType<Adapter>;\n\n type LocalError = TypeWithDefaults<RequestProperties, \"error\", GlobalErrorType>;\n /** we pass never to prevent the type from being empty, but we allow it to be undefined (optional) */\n type QueryParams = TypeWithDefaults<RequestProperties, \"queryParams\", DefaultQueryParams, never>;\n\n return <\n EndpointType extends ExtractAdapterEndpointType<Adapter>,\n AdapterOptions extends ExtractAdapterOptionsType<Adapter>,\n MethodType extends ExtractAdapterMethodType<Adapter>,\n >(\n params: RequestOptionsType<EndpointType, AdapterOptions, MethodType> & ExtractAdapterRequestOptionsType<Adapter>,\n ) => {\n type Endpoint = TypeWithDefaults<RequestProperties, \"endpoint\", EndpointType>;\n // A typed endpoint (like a TypedDocumentNode) fills the response and the payload the generics leave out\n type Response = TypeWithDefaults<RequestProperties, \"response\", ExtractEndpointResponseType<EndpointType>>;\n type Payload = TypeWithDefaults<RequestProperties, \"payload\", ExtractEndpointPayloadType<EndpointType>>;\n\n const endpoint = this.adapter.unstable_endpointMapper(params.endpoint);\n\n // Splitting this type prevents \"Type instantiation is excessively deep and possibly infinite\" error\n type ExtractedAdapter = ExtractUnionAdapter<\n Adapter,\n {\n method: MethodType;\n options: AdapterOptions;\n queryParams: QueryParams;\n }\n >;\n type ExtractedAdapterType = ExtractedAdapter extends EmptyTypes ? Adapter : ExtractedAdapter;\n\n const mappedParams: RequestOptionsType<\n Endpoint extends string ? Endpoint : typeof endpoint,\n AdapterOptions,\n MethodType\n > = {\n ...params,\n endpoint: String(endpoint) as Endpoint extends string ? Endpoint : typeof endpoint,\n };\n\n const request = new Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint extends string ? Endpoint : typeof endpoint,\n Client<GlobalErrorType, ExtractedAdapterType>\n >(this as unknown as Client<GlobalErrorType, ExtractedAdapterType>, mappedParams);\n\n this.plugins.forEach((plugin) => plugin.trigger(\"onRequestCreate\", { request }));\n\n return request;\n };\n };\n}\n","export const stringifyDefaultOptions = {\n strict: true,\n encode: true,\n arrayFormat: \"bracket\",\n arraySeparator: \"|\",\n sort: false,\n skipNull: true,\n skipEmptyString: true,\n} as const;\n","import type { ClientErrorType, ClientOptionsType } from \"client\";\nimport { Client } from \"client\";\nimport type { HttpAdapterType } from \"http-adapter\";\nimport type { TypeWithDefaults } from \"types\";\n\nexport type ClientGenericType = {\n error?: ClientErrorType;\n};\n\nexport function createClient<ClientProperties extends ClientGenericType = {}>(\n options: ClientOptionsType<Client<NonNullable<TypeWithDefaults<ClientProperties, \"error\", Error>>>>,\n): Client<NonNullable<TypeWithDefaults<ClientProperties, \"error\", Error>>, HttpAdapterType> {\n return new Client<NonNullable<TypeWithDefaults<ClientProperties, \"error\", Error>>, HttpAdapterType>(options);\n}\n","import type { ClientInstance } from \"client\";\nimport type { RequestInstance, RetryTimeType } from \"request\";\nimport { Request } from \"request\";\nimport type {\n ExtractEndpointType,\n ExtractResponseType,\n ExtractPayloadType,\n ExtractQueryParamsType,\n ExtractLocalErrorType,\n ExtractHasPayloadType,\n ExtractHasParamsType,\n ExtractHasQueryParamsType,\n ExtractMutationContextType,\n} from \"types\";\n\nexport type RecursiveSchemaType = Record<\n string, // for example users / $userId / posts / $postId\n any\n>;\n\n/**\n * Recursively walks a schema and rebuilds every `Request` leaf with the SDK's actual client\n * type injected into the `Client` generic slot. Lets users omit `client` from their\n * `RequestModel<{...}>` declarations - the SDK fills it in from the client passed to\n * `createSdk(client)`.\n *\n * Non-Request leaves (primitive values, plain types) are passed through unchanged. Nested\n * schema objects are recursed into. Depth is guarded at 10 levels to keep the type checker\n * within reasonable bounds.\n */\n/**\n * Keys every request has at runtime - its public properties and the private ones. Below the top level, the SDK reads\n * such a key from the request instead of treating it as a path segment or procedure name.\n */\ntype SdkReservedKey = keyof RequestInstance | \"updatedAbortKey\" | \"updatedCacheKey\" | \"updatedQueryKey\" | \"paramsMapper\";\n\n/**\n * Type of a schema key the SDK can't reach, because every request has a property with the same name - for example a\n * procedure called `send`. Using it fails to compile instead of crashing at runtime. Rename the key, or set the path\n * with a `$`-prefixed key.\n */\nexport type SdkReservedKeyError<Key extends PropertyKey> = {\n __sdkError: `\"${Key & string}\" is a property of every request, so the SDK can't reach a path or procedure with this name. Rename it in the schema.`;\n};\n\nexport type InjectClient<T, TClient extends ClientInstance, Depth extends unknown[] = []> = Depth[\"length\"] extends 10\n ? T\n : T extends RequestInstance\n ? Request<\n ExtractResponseType<T>,\n ExtractPayloadType<T>,\n ExtractQueryParamsType<T>,\n ExtractLocalErrorType<T>,\n ExtractEndpointType<T> extends string ? ExtractEndpointType<T> : string,\n TClient,\n ExtractHasPayloadType<T> extends boolean ? ExtractHasPayloadType<T> : false,\n ExtractHasParamsType<T> extends boolean ? ExtractHasParamsType<T> : false,\n ExtractHasQueryParamsType<T> extends boolean ? ExtractHasQueryParamsType<T> : false,\n ExtractMutationContextType<T>\n >\n : T extends Record<string, any>\n ? {\n // The top level is not a request, so only the nested keys can clash with the request properties\n [K in keyof T]: Depth[\"length\"] extends 0\n ? InjectClient<T[K], TClient, [...Depth, unknown]>\n : K extends SdkReservedKey\n ? SdkReservedKeyError<K>\n : InjectClient<T[K], TClient, [...Depth, unknown]>;\n }\n : T;\n\n/**\n * Per-request defaults that can be applied via SDK configuration.\n * These mirror the chainable setters on Request (headers, cache, retry, etc.).\n */\nexport type SdkRequestDefaults = {\n headers?: HeadersInit;\n auth?: boolean;\n cache?: boolean;\n cacheTime?: number;\n staleTime?: number;\n retry?: number;\n retryTime?: RetryTimeType;\n cancelable?: boolean;\n queued?: boolean;\n offline?: boolean;\n deduplicate?: boolean;\n deduplicateTime?: number | null;\n structuralSharing?: boolean;\n};\n\n/**\n * Configuration value: either a static property bag or a function that receives\n * the request and returns a modified request (full access to every Request setter).\n */\nexport type SdkConfigurationValue = SdkRequestDefaults | ((request: RequestInstance) => RequestInstance);\n\n/**\n * Recursively extracts all endpoint strings from an SDK schema type.\n * Leaf nodes (keys starting with $) are RequestInstance — extract endpoint from those.\n * Other keys are nested schema segments to recurse into.\n */\ntype ExtractSdkEndpoints<T, Depth extends unknown[] = []> = Depth[\"length\"] extends 10\n ? never\n : {\n [K in keyof T]: K extends `$${string}`\n ? T[K] extends RequestInstance\n ? ExtractEndpointType<T[K]>\n : never\n : T[K] extends Record<string, any>\n ? ExtractSdkEndpoints<T[K], [...Depth, unknown]>\n : never;\n }[keyof T];\n\n/**\n * Recursively extracts dot-path accessor keys from an SDK schema.\n * These mirror the SDK property chain: \"users.$get\", \"users.$userId.$get\", etc.\n */\ntype ExtractSdkPaths<T, Prefix extends string = \"\", Depth extends unknown[] = []> = Depth[\"length\"] extends 10\n ? never\n : {\n [K in keyof T & string]: T[K] extends RequestInstance\n ? `${Prefix}${K}`\n : T[K] extends Record<string, any>\n ? ExtractSdkPaths<T[K], `${Prefix}${K}.`, [...Depth, unknown]>\n : never;\n }[keyof T & string];\n\n/**\n * Builds the set of valid configuration keys from an SDK schema:\n * - \"*\" (global wildcard)\n * - exact endpoint paths extracted from RequestInstance nodes (group keys)\n * - wildcard patterns like \"/users/*\" (group keys)\n * - dot-path accessor keys like \"users.$get\" (method-specific keys)\n */\ntype SdkConfigurationKeys<Schema extends RecursiveSchemaType> =\n | \"*\"\n | ExtractSdkEndpoints<Schema>\n | `${ExtractSdkEndpoints<Schema> & string}/*`\n | ExtractSdkPaths<Schema>;\n\n/**\n * Maps endpoint paths, wildcard patterns, or dot-path accessor keys to request defaults.\n * Keys are validated against the SDK schema.\n *\n * Values can be:\n * - A plain `SdkRequestDefaults` object (shorthand for common settings)\n * - A function `(request) => request` for full access to every Request setter\n */\nexport type SdkConfigurationMap<Schema extends RecursiveSchemaType = RecursiveSchemaType> = Partial<\n Record<SdkConfigurationKeys<Schema>, SdkConfigurationValue>\n>;\n\nexport type CreateSdkOptions<Schema extends RecursiveSchemaType = RecursiveSchemaType> = {\n /** @default true */\n camelCaseToKebabCase?: boolean;\n /**\n * URL segment of a schema key, when it differs from the key - for example `{ findByStatus: \"findByStatus\" }` keeps\n * the camelCase segment that `camelCaseToKebabCase` would turn into `find-by-status`. Mapped keys are not converted.\n * SDKs generated by the CLI fill it from the paths of the API schema.\n */\n pathSegments?: Record<string, string>;\n /** @default (method) => method.toUpperCase() */\n methodTransform?: (method: string) => string;\n /** Per-endpoint request defaults */\n defaults?: SdkConfigurationMap<Schema>;\n};\n\nconst OPTIONAL_REQUEST_FIELDS = Request.OPTIONAL_FIELDS;\n\nconst getMethod = (key: string, options?: CreateSdkOptions<any>) => {\n const { methodTransform = (method: string) => method.toUpperCase() } = options ?? {};\n return methodTransform(key);\n};\n\nconst endpointMatchesPattern = (endpoint: string, pattern: string): boolean => {\n if (pattern === \"*\") {return true;}\n if (pattern === endpoint) {return true;}\n // Simple wildcard: \"/users/*\" matches \"/users/:userId\", \"/users/:userId/posts\", etc.\n if (pattern.endsWith(\"/*\")) {\n const prefix = pattern.slice(0, -1);\n return endpoint.startsWith(prefix) || endpoint === prefix.slice(0, -1);\n }\n return false;\n};\n\nconst isDotPath = (key: string): boolean => {\n return key.includes(\".\") && !key.startsWith(\"/\");\n};\n\nconst applyObjectDefaults = (request: RequestInstance, config: SdkRequestDefaults): RequestInstance => {\n let result = request;\n if (config.headers) {result = result.setHeaders(config.headers);}\n if (config.auth !== undefined) {result = result.setAuth(config.auth);}\n if (config.cache !== undefined) {result = result.setCache(config.cache);}\n if (config.cacheTime !== undefined) {result = result.setCacheTime(config.cacheTime);}\n if (config.staleTime !== undefined) {result = result.setStaleTime(config.staleTime);}\n if (config.retry !== undefined) {result = result.setRetry(config.retry);}\n if (config.retryTime !== undefined) {result = result.setRetryTime(config.retryTime);}\n if (config.cancelable !== undefined) {result = result.setCancelable(config.cancelable);}\n if (config.queued !== undefined) {result = result.setQueued(config.queued);}\n if (config.offline !== undefined) {result = result.setOffline(config.offline);}\n if (config.deduplicate !== undefined) {result = result.setDeduplicate(config.deduplicate);}\n if (config.deduplicateTime !== undefined && config.deduplicateTime !== null) {\n result = result.setDeduplicateTime(config.deduplicateTime);\n }\n if (config.structuralSharing !== undefined) {\n result = result.setStructuralSharing(config.structuralSharing);\n }\n return result;\n};\n\nconst applyDefaults = (\n request: RequestInstance,\n context: { endpoint: string; sdkPath: string; defaults?: Partial<Record<string, SdkConfigurationValue>> },\n): RequestInstance => {\n const { endpoint, sdkPath, defaults } = context;\n if (!defaults) {return request;}\n\n let result = request;\n const entries = Object.entries(defaults);\n\n // Sort: \"*\" first, then endpoint groups (start with \"/\"), then dot-path (method-specific) last\n const globalEntries: [string, SdkConfigurationValue][] = [];\n const groupEntries: [string, SdkConfigurationValue][] = [];\n const pathEntries: [string, SdkConfigurationValue][] = [];\n\n for (let i = 0; i < entries.length; i += 1) {\n const [key, value] = entries[i];\n if (!value) {continue;}\n const entry: [string, SdkConfigurationValue] = [key, value];\n if (entry[0] === \"*\") {\n globalEntries.push(entry);\n } else if (isDotPath(entry[0])) {\n pathEntries.push(entry);\n } else {\n groupEntries.push(entry);\n }\n }\n\n const sorted = [...globalEntries, ...groupEntries, ...pathEntries];\n\n for (let i = 0; i < sorted.length; i += 1) {\n const [pattern, config] = sorted[i];\n\n let matches = false;\n if (isDotPath(pattern)) {\n matches = pattern === sdkPath;\n } else {\n matches = endpointMatchesPattern(endpoint, pattern);\n }\n\n if (matches) {\n if (typeof config === \"function\") {\n result = config(result);\n } else {\n result = applyObjectDefaults(result, config);\n }\n }\n }\n\n return result;\n};\n\nconst createRecursiveProxy = (\n client: ClientInstance,\n context: { path: string[]; sdkKeys: string[]; options?: CreateSdkOptions<any> },\n): any => {\n const { path, sdkKeys, options } = context;\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n return new Proxy(() => {}, {\n get: (_target, key: string) => {\n if (typeof key === \"symbol\" || key === \"inspect\") {\n return;\n }\n\n // Check if this is a method (starts with $) or a path segment\n let isMethod = false;\n let methodName = key;\n let pathSegment = key;\n\n if (key.startsWith(\"$\")) {\n isMethod = true;\n methodName = key.slice(1);\n pathSegment = `:${key.slice(1)}`;\n } else if (options?.pathSegments && Object.prototype.hasOwnProperty.call(options.pathSegments, key)) {\n pathSegment = options.pathSegments[key];\n } else if (options?.camelCaseToKebabCase) {\n pathSegment = key.replaceAll(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n }\n\n // Build the sdk dot-path for method-specific configuration matching\n const currentSdkKeys = [...sdkKeys, key];\n const sdkPath = currentSdkKeys.join(\".\");\n\n // Always create a request assuming this is a method call\n const endpoint = `/${path.join(\"/\")}`;\n const method = getMethod(isMethod ? methodName : key, options);\n let request: RequestInstance = client.createRequest()({ endpoint, method });\n request = applyDefaults(request, { endpoint, sdkPath, defaults: options?.defaults });\n\n // But also, assume the key is a new path segment for a deeper call\n const newPath = [...path, pathSegment];\n const deeperProxy = createRecursiveProxy(client, { path: newPath, sdkKeys: currentSdkKeys, options });\n\n // Return a new proxy that wraps both the request and the deeper proxy\n return new Proxy(request, {\n get: (reqTarget, reqKey: string) => {\n // If the property exists on the request instance (like .send(), .setParams()), return it.\n // Optional fields are checked by name as well: transpilers that compile class\n // properties in loose mode (Metro on React Native) drop uninitialized field\n // declarations, and falling through to the deeper proxy would hand callers a\n // truthy path proxy where they expect undefined.\n if (reqKey in reqTarget || (OPTIONAL_REQUEST_FIELDS as readonly string[]).includes(reqKey)) {\n return reqTarget[reqKey as keyof typeof reqTarget];\n }\n // Otherwise, it's a deeper path, so delegate to the deeper proxy.\n return deeperProxy[reqKey];\n },\n });\n },\n });\n};\n\n/**\n * The fully-resolved SDK instance type returned by `createSdk`.\n *\n * The schema is rewritten via {@link InjectClient} so every `Request` leaf carries the\n * actual client type passed to `createSdk(client)` - users do not need to repeat\n * `client: AppClient` in every `RequestModel<{...}>` declaration.\n */\nexport type SdkInstance<\n Schema extends RecursiveSchemaType,\n TClient extends ClientInstance = ClientInstance,\n> = InjectClient<Schema, TClient> & {\n /**\n * Apply request defaults to the SDK. Returns a new SDK instance with the configuration applied.\n * Use \"*\" to match all endpoints, or specific endpoint strings / wildcard patterns.\n */\n $configure: (defaults: SdkConfigurationMap<Schema>) => SdkInstance<Schema, TClient>;\n};\n\nexport const createSdk = <Client extends ClientInstance, RecursiveSchema extends RecursiveSchemaType>(\n client: Client,\n options?: CreateSdkOptions<RecursiveSchema>,\n): SdkInstance<RecursiveSchema, Client> => {\n const {\n camelCaseToKebabCase = true,\n methodTransform = (method: string) => method.toUpperCase(),\n ...rest\n } = options ?? {};\n\n const mergedOptions: CreateSdkOptions<RecursiveSchema> = { camelCaseToKebabCase, methodTransform, ...rest };\n // Break inference for TypeDoc / tsserver (TS2589) — runtime value is unchanged.\n const proxy = createRecursiveProxy(client, { path: [], sdkKeys: [], options: mergedOptions as never });\n\n return new Proxy(proxy, {\n get: (target, key: string) => {\n if (key === \"$configure\") {\n return (defaults: SdkConfigurationMap<RecursiveSchema>) => {\n const existingDefaults = mergedOptions.defaults || {};\n return createSdk<Client, RecursiveSchema>(client, {\n ...mergedOptions,\n defaults: { ...existingDefaults, ...defaults } as SdkConfigurationMap<RecursiveSchema>,\n });\n };\n }\n return target[key];\n },\n }) as SdkInstance<RecursiveSchema, Client>;\n};\n\n/**\n * Type-safe factory for creating SDK configuration maps.\n *\n * @example\n * const config = createConfiguration<MySdkSchema>()({ \"*\": { retry: 3 } })\n */\nexport const createConfiguration = <Schema extends RecursiveSchemaType>() => {\n return (defaults: SdkConfigurationMap<Schema>): SdkConfigurationMap<Schema> => defaults;\n};\n","import type { RequestInstance } from \"request\";\nimport { stringifyKey } from \"request/request.utils\";\n\nimport type { CachedInfinitePage, PaginationConfig, PaginationMode, PaginationPageContext } from \"./infinite.types\";\n\nconst isEmptyCursor = (value: unknown) => value === null || value === undefined || value === \"\";\n\nconst toNumber = (value: unknown): number | undefined => {\n if (value === null || value === undefined || value === \"\") {\n return undefined;\n }\n const number = Number(value);\n return Number.isFinite(number) ? number : undefined;\n};\n\n/**\n * Tells how the list is paged. Throws for a missing or incomplete pagination, because a list without it\n * would silently fetch the same page forever.\n */\nexport const getPaginationMode = (pagination: PaginationConfig): PaginationMode => {\n if (pagination?.cursor) {\n if (!pagination.next) {\n throw new Error('Cursor pagination requires the \"next\" option');\n }\n return \"cursor\";\n }\n if (pagination?.offset) {\n return \"offset\";\n }\n if (pagination?.page) {\n return \"page\";\n }\n throw new Error('Infinite requests require the \"pagination\" option with a \"page\", \"offset\" or \"cursor\" field');\n};\n\nconst getPagingField = (pagination: PaginationConfig) => {\n return (pagination.cursor ?? pagination.offset ?? pagination.page) as string;\n};\n\nconst getSourceValues = (request: RequestInstance, pagination: PaginationConfig): Record<string, unknown> => {\n const values = request[pagination.in ?? \"queryParams\"];\n return values && typeof values === \"object\" ? (values as Record<string, unknown>) : {};\n};\n\nconst getPageLimit = (request: RequestInstance, pagination: PaginationConfig) => {\n if (!pagination.limit) {\n return;\n }\n const limit = toNumber(getSourceValues(request, pagination)[pagination.limit]);\n return limit && limit > 0 ? limit : undefined;\n};\n\n/**\n * The value the list starts from: what the request already holds, otherwise the first page.\n */\nexport const getInitialPageParam = (request: RequestInstance, pagination: PaginationConfig): unknown => {\n const mode = getPaginationMode(pagination);\n const value = getSourceValues(request, pagination)[getPagingField(pagination)];\n\n if (mode === \"cursor\") {\n return isEmptyCursor(value) ? undefined : value;\n }\n return toNumber(value) ?? (mode === \"page\" ? 1 : 0);\n};\n\n// Lists numbered from zero say so by starting at zero, any other start means numbering from one\nconst getFirstPageNumber = (request: RequestInstance, pagination: PaginationConfig) => {\n return getInitialPageParam(request, pagination) === 0 ? 0 : 1;\n};\n\nconst setPagingValue = (request: RequestInstance, pagination: PaginationConfig, value: unknown): RequestInstance => {\n const values = { ...getSourceValues(request, pagination), [getPagingField(pagination)]: value };\n\n switch (pagination.in) {\n case \"params\": {\n return request.setParams(values as any) as RequestInstance;\n }\n case \"payload\": {\n return request.setPayload(values as any) as RequestInstance;\n }\n default: {\n return request.setQueryParams(values as any) as RequestInstance;\n }\n }\n};\n\nconst keyDependencies = new WeakMap<RequestInstance, { cacheKey: boolean; queryKey: boolean }>();\n\n/**\n * Generated keys contain the query params, so usually every page has its own. A custom key, or paging inside\n * the payload, gives all the pages the same key - they would overwrite each other in one cache slot.\n */\nconst getKeyDependencies = (request: RequestInstance, pagination: PaginationConfig) => {\n let dependencies = keyDependencies.get(request);\n if (!dependencies) {\n const first = setPagingValue(request, pagination, \"__hyper_fetch_page_a__\");\n const second = setPagingValue(request, pagination, \"__hyper_fetch_page_b__\");\n dependencies = {\n cacheKey: first.cacheKey !== second.cacheKey,\n queryKey: first.queryKey !== second.queryKey,\n };\n keyDependencies.set(request, dependencies);\n }\n return dependencies;\n};\n\n/**\n * Creates the request of a single page. Generated keys are left untouched, so a page shares its cache\n * with any other request for the same data.\n */\nexport const getPageRequest = <R extends RequestInstance>(\n request: R,\n pagination: PaginationConfig,\n param: unknown,\n): R => {\n if (param === undefined) {\n return request;\n }\n\n const dependencies = getKeyDependencies(request, pagination);\n let page = setPagingValue(request, pagination, param);\n\n if (!dependencies.cacheKey) {\n page = page.setCacheKey(`${page.cacheKey}_${stringifyKey(param)}`) as RequestInstance;\n }\n if (!dependencies.queryKey) {\n page = page.setQueryKey(`${page.queryKey}_${stringifyKey(param)}`) as RequestInstance;\n }\n return page as R;\n};\n\nconst getCallbackContext = ({ data, param, pages }: PaginationPageContext) => ({ data, param, pages });\n\nconst readOption = (option: unknown, context: PaginationPageContext): unknown => {\n if (typeof option === \"function\") {\n return option(getCallbackContext(context));\n }\n return typeof option === \"string\" ? context.data?.[option] : undefined;\n};\n\n/**\n * Items of a single page\n */\nexport const getPageItems = (context: PaginationPageContext): unknown[] => {\n const { pagination, data } = context;\n const items = pagination.items === undefined ? data : readOption(pagination.items, context);\n return Array.isArray(items) ? items : [];\n};\n\n/**\n * Size of the whole list, when the pagination declares it\n */\nexport const getPageTotal = (context: PaginationPageContext): number | null => {\n return toNumber(readOption(context.pagination.total, context)) ?? null;\n};\n\n/**\n * Paging value of the page after the given one\n */\nexport const getNextPageParam = (context: PaginationPageContext): unknown => {\n const { request, pagination, param } = context;\n const mode = getPaginationMode(pagination);\n\n if (mode === \"cursor\") {\n const cursor = readOption(pagination.next, context);\n return isEmptyCursor(cursor) ? undefined : cursor;\n }\n if (mode === \"page\") {\n return Number(param) + 1;\n }\n return Number(param) + (getPageLimit(request, pagination) ?? getPageItems(context).length);\n};\n\n/**\n * Paging value of the page before the given one\n */\nexport const getPreviousPageParam = (context: PaginationPageContext): unknown => {\n const { request, pagination, param } = context;\n const mode = getPaginationMode(pagination);\n\n if (mode === \"cursor\") {\n const cursor = readOption(pagination.previous, context);\n return isEmptyCursor(cursor) ? undefined : cursor;\n }\n if (mode === \"page\") {\n const previous = Number(param) - 1;\n return previous >= getFirstPageNumber(request, pagination) ? previous : undefined;\n }\n if (Number(param) <= 0) {\n return undefined;\n }\n const size = getPageLimit(request, pagination) ?? getPageItems(context).length;\n return Math.max(0, Number(param) - size);\n};\n\n/**\n * Tells whether the list continues after the given page\n */\nexport const getHasNextPage = (context: PaginationPageContext): boolean => {\n const { request, pagination, param } = context;\n const mode = getPaginationMode(pagination);\n\n if (getNextPageParam(context) === undefined) {\n return false;\n }\n if (pagination.hasNext) {\n return !!pagination.hasNext(getCallbackContext(context));\n }\n if (mode === \"cursor\") {\n return true;\n }\n\n const items = getPageItems(context);\n if (items.length === 0) {\n return false;\n }\n\n const limit = getPageLimit(request, pagination);\n const total = getPageTotal(context);\n if (total !== null) {\n if (mode === \"offset\") {\n return Number(param) + items.length < total;\n }\n const pageIndex = Number(param) - getFirstPageNumber(request, pagination);\n return (pageIndex + 1) * (limit ?? items.length) < total;\n }\n\n return limit === undefined || items.length >= limit;\n};\n\n/**\n * Tells whether the list continues before the given page\n */\nexport const getHasPreviousPage = (context: PaginationPageContext): boolean => {\n if (getPreviousPageParam(context) === undefined) {\n return false;\n }\n return context.pagination.hasPrevious ? !!context.pagination.hasPrevious(getCallbackContext(context)) : true;\n};\n\n/**\n * Rebuilds a list from already stored pages: from the starting page forwards, then backwards, until a page\n * is missing. Nothing has to remember which pages were loaded.\n */\nexport const getCachedPages = <T extends { data: unknown }>({\n request,\n pagination,\n read,\n maxPages = Infinity,\n}: {\n request: RequestInstance;\n pagination: PaginationConfig;\n read: (pageRequest: RequestInstance) => T | null | undefined;\n maxPages?: number;\n}): CachedInfinitePage<T>[] => {\n const pages: CachedInfinitePage<T>[] = [];\n // Cursors returned by the server could point back at an earlier page\n const visited = new Set<string>();\n\n const readPage = (param: unknown) => {\n const key = stringifyKey(param);\n if (visited.has(key) || pages.length >= maxPages) {\n return null;\n }\n visited.add(key);\n\n const pageRequest = getPageRequest(request, pagination, param);\n const value = read(pageRequest);\n return value ? { param, request: pageRequest, value } : null;\n };\n\n const getContext = (page: CachedInfinitePage<T>): PaginationPageContext => ({\n request,\n pagination,\n data: page.value.data,\n param: page.param,\n pages: pages.map((item) => item.value.data),\n });\n\n const first = readPage(getInitialPageParam(request, pagination));\n if (!first) {\n return pages;\n }\n pages.push(first);\n\n while (true) {\n const last = pages.at(-1) as CachedInfinitePage<T>;\n const param = getHasNextPage(getContext(last)) ? getNextPageParam(getContext(last)) : undefined;\n const page = param === undefined ? null : readPage(param);\n if (!page) {\n break;\n }\n pages.push(page);\n }\n\n while (true) {\n const param = getHasPreviousPage(getContext(pages[0])) ? getPreviousPageParam(getContext(pages[0])) : undefined;\n const page = param === undefined ? null : readPage(param);\n if (!page) {\n break;\n }\n pages.unshift(page);\n }\n\n return pages;\n};\n","import type { RequestInstance } from \"request\";\nimport type { HydrateDataType } from \"types\";\n\nimport type { FetchInfiniteOptions, FetchInfiniteResult, Pagination, PaginationConfig } from \"./infinite.types\";\nimport {\n getHasNextPage,\n getInitialPageParam,\n getNextPageParam,\n getPageItems,\n getPageRequest,\n getPageTotal,\n} from \"./infinite.utils\";\n\n/**\n * Fetches the first pages of a list one after another, without touching the cache or the queues.\n * Made for server rendering: pass `dehydrated` to the `Hydrate` component to render them on the client.\n *\n * @example\n * ```ts\n * const { dehydrated } = await fetchInfinite(getFeed, {\n * pagination: { cursor: \"cursor\", next: \"nextCursor\", items: \"data\" },\n * pages: 2,\n * });\n * ```\n */\nexport const fetchInfinite = async <R extends RequestInstance, const P extends Pagination<R>>(\n request: R,\n options: FetchInfiniteOptions<P>,\n): Promise<FetchInfiniteResult<R, P>> => {\n const pagination = options.pagination as PaginationConfig;\n const pageCount = Math.max(1, options.pages ?? 1);\n\n const result: FetchInfiniteResult<any, any> = {\n items: [],\n pages: [],\n pageParams: [],\n total: null,\n hasNextPage: false,\n error: null,\n responses: [],\n dehydrated: [],\n };\n\n let param = getInitialPageParam(request, pagination);\n\n for (let index = 0; index < pageCount; index += 1) {\n const pageRequest = getPageRequest(request, pagination, param);\n // Pages depend on each other, so they cannot be requested at the same time\n // eslint-disable-next-line no-await-in-loop\n const response = await (pageRequest as RequestInstance).exec({});\n\n result.responses.push(response);\n\n if (!response.success) {\n result.error = response.error;\n break;\n }\n\n const context = { request, pagination, data: response.data, param, pages: result.pages };\n\n result.pages.push(response.data);\n result.pageParams.push(param);\n (result.items as unknown[]).push(...getPageItems(context));\n result.total = getPageTotal(context) ?? result.total;\n result.hasNextPage = getHasNextPage(context);\n result.dehydrated.push(pageRequest.dehydrate({ response }) as HydrateDataType);\n\n if (!result.hasNextPage) {\n break;\n }\n param = getNextPageParam(context);\n }\n\n return result as FetchInfiniteResult<R, P>;\n};\n"],"x_google_ignoreList":[12],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,IAAa,SAAb,MAAuF;CACrF;CACA;CAEA,SAAoC,KAAA;CAEpC,gBAAwD,EAAE;CAE1D,YAAY,QAA8C;AAAvC,OAAA,SAAA;AACjB,OAAK,OAAO,OAAO;AACnB,MAAI,OAAO,KACT,MAAK,OAAO,OAAO;;;C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O,SAAS,MAAM;AACzD,MAAI,CAAC,KACH;AAEF,QAAM,QAAQ,KAAK;;AAGrB,QAAO;;;;;;;;;;;;;;;;ACvRT,IAAa,gBAAgB,OAC3B,SACA,YACuC;CACvC,MAAM,aAAa,QAAQ;CAC3B,MAAM,YAAY,KAAK,IAAI,GAAG,QAAQ,SAAS,EAAE;CAEjD,MAAM,SAAwC;EAC5C,OAAO,EAAE;EACT,OAAO,EAAE;EACT,YAAY,EAAE;EACd,OAAO;EACP,aAAa;EACb,OAAO;EACP,WAAW,EAAE;EACb,YAAY,EAAE;EACf;CAED,IAAI,QAAQ,oBAAoB,SAAS,WAAW;AAEpD,MAAK,IAAI,QAAQ,GAAG,QAAQ,WAAW,SAAS,GAAG;EACjD,MAAM,cAAc,eAAe,SAAS,YAAY,MAAM;EAG9D,MAAM,WAAW,MAAO,YAAgC,KAAK,EAAE,CAAC;AAEhE,SAAO,UAAU,KAAK,SAAS;AAE/B,MAAI,CAAC,SAAS,SAAS;AACrB,UAAO,QAAQ,SAAS;AACxB;;EAGF,MAAM,UAAU;GAAE;GAAS;GAAY,MAAM,SAAS;GAAM;GAAO,OAAO,OAAO;GAAO;AAExF,SAAO,MAAM,KAAK,SAAS,KAAK;AAChC,SAAO,WAAW,KAAK,MAAM;AAC5B,SAAO,MAAoB,KAAK,GAAG,aAAa,QAAQ,CAAC;AAC1D,SAAO,QAAQ,aAAa,QAAQ,IAAI,OAAO;AAC/C,SAAO,cAAc,eAAe,QAAQ;AAC5C,SAAO,WAAW,KAAK,YAAY,UAAU,EAAE,UAAU,CAAC,CAAoB;AAE9E,MAAI,CAAC,OAAO,YACV;AAEF,UAAQ,iBAAiB,QAAQ;;AAGnC,QAAO"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/plugin/plugin.ts","../src/constants/time.constants.ts","../src/utils/error.utils.ts","../src/utils/uuid.utils.ts","../../../node_modules/.pnpm/events@3.3.0/node_modules/events/events.js","../src/utils/emitter.utils.ts","../src/request/request.hooks.ts","../src/mocker/mocker.ts","../src/adapter/adapter.bindings.ts","../src/adapter/adapter.utils.ts","../src/adapter/adapter.ts","../src/constants/http.constants.ts","../src/optimistic/optimistic.utils.ts","../src/optimistic/optimistic.ts","../src/optimistic/optimistic.settlement.ts","../src/request/request.utils.ts","../src/request/request.ts","../src/cache/cache.ts","../src/cache/cache.utils.ts","../src/cache/cache.events.ts","../src/dispatcher/dispatcher.constants.ts","../src/dispatcher/dispatcher.events.ts","../src/dispatcher/dispatcher.ts","../src/dispatcher/dispatcher.utils.ts","../src/http-adapter/http-adapter.constants.ts","../src/http-adapter/http-adapter.utils.ts","../src/http-adapter/http-adapter.fetch.ts","../src/http-adapter/http-adapter.ts","../src/managers/app/app.manager.ts","../src/managers/app/app.manager.utils.ts","../src/managers/app/app.manager.events.ts","../src/managers/app/app.manager.constants.ts","../src/managers/request/request.manager.ts","../src/managers/request/request.manager.utils.ts","../src/managers/request/request.manager.events.ts","../src/managers/logger/logger.manager.ts","../src/managers/logger/logger.manager.utils.ts","../src/managers/logger/logger.manager.constants.ts","../src/client/client.utils.ts","../src/client/client.ts","../src/client/client.constants.ts","../src/client/client.create.ts","../src/sdk/sdk.ts","../src/infinite/infinite.utils.ts","../src/infinite/infinite.ts"],"sourcesContent":["import type { ClientInstance } from \"client\";\nimport type { PluginMethodParameters, PluginMethods, PluginOptionsType } from \"plugin\";\n\n/**\n * Base class for plugins that hook into the request, cache, dispatcher, and adapter lifecycle.\n * Extend this to build devtools, logging, analytics, or custom side-effect plugins.\n */\nexport class Plugin<Client extends ClientInstance = ClientInstance, PluginData = void> {\n public name: string;\n public data: PluginData;\n\n public client: Client | undefined = undefined;\n\n private pluginMethods: Partial<PluginMethods<Client>> = {};\n\n constructor(public config: PluginOptionsType<PluginData>) {\n this.name = config.name;\n if (config.data) {\n this.data = config.data;\n }\n }\n\n /** Bind the plugin to a client instance. Called automatically when the plugin is added via `client.addPlugin()`. */\n initialize = (client: Client) => {\n this.client = client;\n return this;\n };\n\n /** Invoke a registered plugin method by name. Used internally by the client to dispatch lifecycle events. */\n trigger = <Key extends keyof PluginMethods<Client>>(method: Key, data: PluginMethodParameters<Key, Client>) => {\n const callback = this.pluginMethods[method];\n if (callback) {\n callback(data as any);\n }\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Plugin lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /**\n * Callback that will be executed when plugin is mounted\n */\n onMount = (callback: PluginMethods<Client>[\"onMount\"]) => {\n this.pluginMethods.onMount = callback;\n return this;\n };\n\n /**\n * Callback that will be executed when plugin is unmounted\n */\n onUnmount = (callback: PluginMethods<Client>[\"onUnmount\"]) => {\n this.pluginMethods.onUnmount = callback;\n return this;\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Request lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /**\n * Callback that will be executed when request is created\n */\n onRequestCreate = (callback: PluginMethods<Client>[\"onRequestCreate\"]) => {\n this.pluginMethods.onRequestCreate = callback;\n return this;\n };\n /**\n * Callback that will be executed when request gets triggered\n */\n onRequestTrigger = (callback: PluginMethods<Client>[\"onRequestTrigger\"]) => {\n this.pluginMethods.onRequestTrigger = callback;\n return this;\n };\n /**\n * Callback that will be executed when request starts\n */\n onRequestStart = (callback: PluginMethods<Client>[\"onRequestStart\"]) => {\n this.pluginMethods.onRequestStart = callback;\n return this;\n };\n /**\n * Callback that will be executed when response is successful\n */\n onRequestSuccess = (callback: PluginMethods<Client>[\"onRequestSuccess\"]) => {\n this.pluginMethods.onRequestSuccess = callback;\n return this;\n };\n /**\n * Callback that will be executed when response is failed\n */\n onRequestError = (callback: PluginMethods<Client>[\"onRequestError\"]) => {\n this.pluginMethods.onRequestError = callback;\n return this;\n };\n /**\n * Callback that will be executed when response is finished\n */\n onRequestFinished = (callback: PluginMethods<Client>[\"onRequestFinished\"]) => {\n this.pluginMethods.onRequestFinished = callback;\n return this;\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Dispatcher lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /** Called when the dispatcher storage is fully cleared */\n onDispatcherCleared = (callback: PluginMethods<Client>[\"onDispatcherCleared\"]) => {\n this.pluginMethods.onDispatcherCleared = callback;\n return this;\n };\n\n /** Called when a dispatcher queue has no more pending requests */\n onDispatcherQueueDrained = (callback: PluginMethods<Client>[\"onDispatcherQueueDrained\"]) => {\n this.pluginMethods.onDispatcherQueueDrained = callback;\n return this;\n };\n\n /** Called when a dispatcher queue transitions to running, paused, or stopped */\n onDispatcherQueueRunning = (callback: PluginMethods<Client>[\"onDispatcherQueueRunning\"]) => {\n this.pluginMethods.onDispatcherQueueRunning = callback;\n return this;\n };\n\n /** Called when a new item is added to a dispatcher queue */\n onDispatcherItemAdded = (callback: PluginMethods<Client>[\"onDispatcherItemAdded\"]) => {\n this.pluginMethods.onDispatcherItemAdded = callback;\n return this;\n };\n\n /** Called when an item is removed from a dispatcher queue */\n onDispatcherItemDeleted = (callback: PluginMethods<Client>[\"onDispatcherItemDeleted\"]) => {\n this.pluginMethods.onDispatcherItemDeleted = callback;\n return this;\n };\n\n /** Called when a new dispatcher queue is created */\n onDispatcherQueueCreated = (callback: PluginMethods<Client>[\"onDispatcherQueueCreated\"]) => {\n this.pluginMethods.onDispatcherQueueCreated = callback;\n return this;\n };\n\n /** Called when an entire dispatcher queue is cleared */\n onDispatcherQueueCleared = (callback: PluginMethods<Client>[\"onDispatcherQueueCleared\"]) => {\n this.pluginMethods.onDispatcherQueueCleared = callback;\n return this;\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Cache lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /** Called when a cache entry is created or updated */\n onCacheItemChange = (callback: PluginMethods<Client>[\"onCacheItemChange\"]) => {\n this.pluginMethods.onCacheItemChange = callback;\n return this;\n };\n\n /** Called when a cache entry is deleted */\n onCacheItemDelete = (callback: PluginMethods<Client>[\"onCacheItemDelete\"]) => {\n this.pluginMethods.onCacheItemDelete = callback;\n return this;\n };\n\n /** Called when a cache entry is invalidated */\n onCacheItemInvalidate = (callback: PluginMethods<Client>[\"onCacheItemInvalidate\"]) => {\n this.pluginMethods.onCacheItemInvalidate = callback;\n return this;\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Adapter lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /** Called when the adapter fetcher is about to execute a request */\n onAdapterFetch = (callback: PluginMethods<Client>[\"onAdapterFetch\"]) => {\n this.pluginMethods.onAdapterFetch = callback;\n return this;\n };\n}\n","export enum Time {\n SEC = 1e3,\n MIN = 6e4,\n HOUR = 3.6e6,\n DAY = 8.64e7,\n WEEK = 6.048e8,\n MONTH_30 = 2.592e9,\n MONTH_31 = 2.6784e9,\n YEAR = 3.1536e10,\n YEAR_LEAP = 3.162_24e10,\n}\n","/**\n * Callbacks, listeners, plugins and optimistic handlers are the code of the user running inside of the request\n * lifecycle. Their error can't break it, and it can't get lost either - it is thrown from a timer, outside of the\n * lifecycle, so it reaches the error handlers of the environment (`window.onerror`, `uncaughtException`).\n * @internal\n * @param error value thrown by the user code\n */\nexport const throwOutsideLifecycle = (error: unknown): void => {\n setTimeout(() => {\n throw error;\n });\n};\n\n/**\n * Runs the code of the user in the middle of the request lifecycle. When it throws, the lifecycle goes on\n * and the error is thrown outside of it.\n * @internal\n * @param callback code of the user to run\n * @returns `true` when the callback finished, `false` when it threw\n */\nexport const runUserCode = (callback: VoidFunction): boolean => {\n try {\n callback();\n return true;\n } catch (error) {\n throwOutsideLifecycle(error);\n return false;\n }\n};\n","import type { RequestInstance } from \"request\";\n\nexport const getUniqueRequestId = (request: Pick<RequestInstance, \"queryKey\">) => {\n return `${request.queryKey}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n","import Emitter from \"events\";\n\nimport { runUserCode } from \"./error.utils\";\n\nconst getListenName = (event: string | symbol) => `listen_${String(event)}`;\n\nexport class EventEmitter extends Emitter {\n emitCallbacks: ((event: string, data: any, isTriggeredExternally?: true) => void)[] = [];\n\n // eslint-disable-next-line @typescript-eslint/no-useless-constructor\n constructor(options?: ConstructorParameters<typeof Emitter>[0]) {\n super(options);\n }\n\n emit(type: string, data: any, isTriggeredExternally: boolean) {\n const params: [string, any, true?] = [type, data];\n\n if (isTriggeredExternally) {\n params.push(isTriggeredExternally);\n }\n\n this.emitCallbacks?.forEach((callback) => runUserCode(() => callback(...params)));\n\n // Every listener gets the event - a throwing one can't keep it from the listeners added after it\n const listeners = this.rawListeners(type);\n listeners.forEach((listener) => runUserCode(() => listener.call(this, ...params.slice(1))));\n\n return listeners.length > 0;\n }\n\n onEmit = (callback: (event: string, data: any, isTriggeredExternally?: true) => void) => {\n this.emitCallbacks?.push(callback);\n return () => {\n this.emitCallbacks = this.emitCallbacks?.filter((cb) => cb !== callback);\n };\n };\n\n onListener = (event: string, listener: (count: number) => void) => {\n super.on(getListenName(event), listener);\n return () => {\n super.off(getListenName(event), listener);\n };\n };\n\n on = (event: string | symbol, listener: (...args: any[]) => void) => {\n super.on(event, listener);\n super.emit(getListenName(event), super.listeners(event).length);\n return this;\n };\n\n off = (event: string | symbol, listener: (...args: any[]) => void) => {\n super.off(event, listener);\n super.emit(getListenName(event), super.listeners(event).length);\n return this;\n };\n\n addListener = this.on;\n removeListener = this.off;\n}\n","import type {\n RequestEventType,\n RequestProgressEventType,\n RequestResponseEventType,\n RequestRetryEventType,\n} from \"managers\";\n\nimport type { RequestInstance } from \"./request.types\";\n\ntype HookName =\n | \"onBeforeSent\"\n | \"onRequestStart\"\n | \"onResponseStart\"\n | \"onUploadProgress\"\n | \"onDownloadProgress\"\n | \"onResponse\"\n | \"onRetry\"\n | \"onRemove\";\n\nexport interface RequestHooks<R extends RequestInstance> {\n onBeforeSent: (cb: (eventData: RequestEventType<R>) => void) => () => void;\n onRequestStart: (cb: (eventData: RequestEventType<R>) => void) => () => void;\n onResponseStart: (cb: (eventData: RequestEventType<R>) => void) => () => void;\n onUploadProgress: (cb: (eventData: RequestProgressEventType<R>) => void) => () => void;\n onDownloadProgress: (cb: (eventData: RequestProgressEventType<R>) => void) => () => void;\n onResponse: (cb: (eventData: RequestResponseEventType<R>) => void) => () => void;\n /** Called when a failed attempt of a `send()` schedules a retry, with the `retry` number and its `delay` */\n onRetry: (cb: (eventData: RequestRetryEventType<R>) => void) => () => void;\n onRemove: (cb: (eventData: RequestEventType<R>) => void) => () => void;\n /** @internal Invoke all registered listeners for a given hook */\n __emit: (name: HookName, data: any) => void;\n /** @internal Get a snapshot of all registered listeners (used by clone) */\n __snapshot: () => Record<HookName, ((...args: any[]) => void)[]>;\n}\n\nconst HOOK_NAMES: HookName[] = [\n \"onBeforeSent\",\n \"onRequestStart\",\n \"onResponseStart\",\n \"onUploadProgress\",\n \"onDownloadProgress\",\n \"onResponse\",\n \"onRetry\",\n \"onRemove\",\n];\n\nexport function createRequestHooks<R extends RequestInstance>(\n initial?: Record<HookName, ((...args: any[]) => void)[]>,\n): RequestHooks<R> {\n const listeners: Record<HookName, ((...args: any[]) => void)[]> = {\n onBeforeSent: [],\n onRequestStart: [],\n onResponseStart: [],\n onUploadProgress: [],\n onDownloadProgress: [],\n onResponse: [],\n onRetry: [],\n onRemove: [],\n };\n\n if (initial) {\n HOOK_NAMES.forEach((name) => {\n listeners[name] = [...initial[name]];\n });\n }\n\n const subscribe = (name: HookName) => {\n return (cb: (...args: any[]) => void) => {\n listeners[name].push(cb);\n return () => {\n const idx = listeners[name].indexOf(cb);\n if (idx !== -1) {listeners[name].splice(idx, 1);}\n };\n };\n };\n\n return {\n onBeforeSent: subscribe(\"onBeforeSent\"),\n onRequestStart: subscribe(\"onRequestStart\"),\n onResponseStart: subscribe(\"onResponseStart\"),\n onUploadProgress: subscribe(\"onUploadProgress\"),\n onDownloadProgress: subscribe(\"onDownloadProgress\"),\n onResponse: subscribe(\"onResponse\"),\n onRetry: subscribe(\"onRetry\"),\n onRemove: subscribe(\"onRemove\"),\n __emit(name: HookName, data: any) {\n listeners[name].forEach((cb) => {\n cb(data);\n });\n },\n __snapshot() {\n const snap = {} as Record<HookName, ((...args: any[]) => void)[]>;\n HOOK_NAMES.forEach((name) => {\n snap[name] = [...listeners[name]];\n });\n return snap;\n },\n };\n}\n","import type { getAdapterBindings, AdapterInstance } from \"adapter\";\nimport { RequestProcessingError } from \"adapter\";\nimport type { ExtractAdapterExtraType, ExtractAdapterStatusType } from \"types\";\n\nexport const mocker = async <T extends AdapterInstance>({\n request,\n requestId,\n onError,\n onResponseEnd,\n onTimeoutError,\n onRequestEnd,\n createAbortListener,\n onResponseProgress,\n onRequestProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onSuccess,\n adapter,\n}: Awaited<ReturnType<typeof getAdapterBindings<T>>>) => {\n if (!request.unstable_mock) {\n throw new RequestProcessingError(\"Mock should be defined when calling mocker\");\n }\n\n let thrown = false;\n\n const {\n requestTime = 20,\n responseTime = 20,\n totalUploaded = 1000,\n totalDownloaded = 1000,\n timeout,\n } = request.unstable_mock.config;\n const result = await request.unstable_mock.fn({ request, requestId });\n\n const { data, error, status, extra = request.client.adapter.defaultExtra } = result;\n // Without the `success` flag, a mock with nothing but an error is a failed response\n const hasData = data !== undefined && data !== null;\n const { success = !error || hasData } = result;\n\n createAbortListener({\n status: adapter.systemErrorStatus,\n extra: adapter.systemErrorExtra,\n onAbort: () => {\n thrown = true;\n },\n });\n\n onBeforeRequest();\n onRequestStart();\n\n const progress = (\n totalTime: number,\n totalSize: number,\n progressFunction: typeof onResponseProgress | typeof onRequestProgress,\n ) =>\n new Promise((resolveProgress) => {\n if (thrown) {\n resolveProgress(true);\n return;\n }\n\n const interval = 20;\n const dataStart = Date.now();\n const intervals = Math.ceil(totalTime / interval);\n const chunkSize = Math.ceil(totalSize / intervals);\n let currentlyLoaded = 0;\n const timer = setInterval(function handleProgressInterval() {\n // Aborted or timed out - nothing more is transferred\n if (thrown) {\n resolveProgress(true);\n clearInterval(timer);\n return;\n }\n\n const currentTime = Math.min(totalTime, Date.now() - dataStart);\n currentlyLoaded += currentlyLoaded + chunkSize >= totalSize ? totalSize - currentlyLoaded : chunkSize;\n progressFunction({\n total: totalSize,\n loaded: currentTime >= totalTime ? totalSize : currentlyLoaded,\n });\n\n if (currentTime >= totalTime) {\n resolveProgress(true);\n clearInterval(timer);\n }\n }, interval);\n });\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n if (typeof timeout === \"number\") {\n timeoutId = setTimeout(() => {\n thrown = true;\n onTimeoutError({\n status: 0 as ExtractAdapterStatusType<T>,\n extra: extra as ExtractAdapterExtraType<T>,\n });\n }, timeout);\n }\n if (!thrown) {\n await progress(requestTime, totalUploaded, onRequestProgress);\n }\n if (!thrown) {\n onRequestEnd();\n onResponseStart();\n }\n if (!thrown) {\n await progress(responseTime, totalDownloaded, onResponseProgress);\n }\n clearTimeout(timeoutId);\n // An abort or a timeout was already reported when it happened\n if (thrown) {\n return;\n }\n if (success || (error && data)) {\n onSuccess({\n data,\n error,\n status: status as ExtractAdapterStatusType<T>,\n extra: extra as ExtractAdapterExtraType<T>,\n });\n } else {\n onError({\n error,\n status: status as ExtractAdapterStatusType<T>,\n extra: extra as ExtractAdapterExtraType<T>,\n });\n }\n onResponseEnd();\n};\n","import type { ResponseSuccessType, ResponseErrorType, ProgressDataType, ProgressType, AdapterInstance } from \"adapter\";\nimport { getErrorMessage, RequestProcessingError } from \"adapter\";\nimport type { LoggerMethods } from \"managers\";\nimport type { RequestInstance, ProgressEventType } from \"request\";\nimport { getProgressData, scopeKey } from \"request\";\nimport type {\n ExtractResponseType,\n ExtractErrorType,\n ExtractPayloadType,\n ExtractAdapterOptionsType,\n ExtractAdapterStatusType,\n ExtractAdapterExtraType,\n} from \"types\";\n\nexport const getAdapterBindings = async <T extends AdapterInstance>({\n request: baseRequest,\n requestId,\n resolve,\n onStartTime,\n internalErrorMapping,\n}: {\n request: RequestInstance;\n requestId: string;\n resolve: (value: ResponseSuccessType<any, T> | ResponseErrorType<any, T>) => void;\n onStartTime: (timestamp: number) => void;\n internalErrorMapping: (error: ReturnType<typeof getErrorMessage>) => any;\n}) => {\n const { requestManager, loggerManager } = baseRequest.client;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { unstable_payloadMapper } = baseRequest.client.adapter;\n\n const logger = loggerManager.initialize(baseRequest.client, \"Adapter\");\n\n let requestStartTimestamp: null | number = null;\n let responseStartTimestamp: null | number = null;\n let request = baseRequest;\n\n // Progress\n let requestTotal = 1;\n let responseTotal = 1;\n // Last emitted progress - an identical update is not emitted again\n let previousRequestProgress: { total: number; loaded: number } | null = null;\n let previousResponseProgress: { total: number; loaded: number } | null = null;\n\n const isSameProgress = (previous: { total: number; loaded: number } | null, next: ProgressType) =>\n !!previous && previous.total === next.total && previous.loaded === next.loaded;\n\n // Pre request modifications\n logger.debug({\n title: `Running middleware callbacks`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n\n request = await request.client.unstable_modifyRequest(request);\n\n if (request.auth) {\n request = await request.client.unstable_modifyAuth(request);\n }\n\n if (request.unstable_requestMapper) {\n request = await request.unstable_requestMapper(request, requestId);\n }\n\n // Request Setup\n const { client, abortKey } = request;\n const scopedAbortKey = scopeKey(abortKey, request.scope);\n\n // eslint-disable-next-line prefer-destructuring\n let payload = request.payload;\n\n if (request.unstable_payloadMapper) {\n payload = await request.unstable_payloadMapper<ExtractPayloadType<RequestInstance>>(request.payload);\n } else if (unstable_payloadMapper) {\n payload = await unstable_payloadMapper(payload);\n }\n\n // Defaults from `adapter.setAdapterDefaults()`, overridden by the options of the request\n const adapterDefaults = client.adapter.unstable_getAdapterDefaults?.(request as any);\n const adapterOptions = (adapterDefaults ? { ...adapterDefaults, ...request.options } : request.options) as\n | ExtractAdapterOptionsType<T>\n | undefined;\n const startTime = Date.now();\n onStartTime(startTime);\n\n const getRequestStartTimestamp = () => {\n return requestStartTimestamp;\n };\n\n const getResponseStartTimestamp = () => {\n return responseStartTimestamp;\n };\n\n // Progress\n\n const getTotal = (previousTotal: number, progress?: ProgressDataType) => {\n if (!progress) {\n return previousTotal;\n }\n const total = Number(progress.total || 0);\n const loaded = Number(progress.loaded || 0);\n return Math.max(total, loaded, previousTotal);\n };\n\n const handleRequestProgress = (\n startTimestamp: number,\n progressTimestamp: number,\n progressEvent: ProgressEventType,\n ) => {\n const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);\n\n if (!isSameProgress(previousRequestProgress, progress)) {\n previousRequestProgress = { total: progress.total, loaded: progress.loaded };\n requestManager.events.emitUploadProgress({ ...progress, requestId, request });\n }\n };\n\n const handleResponseProgress = (\n startTimestamp: number,\n progressTimestamp: number,\n progressEvent: ProgressEventType,\n ) => {\n const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);\n\n if (!isSameProgress(previousResponseProgress, progress)) {\n previousResponseProgress = { total: progress.total, loaded: progress.loaded };\n requestManager.events.emitDownloadProgress({ ...progress, requestId, request });\n }\n };\n\n // Pre-request\n\n const onBeforeRequest = () => {\n logger.debug({\n title: `Request about to be sent`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n client.triggerPlugins(\"onRequestTrigger\", { request });\n };\n\n // Request\n\n const onRequestStart = (progress?: ProgressDataType) => {\n logger.info({\n title: `Request start`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n client.triggerPlugins(\"onRequestStart\", { request });\n\n if (progress?.total) {\n requestTotal = getTotal(requestTotal, progress);\n }\n\n const initialPayload = {\n total: requestTotal,\n loaded: progress?.loaded || 0,\n };\n requestStartTimestamp = Date.now();\n handleRequestProgress(requestStartTimestamp, requestStartTimestamp, initialPayload);\n requestManager.events.emitRequestStart({ requestId, request });\n return requestStartTimestamp;\n };\n\n const onRequestProgress = (progress: ProgressDataType) => {\n if (!requestStartTimestamp) {\n requestStartTimestamp = Date.now();\n }\n requestTotal = getTotal(requestTotal, progress);\n\n const progressTimestamp = Date.now();\n\n handleRequestProgress(requestStartTimestamp, progressTimestamp, {\n total: requestTotal,\n loaded: progress.loaded || 0,\n });\n return progressTimestamp;\n };\n\n const onRequestEnd = () => {\n if (!requestStartTimestamp) {\n requestStartTimestamp = Date.now();\n }\n\n const progressTimestamp = Date.now();\n handleRequestProgress(requestStartTimestamp, progressTimestamp, {\n total: requestTotal,\n loaded: requestTotal,\n });\n return progressTimestamp;\n };\n\n // Response\n\n const onResponseStart = (progress?: ProgressDataType) => {\n responseStartTimestamp = Date.now();\n\n responseTotal = getTotal(responseTotal, progress);\n\n const initialPayload = {\n total: responseTotal,\n loaded: progress?.loaded || 0,\n };\n\n handleResponseProgress(responseStartTimestamp, responseStartTimestamp, initialPayload);\n requestManager.events.emitResponseStart({ requestId, request });\n return responseStartTimestamp;\n };\n\n const onResponseProgress = (progress: ProgressDataType) => {\n if (!responseStartTimestamp) {\n responseStartTimestamp = Date.now();\n }\n\n const progressTimestamp = Date.now();\n responseTotal = getTotal(responseTotal, progress);\n\n // The total never drops below the loaded bytes - e.g. a compressed body is counted after decompression,\n // while its Content-Length tells the compressed size\n handleResponseProgress(responseStartTimestamp, progressTimestamp, {\n total: responseTotal,\n loaded: progress.loaded || 0,\n });\n return progressTimestamp;\n };\n\n const onResponseEnd = () => {\n if (!responseStartTimestamp) {\n responseStartTimestamp = Date.now();\n }\n\n const progressTimestamp = Date.now();\n handleResponseProgress(responseStartTimestamp, progressTimestamp, {\n total: responseTotal,\n loaded: responseTotal,\n });\n return progressTimestamp;\n };\n\n // Success\n\n const onSuccess = async ({\n data,\n error,\n status,\n extra,\n }: {\n data: any;\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n error?: ExtractErrorType<T>;\n }): Promise<ResponseSuccessType<ExtractResponseType<T>, T>> => {\n let response: ResponseSuccessType<ExtractResponseType<T>, T> = {\n data,\n error: error ?? null,\n success: true,\n status,\n extra,\n requestTimestamp: startTime,\n responseTimestamp: Date.now(),\n };\n try {\n response = (await request.client.unstable_modifyResponse?.(response, request)) as typeof data;\n response = (await request.client.unstable_modifySuccessResponse?.(response, request)) as typeof data;\n\n client.triggerPlugins(\"onRequestSuccess\", { response, request });\n client.triggerPlugins(\"onRequestFinished\", { response, request });\n } catch (interceptorError) {\n // A throwing interceptor or plugin fails the request, it must not leave it without any response\n response = {\n data: null,\n error: internalErrorMapping(interceptorError as ReturnType<typeof getErrorMessage>),\n success: false,\n status,\n extra,\n requestTimestamp: startTime,\n responseTimestamp: Date.now(),\n } as unknown as typeof response;\n }\n\n resolve(response);\n\n logger.info({\n title: `Response success`,\n type: \"response\",\n extra: {\n request,\n requestId,\n response,\n },\n });\n return response;\n };\n\n // Errors\n\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n const onError = getAdapterOnError({\n request,\n requestId,\n startTime,\n logger,\n resolve,\n });\n\n const onAbortError = ({\n status,\n extra,\n }: {\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n }) => {\n logger.error({\n title: `Abort error`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n const error = internalErrorMapping(getErrorMessage(\"abort\"));\n return onError({ error, status, extra });\n };\n\n const onTimeoutError = ({\n status,\n extra,\n }: {\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n }) => {\n logger.error({\n title: `Timeout error`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n const error = internalErrorMapping(getErrorMessage(\"timeout\"));\n return onError({ error, status, extra });\n };\n\n const onUnexpectedError = ({\n status,\n extra,\n }: {\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n }) => {\n logger.error({\n title: `Unexpected error`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n const error = internalErrorMapping(getErrorMessage());\n return onError({ error, status, extra });\n };\n\n // Abort\n\n const getAbortController = () => {\n return requestManager.getAbortController(scopedAbortKey, requestId);\n };\n\n const createAbortListener = ({\n status,\n extra,\n onAbort = () => {},\n }: {\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n onAbort?: () => void;\n }) => {\n const controller = getAbortController();\n if (!controller) {\n throw new RequestProcessingError(\"Controller is not found\");\n }\n\n const abort = () => {\n onAbortError({ status, extra });\n onAbort();\n requestManager.events.emitAbort({ requestId, request });\n };\n\n // Instant abort when we stack many requests triggered at once, and we receive aborted controller\n if (controller.signal.aborted) {\n abort();\n }\n\n // Abort during the request\n controller.signal.addEventListener(\"abort\", abort);\n\n return () => controller.signal.removeEventListener(\"abort\", abort);\n };\n\n logger.debug({\n title: `Mounted adapter bindings`,\n type: \"request\",\n extra: {\n request,\n requestId,\n payload,\n adapterOptions,\n },\n });\n\n const queryParams = baseRequest.client.adapter.unstable_queryParamsMapper(request.queryParams);\n const endpoint = baseRequest.client.adapter.unstable_endpointMapper(request.endpoint);\n const headers = baseRequest.client.adapter.unstable_headerMapper(request);\n const { url } = baseRequest.client;\n\n return {\n request,\n requestId,\n url,\n endpoint,\n queryParams,\n payload,\n headers,\n adapter: baseRequest.client.adapter,\n adapterOptions,\n getAbortController,\n getRequestStartTimestamp,\n getResponseStartTimestamp,\n createAbortListener,\n onBeforeRequest,\n onRequestStart,\n onRequestProgress,\n onRequestEnd,\n onResponseStart,\n onResponseProgress,\n onResponseEnd,\n onSuccess,\n onAbortError,\n onTimeoutError,\n onUnexpectedError,\n onError,\n };\n};\n\nexport function getAdapterOnError<T extends AdapterInstance>({\n request,\n requestId,\n startTime,\n resolve,\n logger,\n}: {\n request: RequestInstance;\n requestId: string;\n startTime: number;\n logger: LoggerMethods;\n resolve: (value: ResponseSuccessType<any, T> | ResponseErrorType<any, T>) => void;\n}) {\n const { client } = request;\n\n return async ({\n error,\n status,\n extra,\n }: {\n error: any;\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n }): Promise<ResponseErrorType<any, T>> => {\n let response: ResponseErrorType<any, T> = {\n data: null,\n status,\n error,\n success: false,\n extra,\n requestTimestamp: startTime,\n responseTimestamp: Date.now(),\n };\n\n try {\n response = (await client.unstable_modifyResponse(response, request)) as typeof response;\n response = (await client.unstable_modifyErrorResponse(response, request)) as typeof response;\n\n client.triggerPlugins(\"onRequestError\", { response, request });\n client.triggerPlugins(\"onRequestFinished\", { response, request });\n } catch (interceptorError) {\n // A throwing interceptor or plugin replaces the error, it must not leave the request without any response\n response = { ...response, data: null, error: interceptorError, success: false };\n }\n\n resolve(response);\n\n logger.error({\n title: `Request error`,\n type: \"request\",\n extra: {\n request,\n requestId,\n response,\n },\n });\n\n return response;\n };\n}\n","/* eslint-disable max-classes-per-file */\n// Utils\nimport type { RequestInstance } from \"request\";\n\nexport class TimeoutError extends Error {\n constructor() {\n super(\"Request timeout\");\n this.name = \"TimeoutError\";\n }\n}\n\nexport class AbortError extends Error {\n constructor() {\n super(\"Request aborted\");\n this.name = \"AbortError\";\n }\n}\n\nexport class DeletedError extends Error {\n constructor() {\n super(\"Request deleted\");\n this.name = \"DeletedError\";\n }\n}\n\nexport class RequestProcessingError extends Error {\n description?: string = undefined;\n\n constructor(description?: string) {\n super(\"Request processing error\");\n this.description = description;\n this.name = \"RequestProcessingError\";\n }\n}\n\nexport class UnexpectedError extends Error {\n description?: string = undefined;\n\n constructor(description?: string) {\n super(\"Unexpected error\");\n this.description = description;\n this.name = \"UnexpectedError\";\n }\n}\n\nexport const getErrorMessage = (errorCase?: \"timeout\" | \"abort\" | \"deleted\" | \"processing\" | \"unexpected\") => {\n if (errorCase === \"timeout\") {\n return new TimeoutError();\n }\n if (errorCase === \"abort\") {\n return new AbortError();\n }\n if (errorCase === \"deleted\") {\n return new DeletedError();\n }\n if (errorCase === \"processing\") {\n return new RequestProcessingError();\n }\n return new UnexpectedError();\n};\n\n// Mappers\n\nexport const stringifyValue = (response: string | unknown): string => {\n try {\n return JSON.stringify(response as string);\n } catch {\n return \"\";\n }\n};\n\n/**\n * Payloads which are sent as they are - `fetch`, XHR and other transports know how to handle them\n * (and how to describe them with the `Content-Type` header)\n */\nconst isRawPayload = (payload: unknown): boolean => {\n return (\n (typeof FormData !== \"undefined\" && payload instanceof FormData) ||\n (typeof Blob !== \"undefined\" && payload instanceof Blob) ||\n (typeof URLSearchParams !== \"undefined\" && payload instanceof URLSearchParams) ||\n (typeof ReadableStream !== \"undefined\" && payload instanceof ReadableStream) ||\n (typeof ArrayBuffer !== \"undefined\" && (payload instanceof ArrayBuffer || ArrayBuffer.isView(payload)))\n );\n};\n\n/** `HeadersInit` can be an object, a list of pairs or the `Headers` instance */\nconst getHeadersEntries = (headers: HeadersInit | undefined): [string, string][] => {\n if (!headers) {\n return [];\n }\n if (typeof Headers !== \"undefined\" && headers instanceof Headers) {\n const entries: [string, string][] = [];\n headers.forEach((value, key) => entries.push([key, value]));\n return entries;\n }\n if (Array.isArray(headers)) {\n return headers as [string, string][];\n }\n return Object.entries(headers);\n};\n\nexport const getAdapterHeaders = (request: RequestInstance) => {\n const isObject = typeof request.payload === \"object\" && request.payload !== null;\n const entries = getHeadersEntries(request.headers);\n // Header names are case-insensitive, so \"content-type\" given with the request replaces the default one\n const hasContentType = entries.some(([name]) => name.toLowerCase() === \"content-type\");\n const headers: Record<string, string> = {};\n\n if (isObject && !isRawPayload(request.payload) && !hasContentType) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n entries.forEach(([name, value]) => {\n // Empty value is the way to not send a header (also the default one)\n if (value !== undefined && value !== null) {\n headers[name] = value;\n }\n });\n return headers as HeadersInit;\n};\n\nexport const getAdapterPayload = (data: unknown): string | FormData => {\n // Binary, form and stream payloads can't be turned into JSON - they would end up as \"{}\"\n if (isRawPayload(data)) {\n return data as FormData;\n }\n\n return stringifyValue(data);\n};\n","import type { Client, ClientInstance } from \"client\";\nimport type { LoggerMethods } from \"managers\";\nimport { mocker } from \"mocker\";\nimport type { RequestInstance, RequestOptionsType } from \"request\";\n/* eslint-disable class-methods-use-this */\nimport type { EmptyTypes, ExtendRequest } from \"types\";\n\nimport { getAdapterOnError, getAdapterBindings } from \"./adapter.bindings\";\nimport type {\n EndpointMapper,\n AdapterFetcherType,\n AdapterPayloadMappingType,\n HeaderMappingType,\n QueryParamsMapper,\n QueryParamsType,\n RequestResponseType,\n ResponseType,\n} from \"./adapter.types\";\nimport type { getErrorMessage } from \"./adapter.utils\";\nimport { getAdapterHeaders, getAdapterPayload, RequestProcessingError } from \"./adapter.utils\";\n\nexport type DefaultMapperType = <V, C = undefined>(value: V, config?: C) => V;\nexport const defaultMapper: DefaultMapperType = (value) => value;\n\n/**\n * Base adapter class responsible for executing HTTP requests. Adapters handle endpoint resolution,\n * header/payload/query-params mapping, and the actual fetch call. Extend or configure this class\n * to integrate custom transport layers (e.g., axios, graphql, firebase).\n */\nexport class Adapter<\n AdapterOptions,\n MethodType extends string,\n StatusType extends number | string,\n Extra extends Record<string, any>,\n QueryParams = QueryParamsType | string | EmptyTypes,\n DefaultQueryParams = undefined,\n EndpointType = string,\n EndpointMapperType extends EndpointMapper<EndpointType> | DefaultMapperType = DefaultMapperType,\n QueryParamsMapperType extends QueryParamsMapper<QueryParams> | DefaultMapperType = DefaultMapperType,\n HeaderMapperType extends HeaderMappingType | DefaultMapperType = DefaultMapperType,\n PayloadMapperType extends AdapterPayloadMappingType | DefaultMapperType = DefaultMapperType,\n RequestOptions extends Record<string, any> = {},\n> {\n /** Fetching function */\n public unstable_fetcher: AdapterFetcherType<\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >;\n\n /**\n * ********************\n * Defaults\n * ********************\n */\n\n public name: string;\n public defaultMethod: MethodType;\n public defaultExtra: Extra;\n public systemErrorStatus: StatusType;\n public systemErrorExtra: Extra;\n public defaultRequestOptions?: RequestOptionsType<EndpointType, AdapterOptions, MethodType> = undefined;\n public logger: LoggerMethods;\n public initialized = false;\n public client: ClientInstance;\n\n public unstable_onInitializeCallback?: (options: { client: ClientInstance }) => void = undefined;\n\n public unstable_queryParamsMapperConfig: Parameters<QueryParamsMapperType>[1];\n public unstable_headerMapperConfig: Parameters<HeaderMapperType>[1];\n public unstable_payloadMapperConfig: Parameters<PayloadMapperType>[1];\n public unstable_endpointMapperConfig: Parameters<EndpointMapperType>[1];\n\n /**\n * Type-only carrier of the additional `createRequest` fields declared by this adapter.\n * It has no runtime value - adapters read those fields from `request.requestOptions`.\n */\n public unstable_requestOptionsType?: RequestOptions = undefined;\n\n constructor(\n public options: {\n name: string;\n defaultMethod: MethodType;\n defaultExtra: Extra;\n systemErrorStatus: StatusType;\n systemErrorExtra: Extra;\n defaultRequestOptions?: RequestOptionsType<EndpointType, AdapterOptions, MethodType>;\n },\n ) {\n this.name = options.name;\n this.defaultMethod = options.defaultMethod;\n this.defaultExtra = options.defaultExtra;\n this.systemErrorStatus = options.systemErrorStatus;\n this.systemErrorExtra = options.systemErrorExtra;\n this.defaultRequestOptions = options.defaultRequestOptions;\n }\n\n /** Initialize the adapter with a client reference and set up logging. Called automatically when the client is created. */\n initialize = (client: ClientInstance) => {\n this.logger = client.loggerManager.initialize(client, \"Adapter\");\n this.initialized = true;\n this.client = client;\n\n this.unstable_onInitializeCallback?.({ client });\n return this;\n };\n\n /** Register a callback invoked once the adapter is initialized with a client. */\n onInitialize = (callback: (options: { client: ClientInstance }) => void) => {\n this.unstable_onInitializeCallback = callback;\n return this;\n };\n\n /**\n * ********************\n * Options Setters\n * ********************\n */\n\n public unstable_internalErrorMapping: (error: ReturnType<typeof getErrorMessage>) => any = (error) => error;\n /** Method to get default headers and to map them based on the data format exchange, by default it handles FormData / JSON formats. */\n public unstable_headerMapper: HeaderMapperType = getAdapterHeaders as HeaderMapperType;\n /** Method to get request data and transform them to the required format. It handles FormData and JSON by default. */\n public unstable_payloadMapper: PayloadMapperType = getAdapterPayload as PayloadMapperType;\n /** Method to get the endpoint for the adapter request. */\n public unstable_endpointMapper: EndpointMapperType = defaultMapper as EndpointMapperType;\n /** Method to get request data and transform them to the required format. */\n public unstable_queryParamsMapper: QueryParamsMapperType = defaultMapper as QueryParamsMapperType;\n /**\n * Turns query params given as a callback into data, at the moment they are set on a request. Unset by default, so\n * adapters without it store query params as given. See {@link Adapter.setQueryParamsResolver}.\n */\n public unstable_queryParamsResolver?: (callback: (...args: any[]) => unknown) => unknown = undefined;\n /** Get default adapter options for the request. */\n public unstable_getAdapterDefaults?: (\n request: ExtendRequest<\n RequestInstance,\n {\n client: Client<\n any,\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >;\n }\n >,\n ) => AdapterOptions = undefined;\n /** Get default request options for the request. */\n public unstable_getRequestDefaults?: (\n options: RequestOptionsType<EndpointType, AdapterOptions, MethodType>,\n ) => Partial<RequestOptionsType<EndpointType, AdapterOptions, MethodType>> = undefined;\n /**\n * Get formatted endpoint name of the request.\n * Helpful in displaying long endpoints like in case of graphql schemas etc.\n */\n public unstable_devtoolsEndpointGetter: (endpoint: string, requestOptions?: Record<string, any>) => string = (\n endpoint,\n ) => endpoint;\n\n /**\n * ********************\n * Methods\n * ********************\n */\n\n /** Set the default HTTP method used when a request does not specify one. */\n setDefaultMethod = (method: MethodType) => {\n this.defaultMethod = method;\n return this;\n };\n\n /** Set the default extra metadata attached to every request response (e.g., headers, status). */\n setDefaultExtra = (extra: Extra) => {\n this.defaultExtra = extra;\n return this;\n };\n\n /** Set a function that formats the endpoint string for display in devtools. */\n setDevtoolsEndpointGetter = (callback: (endpoint: string, requestOptions?: Record<string, any>) => string) => {\n this.unstable_devtoolsEndpointGetter = callback;\n return this;\n };\n\n /**\n * This method allows to configure global defaults for the request configuration like method, auth, deduplication etc.\n */\n setRequestDefaults = (callback: typeof this.unstable_getRequestDefaults): this => {\n this.unstable_getRequestDefaults = callback;\n return this;\n };\n\n /**\n * Set the adapter default options added to every sent request\n */\n setAdapterDefaults = (\n callback: (\n request: ExtendRequest<\n RequestInstance,\n {\n // No need for global error type, because we haven't sent the request yet\n client: Client<\n any,\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >;\n }\n >,\n ) => AdapterOptions,\n ): this => {\n this.unstable_getAdapterDefaults = callback;\n return this;\n };\n\n /** Set a custom mapping for internal adapter errors before they are returned in the response. */\n setInternalErrorMapping = (callback: (error: ReturnType<typeof getErrorMessage>) => any) => {\n this.unstable_internalErrorMapping = callback;\n return this;\n };\n\n /**\n * Set the custom header mapping function\n */\n setHeaderMapper = <NewMapper extends HeaderMappingType>(headerMapper: NewMapper) => {\n this.unstable_headerMapper = ((req: Parameters<NewMapper>[0]) =>\n headerMapper(req, this.unstable_headerMapperConfig as Parameters<NewMapper>[1])) as unknown as HeaderMapperType;\n return this as unknown as Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n NewMapper,\n PayloadMapperType,\n RequestOptions\n >;\n };\n\n /**\n * Set the payload mapping function which runs before every request is sent.\n * It is called with the raw payload and the value set with `setPayloadMapperConfig`,\n * and its return value is the body passed to the adapter.\n * Requests with their own `request.setPayloadMapper` skip it.\n * @example\n * ```ts\n * client.adapter.setPayloadMapper((payload, config) => encrypt(JSON.stringify(payload), config));\n * ```\n */\n setPayloadMapper = <NewMapper extends AdapterPayloadMappingType>(payloadMapper: NewMapper) => {\n this.unstable_payloadMapper = ((payload: Parameters<NewMapper>[0]) =>\n payloadMapper(\n payload,\n this.unstable_payloadMapperConfig as Parameters<NewMapper>[1],\n )) as unknown as PayloadMapperType;\n return this as unknown as Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n NewMapper,\n RequestOptions\n >;\n };\n\n /**\n * Set the endpoint mapping function which transforms the endpoint string before the request is sent\n */\n setEndpointMapper = <NewEndpointMapper extends EndpointMapper<EndpointType>>(endpointMapper: NewEndpointMapper) => {\n this.unstable_endpointMapper = ((endpoint: Parameters<NewEndpointMapper>[0]) =>\n endpointMapper(\n endpoint,\n this.unstable_endpointMapperConfig as Parameters<NewEndpointMapper>[1],\n )) as unknown as EndpointMapperType;\n return this as unknown as Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n NewEndpointMapper,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >;\n };\n\n /**\n * Set the query params mapping function which get triggered before request get sent\n */\n setQueryParamsMapper = <NewQueryParamsMapper extends QueryParamsMapper<QueryParams>>(\n queryParamsMapper: NewQueryParamsMapper,\n ) => {\n this.unstable_queryParamsMapper = ((queryParams: Parameters<NewQueryParamsMapper>[0]) =>\n queryParamsMapper(\n queryParams,\n this.unstable_queryParamsMapperConfig as Parameters<NewQueryParamsMapper>[1],\n )) as unknown as QueryParamsMapperType;\n return this as unknown as Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n NewQueryParamsMapper,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >;\n };\n\n /**\n * Let requests take query params as a callback. When a request gets a function as its query params (in\n * `createRequest`, `setQueryParams` or `send`), the resolver runs right away and the request stores what it returns,\n * so cache keys, query keys and `toJSON()` only ever see data. The resolver decides what the callback receives.\n *\n * Opt-in: adapters without a resolver store query params as given. Declare the callback in the adapter's query params\n * type so requests accept it.\n *\n * @example\n * // The Firebase adapter passes a constraints builder and stores the constraints it collected\n * adapter.setQueryParamsResolver((callback) => callback(createConstraints()).toJSON());\n */\n setQueryParamsResolver = (resolver: (callback: (...args: any[]) => unknown) => unknown) => {\n this.unstable_queryParamsResolver = resolver;\n return this;\n };\n\n /** Set the configuration object passed as the second argument to the query params mapper. */\n setQueryParamsMapperConfig = <NewQueryParamsMapperConfig extends Parameters<QueryParamsMapperType>[1]>(\n config: NewQueryParamsMapperConfig,\n ) => {\n this.unstable_queryParamsMapperConfig = config;\n return this;\n };\n\n /** Set the configuration object passed as the second argument to the header mapper. */\n setHeaderMapperConfig = <NewHeaderMapperConfig extends Parameters<HeaderMapperType>[1]>(\n config: NewHeaderMapperConfig,\n ) => {\n this.unstable_headerMapperConfig = config;\n return this;\n };\n\n /** Set the configuration object passed as the second argument to the endpoint mapper. */\n setEndpointMapperConfig = <NewEndpointMapperConfig extends Parameters<EndpointMapperType>[1]>(\n config: NewEndpointMapperConfig,\n ) => {\n this.unstable_endpointMapperConfig = config;\n return this;\n };\n\n /** Set the configuration object passed as the second argument to the payload mapper. */\n setPayloadMapperConfig = <NewPayloadMapperConfig extends Parameters<PayloadMapperType>[1]>(\n config: NewPayloadMapperConfig,\n ) => {\n this.unstable_payloadMapperConfig = config;\n return this;\n };\n\n /**\n * ********************\n * Fetching\n * ********************\n */\n\n /** Set the fetcher function that performs the actual network request. Must be called before any request can be executed. */\n public setFetcher(\n fetcher: AdapterFetcherType<\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >,\n ) {\n this.unstable_fetcher = fetcher.bind(this);\n return this;\n }\n\n /** Execute a request through the adapter pipeline: maps endpoint/headers/payload, runs plugins, then calls the fetcher. */\n public async fetch(\n request: ExtendRequest<\n RequestInstance,\n {\n // No need for global error type, it doesn't matter to the fetcher itself\n client: Client<\n any,\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >;\n }\n >,\n requestId: string,\n ): Promise<RequestResponseType<RequestInstance>> {\n let startTime: number | undefined;\n\n const execute = async (resolve: (value: ResponseType<any, any, any>) => void) => {\n try {\n if (!this.initialized) {\n throw new RequestProcessingError(`Adapter ${this.options.name} is not initialized`);\n }\n\n if (!this.unstable_fetcher) {\n throw new RequestProcessingError(`Fetcher for ${this.options.name} adapter is not set`);\n }\n\n this.client.triggerPlugins(\"onAdapterFetch\", {\n adapter: this,\n request,\n requestId,\n });\n\n const bindings = await getAdapterBindings<\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >({\n request,\n requestId,\n resolve,\n internalErrorMapping: this.unstable_internalErrorMapping,\n onStartTime: (time) => {\n startTime = time;\n },\n });\n\n if (request.unstable_mock && request.isMockerEnabled && request.client.isMockerEnabled) {\n return await mocker<\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >(bindings);\n }\n\n // Awaited so a rejected async fetcher lands in the catch below and resolves the request with the error\n return await this.unstable_fetcher(bindings);\n } catch (error) {\n const onError = getAdapterOnError({\n request,\n requestId,\n startTime: startTime || Date.now(),\n logger: this.logger,\n resolve,\n });\n\n return onError({\n error: this.unstable_internalErrorMapping(error as ReturnType<typeof getErrorMessage>),\n status: this.options.systemErrorStatus,\n extra: this.options.systemErrorExtra,\n });\n }\n };\n\n const promise = new Promise((resolve) => {\n execute(resolve);\n });\n\n return promise as Promise<RequestResponseType<RequestInstance>>;\n }\n}\n","export enum HttpMethods {\n GET = \"GET\",\n POST = \"POST\",\n PUT = \"PUT\",\n PATCH = \"PATCH\",\n DELETE = \"DELETE\",\n /** Safe, idempotent read with a request body (IETF draft-ietf-httpbis-safe-method-w-body). */\n QUERY = \"QUERY\",\n}\n\n/** Methods that are safe reads: routed to the fetch dispatcher and deduplicated by default. */\nexport const SAFE_HTTP_METHODS: string[] = [HttpMethods.GET, HttpMethods.QUERY];\n","import type { OptimisticInsertOptionsType } from \"./optimistic.types\";\n\n/** Erased match - a predicate or a plain value compared with the `key` field */\nexport type OptimisticMatcher = ((item: any) => boolean) | unknown;\n\n/** Selects list items: the match and the field a plain value is compared with */\nexport type OptimisticSelector = { match: OptimisticMatcher; key?: PropertyKey };\n\ntype Item = Record<PropertyKey, unknown>;\n\nconst isComparableId = (value: unknown): value is string | number =>\n typeof value === \"string\" || typeof value === \"number\";\n\n/**\n * Tells if the item is selected by the match. Plain values are compared with the `key` field of the item, numbers and\n * strings match each other the same way route params do (`\"1\"` matches `1`).\n */\nexport const isOptimisticMatch = (item: unknown, match: OptimisticMatcher, key: PropertyKey = \"id\"): boolean => {\n if (typeof match === \"function\") {\n return !!match(item);\n }\n if (item === null || typeof item !== \"object\") {\n return false;\n }\n const value = (item as Item)[key];\n if (Object.is(value, match)) {\n return true;\n }\n return isComparableId(value) && isComparableId(match) && String(value) === String(match);\n};\n\nconst assertList = (list: unknown): unknown[] => {\n if (!Array.isArray(list)) {\n throw new TypeError(\"Optimistic list helpers need an array, use .list(field) for an array inside an object\");\n }\n return list;\n};\n\nconst assertEntry = (data: unknown): Item => {\n if (data === null || typeof data !== \"object\" || Array.isArray(data)) {\n throw new TypeError(\"Optimistic increment(field, by) needs an object, use increment(match, field, by) on a list\");\n }\n return data as Item;\n};\n\nconst addToField = (item: Item, field: PropertyKey, by: number): Item => {\n const value = item[field];\n return { ...item, [field]: (typeof value === \"number\" ? value : 0) + by };\n};\n\n/**\n * Maps the matching items. The list keeps its reference when nothing matched, so unchanged data produces no write.\n */\nconst mapMatching = (list: unknown, { match, key }: OptimisticSelector, map: (item: Item) => Item): unknown[] => {\n const items = assertList(list);\n let changed = false;\n const next = items.map((item) => {\n if (!isOptimisticMatch(item, match, key)) {\n return item;\n }\n changed = true;\n return map(item as Item);\n });\n return changed ? next : items;\n};\n\nexport const patchItems = (list: unknown, selector: OptimisticSelector, fields: object): unknown[] => {\n return mapMatching(list, selector, (item) => ({ ...item, ...fields }));\n};\n\nexport const insertItem = (list: unknown, item: unknown, options?: OptimisticInsertOptionsType): unknown[] => {\n const items = assertList(list);\n const at = options?.at ?? \"end\";\n if (at === \"start\") {\n return [item, ...items];\n }\n if (at === \"end\") {\n return [...items, item];\n }\n const next = [...items];\n next.splice(at, 0, item);\n return next;\n};\n\nexport const removeItems = (list: unknown, { match, key }: OptimisticSelector): unknown[] => {\n const items = assertList(list);\n const next = items.filter((item) => !isOptimisticMatch(item, match, key));\n return next.length === items.length ? items : next;\n};\n\nexport const incrementItems = (\n list: unknown,\n selector: OptimisticSelector,\n { field, by }: { field: PropertyKey; by: number },\n): unknown[] => {\n return mapMatching(list, selector, (item) => addToField(item, field, by));\n};\n\nexport const incrementField = (data: unknown, field: PropertyKey, by: number): Item => {\n return addToField(assertEntry(data), field, by);\n};\n\n/**\n * Runs a list helper on the array held in `field`. A missing list counts as empty, the object keeps its reference when\n * the list did not change.\n */\nexport const updateListField = (data: unknown, field: PropertyKey, update: (list: unknown[]) => unknown[]): Item => {\n const entry = assertEntry(data);\n const list = entry[field] ?? [];\n const next = update(assertList(list));\n return next === list ? entry : { ...entry, [field]: next };\n};\n","/* eslint-disable max-params -- increment(match, field, by, options) is the public signature of the helper */\nimport type { RequestInstance } from \"request\";\n\nimport type {\n OptimisticFactoryType,\n OptimisticInsertOptionsType,\n OptimisticMatchOptionsType,\n OptimisticOperationCommitType,\n OptimisticOperationRollbackType,\n} from \"./optimistic.types\";\nimport type { OptimisticMatcher } from \"./optimistic.utils\";\nimport {\n incrementField,\n incrementItems,\n insertItem,\n patchItems,\n removeItems,\n updateListField,\n} from \"./optimistic.utils\";\n\n/**\n * Callbacks are stored with an erased mutation type - the mutation type is only checked where they are passed in,\n * which keeps operations of a specific mutation assignable to the erased one.\n */\ntype OptimisticOperationOptions<Data> = {\n target: RequestInstance;\n allVariants: boolean;\n update: (data: Data) => Data;\n onRollback?: OptimisticOperationRollbackType<Data, RequestInstance>;\n onCommit?: OptimisticOperationCommitType<Data, RequestInstance>;\n};\n\n/**\n * One change of one target, built with `optimistic(target)`. Core applies it before the mutation is sent, and runs its\n * `.commit()` on success or its `.rollback()` when the mutation fails, is aborted or removed from the queue.\n * Operations are immutable - `.rollback()` and `.commit()` return a new operation, so one can be reused.\n */\nexport class OptimisticOperation<Data, Mutation extends RequestInstance = RequestInstance> {\n /** @internal */\n readonly target: RequestInstance;\n /** @internal */\n readonly allVariants: boolean;\n /** @internal */\n readonly update: (data: Data) => Data;\n /** @internal */\n readonly onRollback?: OptimisticOperationRollbackType<Data, RequestInstance> = undefined;\n /** @internal */\n readonly onCommit?: OptimisticOperationCommitType<Data, RequestInstance> = undefined;\n\n constructor(options: OptimisticOperationOptions<Data>) {\n this.target = options.target;\n this.allVariants = options.allVariants;\n this.update = options.update;\n this.onRollback = options.onRollback;\n this.onCommit = options.onCommit;\n }\n\n /**\n * Undo of this change, written by hand and run by core when the mutation fails for good, is aborted or removed from\n * the queue. Rollbacks of one mutation run in reverse order of the changes. It receives\n * `{ data, previous, reason, response, request }` and returns the new data; returning nothing leaves the data as it\n * is. Build the result from `data` and use `previous` only to look old values up. Must be synchronous.\n * Without it nothing is undone locally and the target is refetched.\n */\n // Method syntax keeps the mutation type bivariant, so operations typed by a mutation fit erased requests\n rollback(callback: OptimisticOperationRollbackType<Data, Mutation>): OptimisticOperation<Data, Mutation> {\n return new OptimisticOperation({\n target: this.target,\n allVariants: this.allVariants,\n update: this.update,\n onRollback: callback as OptimisticOperationRollbackType<Data, RequestInstance>,\n onCommit: this.onCommit,\n });\n }\n\n /**\n * Runs when the mutation succeeds, before the target is refreshed. It receives `{ data, response, request }` and\n * returns the new data, for example to swap a temporary item for the one from the response. Returning nothing leaves\n * the data as it is. Must be synchronous.\n */\n commit(callback: OptimisticOperationCommitType<Data, Mutation>): OptimisticOperation<Data, Mutation> {\n return new OptimisticOperation({\n target: this.target,\n allVariants: this.allVariants,\n update: this.update,\n onRollback: this.onRollback,\n onCommit: callback as OptimisticOperationCommitType<Data, RequestInstance>,\n });\n }\n}\n\ntype ListUpdate = (list: unknown[]) => unknown[];\n\nconst createTarget = (target: RequestInstance, allVariants: boolean) => {\n const operation = (update: (data: unknown) => unknown) => {\n return new OptimisticOperation<unknown>({ target, allVariants, update });\n };\n\n const createListHelpers = (onList: (update: ListUpdate) => (data: unknown) => unknown) => ({\n patch: (match: OptimisticMatcher, fields: object, options?: OptimisticMatchOptionsType<PropertyKey>) => {\n return operation(onList((list) => patchItems(list, { match, key: options?.key }, fields)));\n },\n insert: (item: unknown, options?: OptimisticInsertOptionsType) => {\n return operation(onList((list) => insertItem(list, item, options)));\n },\n remove: (match: OptimisticMatcher, options?: OptimisticMatchOptionsType<PropertyKey>) => {\n return operation(onList((list) => removeItems(list, { match, key: options?.key })));\n },\n increment: (\n match: OptimisticMatcher,\n field: PropertyKey,\n by: number,\n options?: OptimisticMatchOptionsType<PropertyKey>,\n ) => {\n return operation(onList((list) => incrementItems(list, { match, key: options?.key }, { field, by })));\n },\n });\n\n // The target's data is the list itself\n const listHelpers = createListHelpers((update) => (data) => update(data as unknown[]));\n\n return {\n ...listHelpers,\n set: (updater: (data: unknown) => unknown) => operation(updater),\n // `increment(field, by)` changes the data, `increment(match, field, by)` the matching list items\n increment: (...args: [PropertyKey, number] | [OptimisticMatcher, PropertyKey, number, object?]) => {\n if (args.length >= 3) {\n const [match, field, by, options] = args as [OptimisticMatcher, PropertyKey, number, object?];\n return listHelpers.increment(match, field, by, options);\n }\n const [field, by] = args as [PropertyKey, number];\n return operation((data) => incrementField(data, field, by));\n },\n list: (field: PropertyKey) => {\n return createListHelpers((update) => (data) => updateListField(data, field, update));\n },\n };\n};\n\nconst optimisticFactory = (target: RequestInstance) => createTarget(target, false);\noptimisticFactory.all = (target: RequestInstance) => createTarget(target, true);\n\n/**\n * Describes an optimistic change of a cached request. Return the operations from `setOptimistic` or pass them with the\n * `optimistic` send option, core applies them, runs `.commit()` / `.rollback()` when the mutation settles and refreshes\n * the targets once the last pending mutation on them is done.\n *\n * - `optimistic(getTodos)` - the entry of this request (its params and query params)\n * - `optimistic.all(getTodos)` - every cached variant of it, whatever the query params (filters, infinite pages)\n *\n * Helpers: `set(updater)`, `patch(match, fields)`, `insert(item, { at })`, `remove(match)`,\n * `increment(field, by)` / `increment(match, field, by)` and `.list(\"field\")` for an array inside an object.\n *\n * @example\n * optimistic(getTodos)\n * .patch(params.todoId, payload)\n * .rollback(({ data, previous }) => {\n * const before = previous.find((todo) => todo.id === params.todoId);\n * return data.map((todo) => (todo.id === params.todoId && before ? before : todo));\n * });\n */\nexport const optimistic = optimisticFactory as unknown as OptimisticFactoryType;\n","import type { AdapterInstance, ResponseSuccessType, ResponseType } from \"adapter\";\nimport type { CacheValueType } from \"cache\";\nimport type { ClientInstance } from \"client\";\nimport type {\n OptimisticCallbackResult,\n OptimisticCallbackReturnType,\n OptimisticRollbackArgs,\n RequestInstance,\n} from \"request\";\nimport { getRequestKey, scopeKey, stringifyKey } from \"request\";\nimport { throwOutsideLifecycle } from \"utils\";\n\nimport { OptimisticOperation } from \"./optimistic\";\n\n/**\n * Settlement of optimistic updates.\n *\n * Every cache key changed by pending mutations has a counter. While it is above zero, fetch responses for the key are\n * not written to the cache, and fetches still running when a mutation on the key settles are marked as stale - they\n * started before the change was confirmed or reverted. Once the last mutation settles and the stale fetches are done,\n * the key is refreshed (invalidated) once, so the server's data replaces the optimistic value.\n */\n\ntype KeyState = {\n /** Mutations still pending on the key */\n pending: number;\n /** A settled mutation asked for the refresh */\n refresh: boolean;\n /** Request used to invalidate the key */\n request: RequestInstance;\n};\n\ntype ClientState = {\n keys: Map<string, KeyState>;\n /** Running fetches that started before a mutation on their key settled - request id to storage key */\n staleRequests: Map<string, string>;\n};\n\ntype AppliedOperation = {\n operation: OptimisticOperation<unknown, RequestInstance>;\n storageKey: string;\n /** Request of the changed entry */\n request: RequestInstance;\n previous: unknown;\n};\n\n/** @internal State of one mutation's optimistic updates, from applying them until the mutation settles */\nexport type OptimisticPendingType = {\n client: ClientInstance;\n result: OptimisticCallbackResult<unknown>;\n applied: AppliedOperation[];\n /** Every key the operations target, with the request used to refresh it */\n targets: Map<string, RequestInstance>;\n /** Keys changed by the operations - their fetch responses are held back until the mutation settles */\n guarded: Set<string>;\n /** Keys where user code failed - refreshed whatever the outcome */\n failed: Set<string>;\n};\n\n/** @internal How the mutation settled */\nexport type OptimisticOutcomeType =\n | { type: \"success\"; response: ResponseType<any, any, AdapterInstance>; request: RequestInstance }\n | ({ type: \"rollback\" } & OptimisticRollbackArgs<RequestInstance>);\n\nconst clientStates = new WeakMap<ClientInstance, ClientState>();\n\nconst getClientState = (client: ClientInstance): ClientState => {\n let state = clientStates.get(client);\n if (!state) {\n state = { keys: new Map(), staleRequests: new Map() };\n clientStates.set(client, state);\n }\n return state;\n};\n\n/**\n * Failures of user code (helpers, commits, rollbacks, predicates) are logged and thrown outside of the request\n * lifecycle, like every other user code running in it - the request and the other changes still settle.\n */\nconst reportFailure = (client: ClientInstance, title: string, extra: { error: unknown } & Record<string, unknown>) => {\n client.logger.error({ title, type: \"system\", extra });\n throwOutsideLifecycle(extra.error);\n};\n\nconst readEntry = (client: ClientInstance, storageKey: string) => {\n return client.cache.get<unknown, unknown>(storageKey);\n};\n\n/**\n * Writes the data through the regular cache path, so listeners get one event per change. The entry keeps its\n * timestamps and staleness - an optimistic value doesn't make the entry fresh.\n */\nconst writeData = (request: RequestInstance, entry: CacheValueType<unknown, unknown, AdapterInstance>, data: unknown) => {\n const entryRequest = request.clone({ staleTime: entry.staleTime, cacheTime: entry.cacheTime }) as RequestInstance;\n request.client.cache.set(entryRequest, { ...entry, data });\n};\n\n/**\n * Cache keys targeted by the operation. `optimistic.all()` matches every entry of the same method and endpoint\n * whatever the query params; a custom cache key matches itself and the keys derived from it (infinite pages).\n */\nconst resolveTargets = (client: ClientInstance, operation: OptimisticOperation<unknown, RequestInstance>) => {\n const { target } = operation;\n const targets = new Map<string, RequestInstance>();\n\n if (!operation.allVariants) {\n targets.set(scopeKey(target.cacheKey, target.scope), target);\n return targets;\n }\n\n const isGeneratedKey = target.cacheKey === getRequestKey(target);\n const prefix = isGeneratedKey\n ? `${stringifyKey(target.method)}_${stringifyKey(target.endpoint)}_`\n : `${target.cacheKey}_`;\n\n client.cache.keys().forEach((storageKey) => {\n const entry = client.cache.storage.get<unknown, unknown, AdapterInstance>(storageKey);\n if (!entry || entry.scope !== target.scope) {\n return;\n }\n if (entry.cacheKey === target.cacheKey) {\n targets.set(storageKey, target);\n } else if (entry.cacheKey.startsWith(prefix)) {\n // `setCacheKey` marks the instance it is called on - a clone keeps the user's request untouched\n targets.set(storageKey, target.clone().setCacheKey(entry.cacheKey) as RequestInstance);\n }\n });\n\n return targets;\n};\n\n/**\n * Runs `.rollback()` / `.commit()` of an operation and writes what it returned. User code can't break the settlement:\n * a throw or a promise is reported and the key gets refreshed.\n */\nconst runSettleCallback = (\n pending: OptimisticPendingType,\n { operation, storageKey, request, previous }: AppliedOperation,\n outcome: OptimisticOutcomeType,\n) => {\n const { client } = pending;\n const entry = readEntry(client, storageKey);\n const isCommit = outcome.type === \"success\";\n const title = isCommit ? \"Optimistic commit failed\" : \"Optimistic rollback failed\";\n const run = (data: unknown) => {\n if (outcome.type === \"success\") {\n const response = outcome.response as ResponseSuccessType<unknown, AdapterInstance>;\n return operation.onCommit?.({ data, response, request: outcome.request });\n }\n const { type: _type, ...args } = outcome;\n return operation.onRollback?.({ ...args, data, previous });\n };\n\n // Entry deleted or cache cleared in the meantime - there is nothing to update\n if (!(isCommit ? operation.onCommit : operation.onRollback) || !entry) {\n return;\n }\n\n try {\n const next = run(entry.data);\n\n if (next instanceof Promise) {\n next.catch((error: unknown) => reportFailure(client, title, { error, storageKey }));\n throw new TypeError(\"Optimistic rollback and commit must be synchronous, the returned promise was ignored\");\n }\n if (next !== undefined && next !== entry.data) {\n writeData(request, entry, next);\n }\n } catch (error) {\n reportFailure(client, title, { error, storageKey, request: outcome.request });\n pending.failed.add(storageKey);\n }\n};\n\n/** Rollback of the hand-written object form - runs once, its failure can't affect the request */\nconst runObjectRollback = (pending: OptimisticPendingType, args: OptimisticRollbackArgs<RequestInstance>) => {\n const { client, result } = pending;\n const onFailure = (error: unknown) => {\n reportFailure(client, \"Optimistic rollback failed\", { error, reason: args.reason, request: args.request });\n };\n\n try {\n // Async rollback is not awaited, but its rejection can't stay unhandled\n Promise.resolve(result.rollback?.(args)).catch(onFailure);\n } catch (error) {\n onFailure(error);\n }\n};\n\nconst runObjectInvalidation = ({ client, result }: OptimisticPendingType, request: RequestInstance) => {\n result.invalidate?.forEach((target) => {\n try {\n client.cache.invalidate(target);\n } catch (error) {\n reportFailure(client, \"Optimistic invalidation failed\", { error, target, request });\n }\n });\n};\n\n/**\n * `rollbackOnError` decides about final errors only - aborted and removed requests are always reverted.\n * A predicate that throws is reported and the change is reverted.\n */\nconst shouldRollback = (pending: OptimisticPendingType, outcome: OptimisticRollbackArgs<RequestInstance>) => {\n const { rollbackOnError } = pending.result;\n if (outcome.reason !== \"error\" || rollbackOnError === undefined || rollbackOnError === true) {\n return true;\n }\n if (rollbackOnError === false) {\n return false;\n }\n try {\n return !!rollbackOnError({ response: outcome.response, request: outcome.request });\n } catch (error) {\n reportFailure(pending.client, \"Optimistic rollbackOnError failed\", { error, request: outcome.request });\n return true;\n }\n};\n\nconst getRunningRequestsOnKey = (client: ClientInstance, storageKey: string) => {\n return [...client.fetchDispatcher.getAllRunningRequests(), ...client.submitDispatcher.getAllRunningRequests()].filter(\n ({ request }) => scopeKey(request.cacheKey, request.scope) === storageKey,\n );\n};\n\nconst hasStaleRequests = (state: ClientState, storageKey: string) => {\n return [...state.staleRequests.values()].includes(storageKey);\n};\n\n/** Refreshes the key once nothing pending or stale is left on it */\nconst refreshWhenIdle = (client: ClientInstance, state: ClientState, storageKey: string) => {\n const keyState = state.keys.get(storageKey);\n if (!keyState || keyState.pending > 0 || hasStaleRequests(state, storageKey)) {\n return;\n }\n state.keys.delete(storageKey);\n if (keyState.refresh) {\n client.cache.invalidate(keyState.request);\n }\n};\n\nconst release = (pending: OptimisticPendingType, refresh: boolean) => {\n const { client, targets, failed, guarded } = pending;\n const state = getClientState(client);\n\n targets.forEach((request, storageKey) => {\n const keyState = state.keys.get(storageKey);\n const shouldRefresh = refresh || failed.has(storageKey);\n\n if (!guarded.has(storageKey)) {\n // Nothing was changed here - refresh together with the mutations still pending on the key, or right away\n if (keyState && shouldRefresh) {\n keyState.refresh = true;\n } else if (shouldRefresh) {\n client.cache.invalidate(request);\n }\n return;\n }\n // State was reset by clearing the client\n if (!keyState) {\n return;\n }\n keyState.pending -= 1;\n keyState.refresh = keyState.refresh || shouldRefresh;\n keyState.request = request;\n\n getRunningRequestsOnKey(client, storageKey).forEach(({ requestId }) => {\n state.staleRequests.set(requestId, storageKey);\n });\n\n refreshWhenIdle(client, state, storageKey);\n });\n};\n\n/**\n * @internal\n * Normalizes what `setOptimistic` or the `optimistic` send option returned into the object form.\n */\nexport const getOptimisticResult = (\n value: OptimisticCallbackReturnType<unknown, RequestInstance> | undefined,\n): OptimisticCallbackResult<unknown> => {\n if (Array.isArray(value)) {\n return { updates: value };\n }\n return value || {};\n};\n\n/**\n * @internal\n * Applies the operations of the mutation and registers its target keys as pending. A failing operation is reported,\n * the others still apply.\n */\nexport const applyOptimistic = (\n client: ClientInstance,\n result: OptimisticCallbackResult<unknown>,\n): OptimisticPendingType => {\n const pending: OptimisticPendingType = {\n client,\n result,\n applied: [],\n targets: new Map(),\n guarded: new Set(),\n failed: new Set(),\n };\n const state = getClientState(client);\n\n result.updates?.forEach((value) => {\n try {\n if (!(value instanceof OptimisticOperation)) {\n throw new TypeError(\"Optimistic updates accept operations created with optimistic()\");\n }\n const operation = value as OptimisticOperation<unknown, RequestInstance>;\n\n resolveTargets(client, operation).forEach((request, storageKey) => {\n pending.targets.set(storageKey, request);\n const entry = readEntry(client, storageKey);\n // No data yet - there is nothing to change and nothing to revert\n if (!entry) {\n return;\n }\n try {\n const next = operation.update(entry.data);\n if (next !== entry.data) {\n writeData(request, entry, next);\n }\n pending.applied.push({ operation, storageKey, request, previous: entry.data });\n pending.guarded.add(storageKey);\n } catch (error) {\n reportFailure(client, \"Optimistic update failed\", { error, storageKey });\n pending.failed.add(storageKey);\n }\n });\n } catch (error) {\n reportFailure(client, \"Optimistic update failed\", { error, operation: value });\n }\n });\n\n pending.guarded.forEach((storageKey) => {\n const request = pending.targets.get(storageKey) as RequestInstance;\n const keyState = state.keys.get(storageKey) ?? { pending: 0, refresh: false, request };\n keyState.pending += 1;\n state.keys.set(storageKey, keyState);\n });\n\n return pending;\n};\n\n/**\n * @internal\n * Settles the mutation once. Success runs the commits and invalidations, a final error, abort or queue removal runs the\n * rollbacks in reverse order of application. The targets get refreshed after the last pending mutation on them.\n */\nexport const settleOptimistic = (pending: OptimisticPendingType, outcome: OptimisticOutcomeType) => {\n const { result, applied } = pending;\n const canRefresh = result.revalidate !== false;\n\n if (outcome.type === \"success\") {\n applied.forEach((operation) => runSettleCallback(pending, operation, outcome));\n runObjectInvalidation(pending, outcome.request);\n return release(pending, canRefresh);\n }\n\n const { type: _type, ...args } = outcome;\n if (!shouldRollback(pending, args)) {\n return release(pending, false);\n }\n\n // The latest change is reverted first\n for (let index = applied.length - 1; index >= 0; index -= 1) {\n runSettleCallback(pending, applied[index], outcome);\n }\n runObjectRollback(pending, args);\n return release(pending, canRefresh);\n};\n\n/**\n * @internal\n * Stale response guard, called where the dispatcher writes a response to the cache. A response is discarded when a\n * mutation changed its key and is pending, or when the fetch started before the latest such mutation settled - the\n * refresh after the mutation supplies current data. Keys that had no data when the change was applied are not\n * guarded, so a first load is never held back. Manual cache writes don't go through this check.\n */\nexport const isStaleOptimisticResponse = (\n client: ClientInstance,\n request: RequestInstance,\n requestId: string,\n): boolean => {\n const state = clientStates.get(client);\n if (!state) {\n return false;\n }\n\n const storageKey = scopeKey(request.cacheKey, request.scope);\n const isMarked = state.staleRequests.delete(requestId);\n const isPending = (state.keys.get(storageKey)?.pending ?? 0) > 0;\n if (isMarked) {\n refreshWhenIdle(client, state, storageKey);\n }\n\n return isMarked || isPending;\n};\n\n/** @internal Drops the pending state of the client, its mutations will never settle after clearing it */\nexport const resetOptimisticState = (client: ClientInstance) => {\n clientStates.delete(client);\n};\n","import { getErrorMessage } from \"adapter\";\nimport type { AdapterInstance, ProgressType, RequestResponseType, ResponseType } from \"adapter\";\nimport { SAFE_HTTP_METHODS } from \"constants/http.constants\";\nimport type { Dispatcher } from \"dispatcher\";\nimport type { RequestResponseEventType } from \"managers\";\nimport type { OptimisticPendingType } from \"optimistic\";\nimport { applyOptimistic, getOptimisticResult, optimistic, settleOptimistic } from \"optimistic\";\nimport type { ExtractAdapterType, ExtractErrorType } from \"types\";\nimport { runUserCode } from \"utils\";\n\nimport type {\n OptimisticCallbackResult,\n OptimisticSendOptionType,\n ProgressEventType,\n RequestInstance,\n RequestJSON,\n RequestSendActionsType,\n RequestSendOptionsType,\n RetryTimeFunctionType,\n} from \"./request.types\";\n\ntype MappedResponse =\n | ResponseType<any, any, AdapterInstance>\n | Promise<ResponseType<any, any, AdapterInstance>>\n | undefined;\n\n/**\n * Turns query params given as a callback into data with the adapter's resolver, so a request never stores a function.\n * Without a resolver the value is kept as given.\n */\nexport const resolveQueryParams = <T>(\n client: { adapter: Pick<AdapterInstance, \"unstable_queryParamsResolver\"> },\n queryParams: T,\n): T => {\n const resolver = client.adapter.unstable_queryParamsResolver;\n if (typeof queryParams === \"function\" && resolver) {\n return resolver(queryParams as (...args: any[]) => unknown) as T;\n }\n return queryParams;\n};\n\nexport const scopeKey = (key: string, scope: string | null): string => {\n return scope ? `${scope}__${key}` : key;\n};\n\nexport const stringifyKey = (value: unknown): string => {\n try {\n if (typeof value === \"string\") {\n return value;\n }\n if (value === undefined || value === null) {\n return \"\";\n }\n const data = JSON.stringify(value);\n if (typeof data !== \"string\") {\n throw new TypeError();\n }\n return data;\n } catch {\n return \"\";\n }\n};\n\nexport const getProgressValue = ({ loaded, total }: ProgressEventType): number => {\n if (!loaded || !total) {\n return 0;\n }\n return Number(((loaded * 100) / total).toFixed(0));\n};\n\nexport const getRequestEta = (\n startDate: Date,\n progressDate: Date,\n { total, loaded }: ProgressEventType,\n): { sizeLeft: number; timeLeft: number | null } => {\n const timeElapsed = +progressDate - +startDate || 1;\n const uploadSpeed = loaded / timeElapsed;\n const totalValue = Math.max(total, loaded);\n const sizeLeft = totalValue - loaded;\n const estimatedTimeValue = uploadSpeed ? sizeLeft / uploadSpeed : null;\n const timeLeft = totalValue === loaded ? 0 : estimatedTimeValue;\n\n return { timeLeft, sizeLeft };\n};\n\nexport const getProgressData = (\n requestStartTime: Date,\n progressDate: Date,\n progressEvent: ProgressEventType,\n): ProgressType => {\n const { total, loaded } = progressEvent;\n if (Number.isNaN(total) || Number.isNaN(loaded)) {\n return {\n progress: 0,\n timeLeft: 0,\n sizeLeft: 0,\n total: 0,\n loaded: 0,\n startTimestamp: +requestStartTime,\n };\n }\n\n const { timeLeft, sizeLeft } = getRequestEta(requestStartTime, progressDate, progressEvent);\n\n return {\n progress: getProgressValue(progressEvent),\n timeLeft,\n sizeLeft,\n total,\n loaded,\n startTimestamp: +requestStartTime,\n };\n};\n\n// Keys\nexport const getSimpleKey = (request: RequestInstance | RequestJSON<RequestInstance>): string => {\n return `${request.method}_${request.requestOptions.endpoint}_${request.cancelable}`;\n};\n\n/**\n * Cache instance for individual request that collects individual requests responses from\n * the same endpoint (they may differ base on the custom key, endpoint params etc)\n * @param request\n * @param useInitialValues\n * @returns\n */\nexport const getRequestKey = (\n request: RequestInstance | RequestJSON<RequestInstance>,\n useInitialValues?: boolean,\n): string => {\n /**\n * Below stringified values allow to match the response by method, endpoint and query params.\n * That's because we have shared endpoint, but data with queryParams '?user=1' will not match regular request without queries.\n * We want both results to be cached in separate places to not override each other.\n *\n * Values to be stringified:\n *\n * endpoint: string;\n * queryParams: string;\n * params: string;\n */\n const methodKey = stringifyKey(request.method);\n const endpointKey = useInitialValues ? request.requestOptions.endpoint : stringifyKey(request.endpoint);\n const queryParamsKey = useInitialValues ? \"\" : stringifyKey(request.queryParams);\n\n return `${methodKey}_${endpointKey}_${queryParamsKey}`;\n};\n\nexport const getRequestDispatcher = <Request extends RequestInstance>(\n request: Request,\n dispatcherType: \"auto\" | \"fetch\" | \"submit\" = \"auto\",\n): [Dispatcher<ExtractAdapterType<Request>>, isFetchDispatcher: boolean] => {\n const { fetchDispatcher, submitDispatcher } = request.client;\n const isSafeRead = SAFE_HTTP_METHODS.includes(request.method as string);\n const isFetchDispatcher = (dispatcherType === \"auto\" && isSafeRead) || dispatcherType === \"fetch\";\n const dispatcher = isFetchDispatcher ? fetchDispatcher : submitDispatcher;\n\n return [dispatcher, isFetchDispatcher];\n};\n\n/**\n * Runs the response mapper of the request. Mapper is user code running in the middle of the response handling,\n * so its failure is logged and ends up as a failed response carrying the thrown value as the `error`.\n * Failures are always delivered through a promise, so sync and async mappers fail the same way.\n * @internal\n * @param request request with the optional response mapper\n * @param response response to be mapped\n * @returns mapped response, promise of it for async and failed mappers, `undefined` when there is no mapper\n */\nexport const runResponseMapper = <Request extends RequestInstance>(\n request: Request,\n response: ResponseType<any, any, AdapterInstance>,\n): MappedResponse => {\n const getFailedResponse = (error: unknown) => {\n request.client.logger.error({\n title: \"Response mapper failed\",\n type: \"system\",\n extra: { error, request, response },\n });\n\n return { ...response, data: null, error, success: false } as ResponseType<any, any, AdapterInstance>;\n };\n\n try {\n const mapping = request.unstable_responseMapper?.(response as ResponseType<any, any, ExtractAdapterType<Request>>);\n\n return mapping instanceof Promise ? mapping.catch(getFailedResponse) : mapping;\n } catch (error) {\n return Promise.resolve(getFailedResponse(error));\n }\n};\n\nexport const mapResponseForSend = async <Request extends RequestInstance>(\n request: Request,\n response: ResponseType<any, any, AdapterInstance>,\n): Promise<RequestResponseType<Request>> => {\n const mapping = runResponseMapper(request, response);\n\n if (mapping instanceof Promise) {\n return (await mapping) as RequestResponseType<Request>;\n }\n\n return (mapping || response) as RequestResponseType<Request>;\n};\n\n/**\n * Passes the lifecycle events of one request id to the callbacks given to `send()` / `exec()` and to the request\n * `$hooks`. Returns the function that removes the listeners.\n */\nexport const subscribeRequestCallbacks = <Request extends RequestInstance>({\n request,\n requestId,\n options,\n mutationContext,\n}: {\n request: Request;\n requestId: string;\n options: RequestSendActionsType<Request> | undefined;\n mutationContext?: OptimisticCallbackResult<any>;\n}) => {\n const { requestManager } = request.client;\n const { $hooks } = request;\n\n const unmounts = [\n requestManager.events.onRequestStartById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n runUserCode(() => options?.onRequestStart?.(enriched));\n runUserCode(() => $hooks.__emit(\"onRequestStart\", enriched));\n }),\n requestManager.events.onResponseStartById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n runUserCode(() => options?.onResponseStart?.(enriched));\n runUserCode(() => $hooks.__emit(\"onResponseStart\", enriched));\n }),\n requestManager.events.onUploadProgressById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n runUserCode(() => options?.onUploadProgress?.(enriched));\n runUserCode(() => $hooks.__emit(\"onUploadProgress\", enriched));\n }),\n requestManager.events.onDownloadProgressById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n runUserCode(() => options?.onDownloadProgress?.(enriched));\n runUserCode(() => $hooks.__emit(\"onDownloadProgress\", enriched));\n }),\n // Failed attempts which are retried do not reach `onResponse` - this is how they are announced\n requestManager.events.onRetryById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n runUserCode(() => options?.onRetry?.(enriched));\n runUserCode(() => $hooks.__emit(\"onRetry\", enriched));\n }),\n ];\n\n return () => unmounts.forEach((unmount) => unmount());\n};\n\n/**\n * Calls `onAbort` once when the signal of the caller aborts - right away when it is aborted already. The signal only\n * triggers the abort controller HyperFetch keeps for the request, so it ends like `request.abort()` does. Returns the\n * function that stops listening.\n */\nexport const linkAbortSignal = (signal: AbortSignal | undefined, onAbort: () => void) => {\n if (!signal) {\n return () => {};\n }\n if (signal.aborted) {\n onAbort();\n return () => {};\n }\n signal.addEventListener(\"abort\", onAbort, { once: true });\n return () => signal.removeEventListener(\"abort\", onAbort);\n};\n\n/** Response of a call that was aborted before the adapter could answer it - the same as the adapter gives an abort */\nexport const getAbortedResponse = <Request extends RequestInstance>(request: Request): RequestResponseType<Request> => {\n const { adapter } = request.client;\n return {\n data: null,\n error: adapter.unstable_internalErrorMapping(getErrorMessage(\"abort\")) as ExtractErrorType<Request>,\n status: adapter.systemErrorStatus,\n success: false,\n extra: adapter.systemErrorExtra,\n requestTimestamp: Date.now(),\n responseTimestamp: Date.now(),\n };\n};\n\nexport const sendRequest = async <Request extends RequestInstance>(\n request: Request,\n options?: RequestSendOptionsType<Request>,\n): Promise<RequestResponseType<Request>> => {\n const { client } = request;\n const { requestManager } = client;\n const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);\n const signal = options?.signal;\n\n // Nothing is queued, sent or optimistically changed for a call that was aborted before it started\n if (signal?.aborted) {\n return getAbortedResponse(request);\n }\n\n let mutationContext: OptimisticCallbackResult<any> | undefined;\n let pendingOptimistic: OptimisticPendingType | undefined;\n // The per-call option replaces the optimistic callback of the request\n const optimisticSource = (options?.optimistic ?? request.optimistic) as\n | OptimisticSendOptionType<RequestInstance>\n | undefined;\n\n if (optimisticSource) {\n try {\n const result = Array.isArray(optimisticSource)\n ? optimisticSource\n : optimisticSource({\n request,\n client: request.client,\n payload: request.payload,\n params: request.params,\n queryParams: request.queryParams,\n optimistic,\n });\n // Synchronous callbacks change the cache within the send() call, async ones once they resolve\n mutationContext = getOptimisticResult(result instanceof Promise ? await result : result);\n } catch (error) {\n return {\n data: null,\n error: new Error(\n `Optimistic callback failed: ${error instanceof Error ? error.message : error}`,\n ) as unknown as ExtractErrorType<Request>,\n status: null,\n success: false,\n extra: client.adapter.defaultExtra,\n requestTimestamp: Date.now(),\n responseTimestamp: Date.now(),\n };\n }\n pendingOptimistic = applyOptimistic(client, mutationContext);\n }\n\n return new Promise<RequestResponseType<Request>>((resolve) => {\n // The dispatcher is done with the request - removal from the queue that follows is not a separate outcome\n let isResolved = false;\n let isDelivered = false;\n let isSettled = false;\n const queryKey = scopeKey(request.queryKey, request.scope);\n // A deduplicated call gets the id of the request it joined, which was in the queue before\n const queuedIds = signal ? new Set(dispatcher.getQueue(queryKey).requests.map((item) => item.requestId)) : null;\n const requestId = dispatcher.add(request);\n const isJoined = !!queuedIds?.has(requestId);\n // Set when the signal of the caller took the request out of the queue before it was sent\n let isRemovedBySignal = false;\n let unlinkSignal = () => {};\n const { $hooks } = request;\n\n // Failed attempts stay in the dispatcher queue when they are going to be sent again\n const getWillBeResent = ({ response, details }: RequestResponseEventType<Request>) => {\n if (response.success || details.isCanceled) {\n return false;\n }\n // One that was taken out of the queue while it was running (cleared queue) has just given its last response\n if (!dispatcher.getRequest(queryKey, requestId)) {\n return false;\n }\n return details.willRetry || (request.offline && details.isOffline);\n };\n\n // Settlement and delivery read the same event - the mapper has to run only once per response\n const mappings = new WeakMap<RequestResponseEventType<Request>, MappedResponse>();\n const getMapping = (values: RequestResponseEventType<Request>) => {\n if (!mappings.has(values)) {\n mappings.set(values, runResponseMapper(request, values.response));\n }\n return mappings.get(values);\n };\n\n // Attached ahead of `onBeforeSent`, so listeners added there already observe the settled cache\n const unmountSettlement = pendingOptimistic\n ? requestManager.events.onResponseById<Request>(requestId, (values) => {\n const pending = pendingOptimistic as OptimisticPendingType;\n const willBeResent = getWillBeResent(values);\n\n const settle = (response: ResponseType<any, any, AdapterInstance>) => {\n if (isSettled || (!response.success && willBeResent)) {\n return;\n }\n isSettled = true;\n\n if (values.details.isCanceled) {\n settleOptimistic(pending, { type: \"rollback\", reason: \"abort\", response, request });\n } else if (response.success) {\n settleOptimistic(pending, { type: \"success\", response, request });\n } else {\n settleOptimistic(pending, { type: \"rollback\", reason: \"error\", response, request });\n }\n };\n\n const mapping = getMapping(values);\n if (mapping instanceof Promise) {\n mapping.then(settle);\n } else {\n settle(mapping || values.response);\n }\n })\n : undefined;\n\n const beforeSentData = { requestId, request, mutationContext };\n runUserCode(() => options?.onBeforeSent?.(beforeSentData));\n runUserCode(() => $hooks.__emit(\"onBeforeSent\", beforeSentData));\n\n const unmountCallbacks = subscribeRequestCallbacks({ request, requestId, options, mutationContext });\n\n // When resolved\n const unmountResponse = requestManager.events.onResponseById<Request>(requestId, (values) => {\n const { response } = values;\n const willBeResent = getWillBeResent(values);\n isResolved = !willBeResent;\n const enrichedValues = { ...values, mutationContext };\n\n const mapping = getMapping(values);\n\n const handleResponse = (success: boolean, data: ResponseType<any, any, ExtractAdapterType<Request>>) => {\n // Retries and offline postponing end with another response we need to listen for\n if (isDelivered || (!success && willBeResent)) {\n return;\n }\n isDelivered = true;\n\n runUserCode(() => options?.onResponse?.(enrichedValues));\n runUserCode(() => $hooks.__emit(\"onResponse\", enrichedValues));\n resolve(data);\n\n // Unmount Listeners\n // eslint-disable-next-line @typescript-eslint/no-use-before-define, @typescript-eslint/no-use-before-define\n umountAll();\n };\n\n // Create async await ONLY when we make a promise mapper\n if (mapping instanceof Promise) {\n (async () => {\n const responseData = await mapping;\n\n const { success } = responseData;\n handleResponse(success, responseData as ResponseType<any, any, ExtractAdapterType<Request>>);\n })();\n }\n // For sync mapping operations we should not use async actions\n else {\n const data = mapping || response;\n const { success } = data;\n handleResponse(success, data);\n }\n });\n\n // When removed from queue storage we need to clean event listeners and return proper error\n const unmountRemoveQueueElement = requestManager.events.onRemoveById<Request>(requestId, (data) => {\n if (!isResolved) {\n isResolved = true;\n isDelivered = true;\n\n // Taken out of the queue by the signal of the caller, it ends the same way an aborted request does\n const removedResponse: RequestResponseType<Request> = isRemovedBySignal\n ? getAbortedResponse(request)\n : {\n data: null,\n status: null,\n success: false,\n error: getErrorMessage(\"deleted\") as unknown as ExtractErrorType<Request>,\n extra: request.client.adapter.defaultExtra,\n requestTimestamp: Date.now(),\n responseTimestamp: Date.now(),\n };\n\n if (pendingOptimistic && !isSettled) {\n isSettled = true;\n settleOptimistic(\n pendingOptimistic,\n isRemovedBySignal\n ? { type: \"rollback\", reason: \"abort\", response: removedResponse, request }\n : { type: \"rollback\", reason: \"removed\", request },\n );\n }\n\n const enriched = { ...data, mutationContext };\n runUserCode(() => options?.onRemove?.(enriched));\n runUserCode(() => $hooks.__emit(\"onRemove\", enriched));\n resolve(removedResponse);\n\n // Unmount Listeners\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n umountAll();\n }\n });\n\n // Linked last - an abort can remove the request synchronously and the listeners above have to observe it\n unlinkSignal = linkAbortSignal(signal, () => {\n if (isDelivered) {\n return;\n }\n // The joined request belongs to the other callers as well - only this call stops waiting for it\n if (isJoined) {\n isResolved = true;\n isDelivered = true;\n const aborted = getAbortedResponse(request);\n if (pendingOptimistic && !isSettled) {\n isSettled = true;\n settleOptimistic(pendingOptimistic, { type: \"rollback\", reason: \"abort\", response: aborted, request });\n }\n resolve(aborted);\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n umountAll();\n return;\n }\n const abortKey = scopeKey(request.abortKey, request.scope);\n // A running request is aborted like `request.abort()` does, only this one by its id\n if (dispatcher.hasRunningRequest(queryKey, requestId)) {\n requestManager.abortByRequestId(abortKey, requestId);\n return;\n }\n // A queued one, or one waiting for its retry or for the connection, is not sent at all\n isRemovedBySignal = true;\n dispatcher.delete(queryKey, requestId, abortKey);\n });\n\n function umountAll() {\n unmountSettlement?.();\n unmountCallbacks();\n unmountResponse();\n unmountRemoveQueueElement();\n unlinkSignal();\n }\n });\n};\n\n/** Above this exponent `min * 2 ** attempt` is past any sane maximum, and a larger one only risks Infinity */\nconst MAX_BACKOFF_EXPONENT = 30;\n\n/**\n * Retry time that grows exponentially with every attempt: `min * 2 ** attempt`, never above `max`. With `jitter` (the\n * default) the delay is a random value from `min` up to that window, so the clients that failed together do not all\n * retry at the same moment.\n *\n * @example\n * client.createRequest()({ endpoint: \"/users\", retry: 5, retryTime: exponentialBackoff({ min: 500, max: 10_000 }) });\n */\nexport const exponentialBackoff = ({\n min = 500,\n max = 30_000,\n jitter = true,\n random = Math.random,\n}: {\n /** Delay of the first retry in milliseconds. @default 500 */\n min?: number;\n /** Longest delay in milliseconds. @default 30000 */\n max?: number;\n /** Spread the delays randomly between `min` and the exponential window. @default true */\n jitter?: boolean;\n /** Source of the randomness, for deterministic tests. @default Math.random */\n random?: () => number;\n} = {}): RetryTimeFunctionType => {\n return ({ attempt }) => {\n const floor = Math.max(0, min);\n const exponent = Math.min(Math.max(0, attempt), MAX_BACKOFF_EXPONENT);\n const exponential = floor * 2 ** exponent;\n\n if (!jitter) {\n return Math.min(max, exponential);\n }\n const window = Math.max(0, Math.min(max - floor, exponential));\n return Math.round(floor + random() * window);\n };\n};\n","import type { RequestResponseType, ResponseErrorType, ResponseSuccessType, ResponseType } from \"adapter\";\nimport type { ClientInstance } from \"client\";\nimport { Time } from \"constants/time.constants\";\nimport type { MockerConfigType, MockResponseType } from \"mocker\";\nimport type {\n ExtractAdapterType,\n ExtractClientAdapterType,\n ExtractClientGlobalError,\n ExtractEndpointType,\n ExtractParamsType,\n ExtractPayloadType,\n ExtractQueryParamsType,\n EmptyTypes,\n ExtractAdapterMethodType,\n ExtractAdapterOptionsType,\n HydrateDataType,\n SyncOrAsync,\n} from \"types\";\nimport { runUserCode } from \"utils\";\n\nimport type { RequestHooks } from \"./request.hooks\";\nimport { createRequestHooks } from \"./request.hooks\";\n/* eslint-disable max-lines */\nimport type {\n RequestSendOptionsType,\n ParamsType,\n RequestSendType,\n PayloadType,\n RequestJSON,\n RequestOptionsType,\n RetryTimeType,\n RequestConfigurationType,\n PayloadMapperType,\n RequestInstance,\n RequestMapper,\n ResponseMapper,\n ExtractUrlParams,\n RetryOnErrorCallbackType,\n OptimisticCallback,\n} from \"./request.types\";\nimport {\n linkAbortSignal,\n mapResponseForSend,\n resolveQueryParams,\n scopeKey,\n sendRequest,\n subscribeRequestCallbacks,\n} from \"./request.utils\";\n\ntype ClientAdapterOptions<C extends ClientInstance> = ExtractAdapterOptionsType<ExtractClientAdapterType<C>>;\ntype ClientAdapterMethod<C extends ClientInstance> = ExtractAdapterMethodType<ExtractClientAdapterType<C>>;\ntype ClientRequestOptions<E, C extends ClientInstance> = RequestOptionsType<\n E,\n ClientAdapterOptions<C>,\n ClientAdapterMethod<C>\n>;\n\n/**\n * Request is a class that represents a request sent to the server. It contains all the necessary information to make a request, like endpoint, method, headers, data, and much more.\n * It is executed at any time via methods like `send` or `exec`.\n *\n * We can set it up with options like endpoint, method, headers and more.\n * We can choose some of advanced settings like cache, invalidation patterns, concurrency, retries and much, much more.\n *\n * @info We should not use this class directly in the standard development flow.\n * We can initialize it using the `createRequest` method on the **Client** class.\n *\n * @attention The most important thing about the request is that it keeps data in the format that can be dumped.\n * This is necessary for the persistence and different dispatcher storage types.\n * This class doesn't have any callback methods by design and communicate with dispatcher and cache by events.\n *\n * It should be serializable to JSON and deserializable back to the class.\n * Serialization should not affect the result of the request, so it's methods and functional part should be only syntax sugar for given runtime.\n */\n\nexport class Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint extends string,\n Client extends ClientInstance,\n HasPayload extends true | false = false,\n HasParams extends true | false = false,\n HasQuery extends true | false = false,\n MutationContext = undefined,\n> {\n endpoint: Endpoint;\n headers?: HeadersInit = undefined;\n auth: boolean;\n method: ClientAdapterMethod<Client>;\n params: ExtractUrlParams<Endpoint> | EmptyTypes;\n payload: PayloadType<Payload>;\n queryParams: QueryParams | EmptyTypes;\n options?: ClientAdapterOptions<Client> | undefined = undefined;\n cancelable: boolean;\n retry: number;\n retryTime: RetryTimeType;\n cacheTime: number;\n cache: boolean;\n staleTime: number;\n queued: boolean;\n offline: boolean;\n abortKey: string;\n cacheKey: string;\n queryKey: string;\n used: boolean;\n deduplicate: boolean;\n deduplicateTime: number | null;\n structuralSharing: boolean;\n throwOnError: boolean;\n scope: string | null;\n\n /**\n * Instance-level lifecycle hooks. These callbacks fire for every `send()` / `exec()` call\n * made on this request instance (and its clones), without needing to pass them to `send()` each time.\n * Useful for cross-cutting concerns like logging, analytics, or toast notifications.\n *\n * Each method registers a callback and returns an unsubscribe function.\n * Multiple listeners per hook are supported.\n */\n $hooks: RequestHooks<RequestInstance> = createRequestHooks();\n\n isMockerEnabled = false;\n\n static readonly OPTIONAL_FIELDS = [\n \"unstable_mock\",\n \"unstable_payloadMapper\",\n \"unstable_requestMapper\",\n \"unstable_responseMapper\",\n \"retryOnError\",\n \"optimistic\",\n ] as const;\n\n // The `= undefined` initializers below are load-bearing. Metro (React Native) compiles\n // class properties in loose mode, which drops field declarations that have no initializer,\n // and the SDK proxy relies on an `in` check to tell request properties apart from deeper\n // API path segments (see OPTIONAL_REQUEST_FIELDS in sdk/sdk.ts).\n unstable_mock?: {\n fn: (options: {\n request: RequestInstance;\n requestId: string;\n }) => MockResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;\n config: MockerConfigType;\n } = undefined;\n /** @internal */\n unstable_payloadMapper?: PayloadMapperType<Payload> = undefined;\n /** @internal */\n unstable_requestMapper?: RequestMapper<any, any> = undefined;\n /** @internal */\n unstable_responseMapper?: ResponseMapper<this, ResponseSuccessType<any, any> | ResponseErrorType<any, any>> =\n undefined;\n /** @internal */\n retryOnError?: RetryOnErrorCallbackType<RequestInstance> = undefined;\n /** @internal */\n optimistic?: OptimisticCallback<RequestInstance, any> = undefined;\n\n unstable_hasParams: HasParams = false as HasParams;\n unstable_hasPayload: HasPayload = false as HasPayload;\n unstable_hasQuery: HasQuery = false as HasQuery;\n unstable_hasMutationContext: MutationContext = undefined as MutationContext;\n\n private updatedAbortKey: boolean;\n private updatedCacheKey: boolean;\n private updatedQueryKey: boolean;\n\n constructor(\n readonly client: Client,\n readonly requestOptions: ClientRequestOptions<Endpoint, Client>,\n readonly initialRequestConfiguration?:\n | RequestConfigurationType<\n Payload,\n Endpoint extends string ? ExtractUrlParams<Endpoint> : never,\n QueryParams,\n Endpoint,\n ClientAdapterOptions<Client>,\n ClientAdapterMethod<Client>\n >\n | undefined,\n ) {\n const configuration: ClientRequestOptions<Endpoint, Client> = {\n ...(this.client.adapter.unstable_getRequestDefaults?.(requestOptions) as ClientRequestOptions<Endpoint, Client>),\n ...requestOptions,\n };\n const {\n endpoint,\n headers,\n auth = true,\n method = client.adapter.defaultMethod,\n options,\n cancelable = false,\n retry = 0,\n retryTime = 500,\n cacheTime = Time.MIN * 5,\n cache = true,\n staleTime = Time.MIN * 5,\n queued = false,\n offline = true,\n abortKey,\n cacheKey,\n queryKey,\n deduplicate = false,\n deduplicateTime = null,\n structuralSharing = true,\n throwOnError = false,\n } = configuration;\n this.endpoint = initialRequestConfiguration?.endpoint ?? endpoint;\n this.headers = initialRequestConfiguration?.headers ?? headers;\n this.auth = initialRequestConfiguration?.auth ?? auth;\n this.method = method as ExtractAdapterMethodType<ExtractClientAdapterType<Client>>;\n this.params = initialRequestConfiguration?.params;\n this.payload = initialRequestConfiguration?.payload;\n this.queryParams = resolveQueryParams(client, initialRequestConfiguration?.queryParams);\n this.options = initialRequestConfiguration?.options ?? options;\n this.cancelable = initialRequestConfiguration?.cancelable ?? cancelable;\n this.retry = initialRequestConfiguration?.retry ?? retry;\n this.retryTime = initialRequestConfiguration?.retryTime ?? retryTime;\n this.cacheTime = initialRequestConfiguration?.cacheTime ?? cacheTime;\n this.cache = initialRequestConfiguration?.cache ?? cache;\n this.staleTime = initialRequestConfiguration?.staleTime ?? staleTime;\n this.queued = initialRequestConfiguration?.queued ?? queued;\n this.offline = initialRequestConfiguration?.offline ?? offline;\n this.abortKey = initialRequestConfiguration?.abortKey ?? abortKey ?? this.client.unstable_abortKeyMapper(this);\n this.cacheKey = initialRequestConfiguration?.cacheKey ?? cacheKey ?? this.client.unstable_cacheKeyMapper(this);\n this.queryKey = initialRequestConfiguration?.queryKey ?? queryKey ?? this.client.unstable_queryKeyMapper(this);\n this.used = initialRequestConfiguration?.used ?? false;\n this.deduplicate = initialRequestConfiguration?.deduplicate ?? deduplicate;\n this.deduplicateTime = initialRequestConfiguration?.deduplicateTime ?? deduplicateTime;\n this.structuralSharing = initialRequestConfiguration?.structuralSharing ?? structuralSharing;\n this.throwOnError = initialRequestConfiguration?.throwOnError ?? throwOnError;\n this.scope = initialRequestConfiguration?.scope ?? null;\n this.updatedAbortKey = initialRequestConfiguration?.updatedAbortKey ?? false;\n this.updatedCacheKey = initialRequestConfiguration?.updatedCacheKey ?? false;\n this.updatedQueryKey = initialRequestConfiguration?.updatedQueryKey ?? false;\n }\n\n /** Set the request headers. Returns a cloned request with the new headers applied. */\n public setHeaders = (headers: HeadersInit) => {\n return this.clone({ headers });\n };\n\n /** Set whether authentication interceptors should run for this request. */\n public setAuth = (auth: boolean) => {\n return this.clone({ auth });\n };\n\n /** Set the URL path parameters (e.g., `:userId`). */\n public setParams = <P extends ExtractParamsType<this>>(params: P) => {\n return this.clone<HasPayload, P extends null ? false : true, HasQuery>({ params });\n };\n\n /** Set the request body payload. Passing `null` removes the payload set before. */\n public setPayload = <P extends Payload>(payload: P) => {\n return this.clone<P extends null ? false : true, HasParams, HasQuery>({\n payload,\n });\n };\n\n /** Set the query parameters appended to the URL. */\n public setQueryParams = (queryParams: QueryParams) => {\n return this.clone<HasPayload, HasParams, true>({ queryParams });\n };\n\n /** Set adapter-specific options (e.g., axios config, fetch init). */\n public setOptions = (options: ClientAdapterOptions<Client>) => {\n return this.clone<HasPayload, HasParams, true>({ options });\n };\n\n /**\n * Set a scope identifier for this request.\n * All keys (cache, queue, abort) are prefixed with this scope, isolating\n * the request from other scopes. In \"server\" client mode, setting a scope\n * also enables caching (which is otherwise disabled to prevent cross-request leaks).\n */\n public setScope = (scopeId: string) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n cloned.scope = scopeId;\n return cloned;\n };\n\n /** Set whether in-flight requests with the same abort key are cancelled when a new one is dispatched. */\n public setCancelable = (cancelable: boolean) => {\n return this.clone({ cancelable });\n };\n\n /** Set the number of retry attempts on failure. */\n public setRetry = (retry: ClientRequestOptions<Endpoint, Client>[\"retry\"]) => {\n return this.clone({ retry });\n };\n\n /** Set the delay in milliseconds between retry attempts, or a function that returns it for each attempt. */\n public setRetryTime = (retryTime: ClientRequestOptions<Endpoint, Client>[\"retryTime\"]) => {\n return this.clone({ retryTime });\n };\n\n /**\n * Set a callback that controls whether a failed request should be retried.\n * Called on each failed attempt before scheduling the next retry.\n * Return `true` to allow the retry, `false` to stop retrying immediately.\n */\n public setRetryOnError = (\n callback: RetryOnErrorCallbackType<\n Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>\n >,\n ) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n cloned.retryOnError = callback as RetryOnErrorCallbackType<RequestInstance>;\n return cloned;\n };\n\n /**\n * Configure optimistic update behavior for this request.\n * The callback runs before the request is sent and receives `{ request, client, payload, params, queryParams,\n * optimistic }`. A synchronous callback changes the cache within the `send()` call.\n *\n * Return an array of changes built with `optimistic()` - core applies them, runs their `.commit()` on success or\n * `.rollback()` on final failure, abort or queue removal, and refreshes the targets after the last pending mutation\n * on them. Or return an object with `updates`, `context` (available in lifecycle callbacks as `mutationContext`),\n * `rollback` (called once on failure, abort or queue removal), `invalidate` (requests invalidated on success),\n * `rollbackOnError` and `revalidate`.\n * Everything runs for every way of sending the request, not only inside of framework hooks.\n *\n * @example\n * toggleTodo.setOptimistic(({ params, payload }) => [optimistic(getTodos).patch(params.todoId, payload)]);\n */\n public setOptimistic = <Ctx = undefined>(callback: OptimisticCallback<this, Ctx>) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n cloned.optimistic = callback as OptimisticCallback<RequestInstance, any>;\n return cloned as unknown as Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint,\n Client,\n HasPayload,\n HasParams,\n HasQuery,\n Ctx\n >;\n };\n\n /** Set how long (in ms) the response remains in cache before being garbage collected. */\n public setCacheTime = (cacheTime: ClientRequestOptions<Endpoint, Client>[\"cacheTime\"]) => {\n return this.clone({ cacheTime });\n };\n\n /** Set whether this request should use the cache. */\n public setCache = (cache: ClientRequestOptions<Endpoint, Client>[\"cache\"]) => {\n return this.clone({ cache });\n };\n\n /** Set how long (in ms) cached data is considered fresh before triggering a revalidation. */\n public setStaleTime = (staleTime: ClientRequestOptions<Endpoint, Client>[\"staleTime\"]) => {\n return this.clone({ staleTime });\n };\n\n /** Set whether the request should be queued and executed sequentially rather than immediately. */\n public setQueued = (queued: boolean) => {\n return this.clone({ queued });\n };\n\n /** Override the abort key used to cancel this request. */\n public setAbortKey = (abortKey: string) => {\n return this.clone({ abortKey, updatedAbortKey: true });\n };\n\n /** Override the cache key used to store/retrieve the response. */\n public setCacheKey = (cacheKey: string) => {\n return this.clone({ cacheKey, updatedCacheKey: true });\n };\n\n /** Override the query key that identifies this request in the dispatcher queue. */\n public setQueryKey = (queryKey: string) => {\n return this.clone({ queryKey, updatedQueryKey: true });\n };\n\n /** Enable or disable request deduplication. When enabled, concurrent identical requests share a single response. */\n public setDeduplicate = (deduplicate: boolean) => {\n return this.clone({ deduplicate });\n };\n\n /** Set the time window (in ms) during which identical requests are deduplicated. */\n public setDeduplicateTime = (deduplicateTime: number) => {\n return this.clone({ deduplicateTime });\n };\n\n /** Enable or disable structural sharing - keeping references of unchanged parts of the response data in cache. */\n public setStructuralSharing = (structuralSharing: boolean) => {\n return this.clone({ structuralSharing });\n };\n\n /**\n * Make `send()` and `exec()` reject with the `error` of a failed response instead of resolving with it - for the\n * query functions of React Query, the fetchers of SWR and other code which tells failures by a rejected promise.\n */\n public setThrowOnError = (throwOnError: boolean) => {\n return this.clone({ throwOnError });\n };\n\n /** Mark the request as used (prevents automatic refetching in hooks). */\n public setUsed = (used: boolean) => {\n return this.clone({ used });\n };\n\n /** Set whether the request should be stored in the offline queue when there is no network connection. */\n public setOffline = (offline: boolean) => {\n return this.clone({ offline });\n };\n\n /** Attach a mock handler to this request. When mocking is enabled, the handler is called instead of the real adapter. */\n public setMock = (\n fn: (options: {\n request: Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;\n requestId: string;\n }) => SyncOrAsync<\n MockResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>\n >,\n config: MockerConfigType = {},\n ) => {\n this.unstable_mock = { fn, config } as typeof this.unstable_mock;\n this.isMockerEnabled = true;\n return this;\n };\n\n /** Remove any attached mock handler and disable mocking for this request. */\n public clearMock = () => {\n this.unstable_mock = undefined;\n this.isMockerEnabled = false;\n return this;\n };\n\n /** Enable or disable the mocker for this request without removing the mock handler. */\n public setMockingEnabled = (isMockerEnabled: boolean) => {\n this.isMockerEnabled = isMockerEnabled;\n return this;\n };\n\n /**\n * Map data before it gets send to the server\n * @param payloadMapper\n * @returns\n */\n public setPayloadMapper = <MappedPayload extends any | Promise<any>>(\n payloadMapper: (data: Payload) => MappedPayload,\n ) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n\n cloned.unstable_payloadMapper = payloadMapper as typeof this.unstable_payloadMapper;\n\n return cloned;\n };\n\n /**\n * Map request before it gets send to the server\n * @param requestMapper mapper of the request\n * @returns new request\n */\n public setRequestMapper = <NewRequest extends RequestInstance>(requestMapper: RequestMapper<this, NewRequest>) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n\n cloned.unstable_requestMapper = requestMapper;\n\n return cloned;\n };\n\n /**\n * Map the response to the new interface\n * @param responseMapper our mapping callback\n * @returns new response\n */\n public setResponseMapper = <MappedResponse extends ResponseSuccessType<any, any> | ResponseErrorType<any, any>>(\n responseMapper?: ResponseMapper<this, MappedResponse>,\n ) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n\n cloned.unstable_responseMapper = responseMapper as typeof cloned.unstable_responseMapper;\n\n return cloned as unknown as Request<\n MappedResponse extends ResponseType<infer R, any, any> ? R : Response,\n Payload,\n QueryParams,\n MappedResponse extends ResponseType<any, infer E, any> ? E : LocalError,\n Endpoint,\n Client,\n HasPayload,\n HasParams,\n HasQuery,\n MutationContext\n >;\n };\n\n private paramsMapper = (params: ParamsType | null | undefined): Endpoint => {\n const { endpoint } = this.requestOptions;\n\n const stringEndpoint = String(endpoint);\n const names = params ? Object.keys(params) : [];\n if (!params || names.length === 0) {\n return stringEndpoint as Endpoint;\n }\n\n // Every `:` segment is replaced once, with the longest matching name. This way `:id` does not eat the beginning\n // of `:idx`, and a value is never parsed again - neither as another param nor as a replacement pattern like `$&`.\n const [start, ...segments] = stringEndpoint.split(\":\");\n const mapped = segments.map((segment) => {\n const name = names.reduce(\n (longest, current) => (segment.startsWith(current) && current.length > longest.length ? current : longest),\n \"\",\n );\n return name ? `${params[name]}${segment.slice(name.length)}` : `:${segment}`;\n });\n\n return [start, ...mapped].join(\"\") as Endpoint;\n };\n\n /** Serialize the request configuration into a plain JSON object for persistence or transfer. */\n public toJSON(): RequestJSON<this> {\n return {\n requestOptions: this.requestOptions as unknown as RequestOptionsType<\n ExtractEndpointType<this>,\n ExtractAdapterOptionsType<ExtractAdapterType<this>>,\n ExtractAdapterMethodType<ExtractAdapterType<this>>\n >,\n endpoint: this.endpoint as ExtractEndpointType<this>,\n headers: this.headers,\n auth: this.auth,\n // TODO: fix this type\n method: this.method as any,\n params: this.params as ExtractParamsType<this>,\n payload: this.payload as ExtractPayloadType<this>,\n queryParams: this.queryParams as ExtractQueryParamsType<this>,\n options: this.options,\n cancelable: this.cancelable,\n retry: this.retry,\n retryTime: this.retryTime,\n cacheTime: this.cacheTime,\n cache: this.cache,\n staleTime: this.staleTime,\n queued: this.queued,\n offline: this.offline,\n abortKey: this.abortKey,\n cacheKey: this.cacheKey,\n queryKey: this.queryKey,\n used: this.used,\n disableResponseInterceptors: this.requestOptions.disableResponseInterceptors,\n disableRequestInterceptors: this.requestOptions.disableRequestInterceptors,\n updatedAbortKey: this.updatedAbortKey,\n updatedCacheKey: this.updatedCacheKey,\n updatedQueryKey: this.updatedQueryKey,\n deduplicate: this.deduplicate,\n deduplicateTime: this.deduplicateTime,\n structuralSharing: this.structuralSharing,\n throwOnError: this.throwOnError,\n scope: this.scope,\n isMockerEnabled: this.isMockerEnabled,\n hasMock: !!this.unstable_mock,\n };\n }\n\n /** Create a new request instance with optional configuration overrides. Used internally by all setter methods. */\n public clone<\n NewData extends true | false = HasPayload,\n NewParams extends true | false = HasParams,\n NewQueryParams extends true | false = HasQuery,\n >(\n configuration?: RequestConfigurationType<\n Payload,\n (typeof this)[\"params\"],\n QueryParams,\n Endpoint,\n ClientAdapterOptions<Client>,\n ClientAdapterMethod<Client>\n >,\n ) {\n const json = this.toJSON();\n const initialRequestConfiguration: RequestConfigurationType<\n Payload,\n Endpoint extends string ? ExtractUrlParams<Endpoint> : never,\n QueryParams,\n Endpoint,\n ClientAdapterOptions<Client>,\n ClientAdapterMethod<Client>\n > = {\n ...json,\n ...configuration,\n options: configuration?.options || this.options,\n // A key given by hand is kept by all the next clones, an auto-generated one is generated again\n abortKey: configuration?.abortKey || (this.updatedAbortKey ? this.abortKey : undefined),\n cacheKey: configuration?.cacheKey || (this.updatedCacheKey ? this.cacheKey : undefined),\n queryKey: configuration?.queryKey || (this.updatedQueryKey ? this.queryKey : undefined),\n updatedAbortKey: !!configuration?.abortKey || this.updatedAbortKey,\n updatedCacheKey: !!configuration?.cacheKey || this.updatedCacheKey,\n updatedQueryKey: !!configuration?.queryKey || this.updatedQueryKey,\n endpoint: this.paramsMapper(configuration?.params || this.params),\n queryParams: configuration?.queryParams || this.queryParams,\n // Falsy payloads like `0`, `false` or an empty string are valid values, `null` removes the payload\n payload: configuration?.payload === null ? undefined : (configuration?.payload ?? this.payload),\n params: (configuration?.params || this.params) as\n | EmptyTypes\n | (Endpoint extends string ? ExtractUrlParams<Endpoint> : never),\n };\n\n const cloned = new Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint,\n Client,\n NewData,\n NewParams,\n NewQueryParams,\n MutationContext\n >(this.client, this.requestOptions, initialRequestConfiguration);\n\n // Inherit methods\n cloned.unstable_payloadMapper = this.unstable_payloadMapper;\n cloned.unstable_responseMapper = this.unstable_responseMapper as typeof cloned.unstable_responseMapper;\n cloned.unstable_requestMapper = this.unstable_requestMapper;\n cloned.retryOnError = this.retryOnError;\n\n cloned.unstable_mock = this.unstable_mock;\n cloned.isMockerEnabled = this.isMockerEnabled;\n cloned.optimistic = this.optimistic;\n cloned.$hooks = createRequestHooks(this.$hooks.__snapshot());\n\n return cloned;\n }\n\n /** Abort all in-flight requests sharing this request's abort key. */\n public abort = () => {\n const { requestManager } = this.client;\n requestManager.abortByKey(scopeKey(this.abortKey, this.scope));\n\n return this.clone();\n };\n\n /** Extract the current cache data for this request into a portable hydration payload (useful for SSR). */\n public dehydrate = (config?: {\n /** in case of using adapter without cache we can provide response to dehydrate */\n response?: ResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;\n /** override cache data */\n override?: boolean;\n }):\n | HydrateDataType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>\n | undefined => {\n const { response, override = true } = config || {};\n\n if (response) {\n return {\n override,\n cacheTime: this.cacheTime,\n staleTime: this.staleTime,\n cacheKey: this.cacheKey,\n scope: this.scope,\n timestamp: Date.now(),\n hydrated: true,\n cache: true,\n response,\n };\n }\n\n const cacheData = this.client.cache.get<Response, LocalError | ExtractClientGlobalError<Client>>(\n scopeKey(this.cacheKey, this.scope),\n );\n\n if (!cacheData) {\n return undefined;\n }\n\n return {\n override,\n cacheTime: this.cacheTime,\n staleTime: this.staleTime,\n cacheKey: this.cacheKey,\n scope: this.scope,\n timestamp: Date.now(),\n hydrated: true,\n cache: true,\n response: {\n data: cacheData.data,\n error: cacheData.error,\n status: cacheData.status,\n success: cacheData.success,\n extra: cacheData.extra,\n requestTimestamp: cacheData.requestTimestamp,\n responseTimestamp: cacheData.responseTimestamp,\n },\n };\n };\n\n /**\n * Read the response from cache data\n *\n * If it returns error and data at the same time, it means that latest request was failed\n * and we show previous data from cache together with error received from actual request\n */\n public read():\n | ResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>\n | undefined {\n const cacheData = this.client.cache.get<Response, LocalError | ExtractClientGlobalError<Client>>(\n scopeKey(this.cacheKey, this.scope),\n );\n\n if (cacheData) {\n return {\n data: cacheData.data,\n error: cacheData.error,\n status: cacheData.status,\n success: cacheData.success,\n extra: cacheData.extra,\n requestTimestamp: cacheData.requestTimestamp,\n responseTimestamp: cacheData.responseTimestamp,\n };\n }\n return undefined;\n }\n\n /**\n * Send the request straight to the adapter, WITHOUT the dispatcher and the cache: it is not queued, deduplicated,\n * retried or cached. Lifecycle callbacks, `$hooks`, interceptors and the response mapper work like in `send()`.\n * Use it when something else owns caching and retries, like React Query or SWR - with `signal` and `throwOnError`.\n * @param options\n * @disableReturns\n * @returns\n * ```tsx\n * Promise<{ data: Data | null, error: Error | null, status: HttpStatus, ... }>\n * ```\n */\n public exec: RequestSendType<this> = async (options?: RequestSendOptionsType<this>) => {\n const { signal, ...configuration } = options || {};\n const { adapter, requestManager } = this.client;\n const request = this.clone(configuration) as unknown as this;\n const { $hooks } = request;\n\n const requestId = this.client.unstable_requestIdMapper(this);\n // The adapter finds the controller by the key of the request it sends - the one of this call\n const abortKey = scopeKey(request.abortKey, request.scope);\n const triggerTimestamp = Date.now();\n\n // Listen for aborting\n requestManager.addAbortController(abortKey, requestId);\n const unmountCallbacks = subscribeRequestCallbacks({ request, requestId, options });\n\n const beforeSentData = { requestId, request };\n runUserCode(() => options?.onBeforeSent?.(beforeSentData));\n runUserCode(() => $hooks.__emit(\"onBeforeSent\", beforeSentData));\n\n // The signal of the caller only triggers the controller of this call\n const unlinkSignal = linkAbortSignal(signal, () => requestManager.abortByRequestId(abortKey, requestId));\n\n const response = await adapter.fetch(request, requestId);\n\n // Read before the controller is dropped\n const isCanceled = requestManager.isCanceled(abortKey, requestId);\n unlinkSignal();\n unmountCallbacks();\n // Stop listening for aborting\n requestManager.removeAbortController(abortKey, requestId);\n\n // A throwing response mapper gives the error response, the same way as in `send()`\n const mappedResponse = await mapResponseForSend(request, response);\n\n const responseData = {\n requestId,\n request,\n response,\n details: {\n retries: 0,\n isCanceled,\n isOffline: false,\n willRetry: false,\n addedTimestamp: triggerTimestamp,\n triggerTimestamp,\n requestTimestamp: response.requestTimestamp,\n responseTimestamp: response.responseTimestamp,\n },\n };\n runUserCode(() => options?.onResponse?.(responseData));\n runUserCode(() => $hooks.__emit(\"onResponse\", responseData));\n\n if (request.throwOnError && !mappedResponse.success) {\n throw mappedResponse.error;\n }\n return mappedResponse;\n };\n\n /**\n * Method used to perform requests with usage of cache and queues\n * @param options\n * @param requestCallback\n * @disableReturns\n * @returns\n * ```tsx\n * Promise<{ data: Data | null, error: Error | null, status: HttpStatus, ... }>\n * ```\n */\n public send: RequestSendType<this> = async (options?: RequestSendOptionsType<this>) => {\n const {\n dispatcherType: _dispatcherType,\n cachePolicy = \"network-only\",\n optimistic: _optimistic,\n signal: _signal,\n ...configuration\n } = options || {};\n\n const request = this.clone(configuration) as unknown as this;\n\n const sendRequestOptions = options === undefined ? undefined : { ...options, cachePolicy: undefined };\n\n const getResponse = async (): Promise<RequestResponseType<this>> => {\n if (cachePolicy === \"network-only\") {\n return sendRequest(request, sendRequestOptions);\n }\n\n const cached = request.read();\n\n if (cachePolicy === \"cache-first\") {\n if (cached) {\n return mapResponseForSend(request, cached);\n }\n return sendRequest(request, sendRequestOptions);\n }\n\n // revalidate\n if (cached) {\n const resolved = await mapResponseForSend(request, cached);\n // Background revalidation; promise from send() already resolved with cache snapshot\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n sendRequest(request, sendRequestOptions);\n return resolved;\n }\n return sendRequest(request, sendRequestOptions);\n };\n\n const response = await getResponse();\n\n if (request.throwOnError && !response.success) {\n throw response.error;\n }\n return response;\n };\n\n /** Reconstruct a Request instance from a previously serialized JSON representation. */\n static fromJSON = <\n NewResponse,\n NewPayload,\n NewQueryParams,\n NewLocalError,\n NewEndpoint extends string,\n NewClient extends ClientInstance,\n NewHasPayload extends true | false = false,\n NewHasParams extends true | false = false,\n NewHasQuery extends true | false = false,\n >(\n client: NewClient,\n json: RequestJSON<\n Request<\n NewResponse,\n NewPayload,\n NewQueryParams,\n NewLocalError,\n NewEndpoint,\n NewClient,\n NewHasPayload,\n NewHasParams,\n NewHasQuery\n >\n >,\n ) => {\n return new Request<\n NewResponse,\n NewPayload,\n NewQueryParams,\n NewLocalError,\n NewEndpoint,\n NewClient,\n NewHasPayload,\n NewHasParams,\n NewHasQuery\n >(client, json.requestOptions, json);\n };\n}\n","import type { AdapterInstance, ResponseType } from \"adapter\";\nimport type {\n CacheOptionsType,\n CacheAsyncStorageType,\n CacheStorageType,\n CacheValueType,\n CacheSetState,\n RequestCacheType,\n} from \"cache\";\nimport { getCacheData, getCacheEvents, replaceEqualDeep } from \"cache\";\nimport type { ClientInstance } from \"client\";\nimport type { ResponseDetailsType, LoggerMethods } from \"managers\";\nimport type { RequestInstance } from \"request\";\nimport { Request, scopeKey } from \"request\";\nimport type { ExtractAdapterType, ExtractErrorType, ExtractResponseType } from \"types\";\nimport { EventEmitter } from \"utils\";\n\n/** Timers can't wait longer than 2^31-1 ms (~24.8 days) - a longer delay overflows and fires immediately */\nconst MAX_TIMER_DELAY = 2_147_483_647;\n\n/**\n * Cache class handles the data exchange with the dispatchers.\n *\n * @note\n * Keys used to save the values are created dynamically on the Request class\n *\n */\nexport class Cache<Adapter extends AdapterInstance> {\n public emitter = new EventEmitter();\n public events: ReturnType<typeof getCacheEvents>;\n\n public storage: CacheStorageType;\n public lazyStorage?: CacheAsyncStorageType = undefined;\n public version: string;\n public garbageCollectors = new Map<string, ReturnType<typeof setTimeout>>();\n private logger: LoggerMethods;\n private client: ClientInstance<{ adapter: Adapter }>;\n\n constructor(public options?: CacheOptionsType) {\n const { storage = new Map<string, CacheValueType>(), lazyStorage, version = \"0.0.1\" } = options ?? {};\n\n this.emitter?.setMaxListeners(1000);\n this.events = getCacheEvents(this.emitter);\n\n this.storage = storage;\n this.version = version;\n this.lazyStorage = lazyStorage;\n }\n\n /** Initialize the cache with a client reference, set up logging, and start garbage collection. */\n initialize = (client: ClientInstance<{ adapter: Adapter }>) => {\n this.client = client;\n this.logger = client.loggerManager.initialize(client, \"Cache\");\n\n // Going back from offline should re-trigger garbage collection\n client.appManager.events.onOnline(() => {\n [...this.storage.keys()].forEach(this.scheduleGarbageCollector);\n });\n\n [...this.storage.keys()].forEach(this.scheduleGarbageCollector);\n\n return this;\n };\n\n /**\n * Set the cache data to the storage\n * @param request\n * @param response\n * @returns\n */\n set = <Request extends RequestCacheType<RequestInstance>>(\n request: Request,\n response: CacheSetState<\n ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>> &\n ResponseDetailsType\n > & { hydrated?: boolean },\n ): void => {\n this.logger.debug({ title: \"Processing cache response\", type: \"system\", extra: { request, response } });\n const { cacheKey, cache, staleTime, cacheTime, scope } = request;\n const storageKey = scopeKey(cacheKey, scope);\n const previousCacheData = this.storage.get<\n ExtractResponseType<Request>,\n ExtractErrorType<Request>,\n ExtractAdapterType<Request>\n >(storageKey);\n\n // Once refresh error occurs we don't want to override already valid data in our cache with the thrown error\n // We need to check it against cache and return last valid data we have\n const processedResponse = typeof response === \"function\" ? response(previousCacheData || null) : response;\n const data = getCacheData(previousCacheData, processedResponse);\n\n // Keep references of the unchanged data parts, so deeply equal responses don't produce new objects\n if (request.structuralSharing !== false && previousCacheData) {\n data.data = replaceEqualDeep(previousCacheData.data, data.data);\n }\n\n const newCacheData: CacheValueType<any, any, ExtractAdapterType<Request>> = {\n ...data,\n scope,\n staleTime,\n version: this.version,\n cacheKey,\n cacheTime,\n cached: !!request.cache,\n };\n\n const isServerMode = this.client.mode === \"server\";\n const isCachingAllowed = cache && (!isServerMode || !!(request as any).scope);\n\n // Only success data is valid for the cache store\n if (processedResponse.success && isCachingAllowed) {\n this.logger.debug({ title: \"Saving response to cache storage\", type: \"system\", extra: { request, data } });\n this.storage.set<Response, Error, ExtractAdapterType<Request>>(storageKey, newCacheData);\n this.runLazyStorage(\"set\", storageKey, (lazyStorage) =>\n lazyStorage.set<Response, Error, ExtractAdapterType<Request>>(storageKey, newCacheData),\n );\n this.client.triggerPlugins(\"onCacheItemChange\", {\n cache: this,\n cacheKey,\n prevData: (previousCacheData || null) as CacheValueType<any, any, AdapterInstance>,\n newData: newCacheData as CacheValueType<any, any, AdapterInstance>,\n });\n\n this.scheduleGarbageCollector(storageKey);\n } else {\n // If request should not use cache - just emit response data\n this.logger.debug({ title: \"Prevented saving response to cache\", type: \"system\", extra: { request, data } });\n }\n\n this.logger.debug({ title: \"Emitting cache response\", type: \"system\", extra: { request, data } });\n this.events.emitCacheData<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>(\n newCacheData,\n );\n };\n\n /**\n * Update the cache data with partial response data. The `responseTimestamp` is set to the time of the update, so\n * the `cacheTime` and `staleTime` count from the update. Use `set` to store the data with another timestamp.\n * @param request\n * @param partialResponse\n * @returns\n */\n update = <Request extends RequestCacheType<RequestInstance>>(\n request: Request,\n partialResponse: CacheSetState<\n Partial<\n ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>> &\n ResponseDetailsType\n >\n >,\n ): void => {\n this.logger.debug({ title: \"Processing cache update\", type: \"system\", extra: { request, partialResponse } });\n const { cacheKey, scope } = request;\n const storageKey = scopeKey(cacheKey, scope);\n const cachedData = this.storage.get<\n ExtractResponseType<Request>,\n ExtractErrorType<Request>,\n ExtractAdapterType<Request>\n >(storageKey);\n\n const processedResponse =\n typeof partialResponse === \"function\" ? partialResponse(cachedData || null) : partialResponse;\n if (cachedData) {\n // The updated data is as old as the update - the cache and stale times count from now. Callbacks usually\n // spread the previous value, so its timestamp is replaced as well.\n this.set(request, { ...cachedData, ...processedResponse, responseTimestamp: Date.now() });\n }\n };\n\n /**\n * Get particular record from storage by cacheKey. It will trigger lazyStorage to emit lazy load event for reading it's data.\n * @param cacheKey\n * @returns\n */\n get = <Response, Error>(cacheKey: string): CacheValueType<Response, Error, Adapter> | undefined => {\n this.getLazyResource<Response, Error>(cacheKey);\n const cachedData = this.storage.get<Response, Error, Adapter>(cacheKey);\n\n // Data saved by another cache version is never returned - the lazy resource check above removes it\n if (cachedData && cachedData.version !== this.version) {\n return undefined;\n }\n return cachedData;\n };\n\n /**\n * Get sync storage keys, lazyStorage keys will not be included\n * @returns\n */\n keys = (): string[] => {\n const values = this.storage.keys();\n\n return [...values];\n };\n\n /**\n * Delete record from storages and trigger invalidation event\n * @param cacheKey\n */\n delete = (cacheKey: string): void => {\n this.logger.debug({ title: \"Deleting cache element\", type: \"system\", extra: { cacheKey } });\n // Removed element has nothing left to collect - pending collector would only emit the deletion once again\n clearTimeout(this.garbageCollectors.get(cacheKey));\n this.garbageCollectors.delete(cacheKey);\n\n // Listeners are subscribed with the cache key of the request, scoped elements are stored under another key\n const listenersKey = this.storage.get(cacheKey)?.cacheKey ?? cacheKey;\n this.storage.delete(cacheKey);\n this.runLazyStorage(\"delete\", cacheKey, (lazyStorage) => lazyStorage.delete(cacheKey));\n\n this.client.triggerPlugins(\"onCacheItemDelete\", {\n cache: this,\n cacheKey,\n });\n\n this.events.emitDelete(cacheKey, false, listenersKey);\n };\n\n /**\n * Invalidate cache by cacheKey or partial matching with RegExp\n * It emits invalidation event for each matching cacheKey and sets staleTime to 0 to indicate out of time cache\n * Called without arguments it invalidates every cached element.\n * @param cacheKeys - cacheKey or Request instance or RegExp for partial matching (defaults to all elements)\n */\n invalidate = (cacheKeys: string | RegExp | RequestInstance | (string | RegExp | RequestInstance)[] = /.*/) => {\n this.logger.debug({ title: \"Revalidating cache element\", type: \"system\", extra: { cacheKeys } });\n\n const onInvalidate = (key: string | RegExp | RequestInstance) => {\n const keys = [...this.storage.keys()];\n const handleInvalidation = (invalidateStorageKey: string, notifyCacheKey: string = invalidateStorageKey) => {\n const value = this.storage.get(invalidateStorageKey);\n if (value) {\n this.storage.set(invalidateStorageKey, { ...value, staleTime: 0 });\n }\n\n this.client.triggerPlugins(\"onCacheItemInvalidate\", {\n cache: this,\n cacheKey: notifyCacheKey,\n });\n\n // Listeners are subscribed with the cache key of the request, scoped elements are stored under another key.\n // The key of the element goes as the event data, so they can tell the scopes apart.\n const listenersKey =\n notifyCacheKey === invalidateStorageKey ? (value?.cacheKey ?? notifyCacheKey) : notifyCacheKey;\n this.events.emitInvalidation(invalidateStorageKey, false, listenersKey);\n };\n\n if (key instanceof Request) {\n handleInvalidation(scopeKey(key.cacheKey, key.scope), key.cacheKey);\n } else if (typeof key === \"string\") {\n handleInvalidation(key);\n } else if (keys.length > 0) {\n // Global and sticky expressions remember the position of the last match, which would skip some of the keys\n const matcher = new RegExp(key.source, key.flags.replaceAll(/[gy]/g, \"\"));\n keys.forEach((entityKey) => {\n if (matcher.test(entityKey)) {\n handleInvalidation(entityKey);\n }\n });\n }\n };\n\n if (Array.isArray(cacheKeys)) {\n cacheKeys.forEach(onInvalidate.bind(this));\n } else {\n onInvalidate.bind(this)(cacheKeys);\n }\n };\n\n /**\n * Used to receive data from lazy storage\n * @param cacheKey\n */\n getLazyResource = async <Response, Error>(\n cacheKey: string,\n ): Promise<CacheValueType<Response, Error, Adapter> | undefined> => {\n const data = await this.runLazyStorage(\"get\", cacheKey, (lazyStorage) =>\n lazyStorage.get<Response, Error, Adapter>(cacheKey),\n );\n const syncData = this.storage.get<Response, Error, Adapter>(cacheKey);\n\n // No data in lazy storage\n if (data) {\n const now = Date.now();\n const isNewestData = syncData ? syncData.responseTimestamp < data.responseTimestamp : true;\n // Storages based on JSON turn Infinity into null - such data never gets stale\n const isStaleData = data.staleTime === null ? false : data.staleTime <= now - data.responseTimestamp;\n const isValidLazyData = data.version === this.version;\n // Collectors do not survive the application restart, so outdated data has to be removed once we meet it\n const isExpiredData = this.client.appManager.isOnline && this.getTimeLeft(data, now) < 0;\n\n if (!isValidLazyData || isExpiredData) {\n this.runLazyStorage(\"delete\", cacheKey, (lazyStorage) => lazyStorage.delete(cacheKey));\n }\n if (isNewestData && !isStaleData && isValidLazyData && !isExpiredData) {\n this.storage.set<Response, Error, Adapter>(cacheKey, data);\n // Data loaded to the sync storage is collected the same way as the data set directly\n this.scheduleGarbageCollector(cacheKey);\n // Data events are emitted with the request cacheKey, which differs from the storage key for scoped requests\n this.events.emitCacheData<Response, Error, Adapter>({\n ...data,\n cacheKey: typeof data.cacheKey === \"string\" ? data.cacheKey : cacheKey,\n cached: true,\n });\n return data;\n }\n }\n\n const isValidData = syncData?.version === this.version;\n if (syncData && !isValidData) {\n this.delete(cacheKey);\n return undefined;\n }\n return syncData;\n };\n\n /**\n * Used to receive keys from lazy storage only\n */\n getLazyKeys = async () => {\n const keys = (await this.lazyStorage?.keys()) || [];\n\n return [...new Set(keys)];\n };\n\n /**\n * Used to receive deduplicated keys from both sync storage and lazy storage\n */\n getAllKeys = async () => {\n const keys = await this.lazyStorage?.keys();\n const asyncKeys = [...(keys || [])];\n const syncKeys = [...this.storage.keys()];\n\n return [...new Set([...asyncKeys, ...syncKeys])];\n };\n\n /**\n * Schedule garbage collection for given key\n * @param cacheKey\n * @returns\n */\n scheduleGarbageCollector = (cacheKey: string) => {\n // We need to make sure that all of the values will be removed, also that we have the proper data\n const cacheData = this.storage.get(cacheKey);\n\n // Clear running garbage collectors for given key\n clearTimeout(this.garbageCollectors.get(cacheKey));\n this.garbageCollectors.delete(cacheKey);\n\n // Garbage collect\n if (cacheData) {\n const timeLeft = this.getTimeLeft(cacheData, Date.now());\n // null\n if (cacheData.cacheTime === null) {\n this.logger.debug({ title: \"Cache time is null\", type: \"system\", extra: { cacheKey } });\n }\n // Infinity\n else if (timeLeft === Infinity) {\n this.logger.debug({ title: \"Cache time is Infinite\", type: \"system\", extra: { cacheKey } });\n }\n // Run garbage collector\n else if (timeLeft >= 0) {\n // Longer delays are split into parts, as timers fire immediately when the delay is too big for them\n const delay = Math.min(timeLeft, MAX_TIMER_DELAY);\n this.garbageCollectors.set(\n cacheKey,\n setTimeout(() => {\n this.garbageCollectors.delete(cacheKey);\n if (delay < timeLeft) {\n this.scheduleGarbageCollector(cacheKey);\n } else if (this.client.appManager.isOnline) {\n this.logger.info({ title: \"Garbage collecting cache data\", type: \"system\", extra: { cacheKey } });\n this.delete(cacheKey);\n }\n }, delay),\n );\n }\n // Delete if value is stale and we are online\n else if (this.client.appManager.isOnline) {\n this.logger.info({ title: \"Garbage collecting cache data\", type: \"system\", extra: { cacheKey } });\n this.delete(cacheKey);\n }\n }\n };\n\n /**\n * Time left to the garbage collection of the cache element. Returns Infinity for elements stored forever\n * and a negative value for outdated elements or elements without valid times.\n */\n private getTimeLeft = (cacheData: Pick<CacheValueType, \"cacheTime\" | \"responseTimestamp\">, now: number): number => {\n const { cacheTime, responseTimestamp } = cacheData;\n // Storages based on JSON turn Infinity into null\n if (cacheTime === null || (typeof cacheTime === \"number\" && !Number.isFinite(cacheTime))) {\n return Infinity;\n }\n const timeLeft = cacheTime + responseTimestamp - now;\n // Missing times can't be scheduled, such element is treated as outdated\n return Number.isNaN(timeLeft) ? -1 : timeLeft;\n };\n\n /**\n * Lazy storage is an external resource (IndexedDB, AsyncStorage etc.) - its failures are logged, they must not\n * break the cache flow nor end up as unhandled promise rejections.\n */\n private runLazyStorage = async <Result>(\n action: \"get\" | \"set\" | \"delete\" | \"clear\",\n cacheKey: string,\n callback: (lazyStorage: CacheAsyncStorageType) => Promise<Result>,\n ): Promise<Result | undefined> => {\n if (!this.lazyStorage) {\n return undefined;\n }\n try {\n return await callback(this.lazyStorage);\n } catch (error) {\n this.logger?.error({\n title: `Lazy storage \"${action}\" failed`,\n type: \"system\",\n extra: { cacheKey, error },\n });\n return undefined;\n }\n };\n\n /**\n * Clear cache storages - the memory and the lazy one. Data left in the lazy storage would be loaded back\n * by the next read, for example for the next user after a logout.\n */\n clear = async (): Promise<void> => {\n this.garbageCollectors.forEach((timeout) => clearTimeout(timeout));\n this.garbageCollectors.clear();\n this.storage.clear();\n\n await this.runLazyStorage(\"clear\", \"*\", async (lazyStorage) => {\n const keys = [...(await lazyStorage.keys())];\n // One element that can't be removed must not keep the others in the storage\n const results = await Promise.allSettled(keys.map((key) => lazyStorage.delete(key)));\n // The type guard keeps older compilers (docs generation) narrowing the result to the rejected one\n const failed = results.find((result): result is PromiseRejectedResult => result.status === \"rejected\");\n if (failed) {\n throw failed.reason;\n }\n });\n };\n}\n","import type { ResponseDetailsType } from \"managers\";\nimport type { RequestInstance } from \"request\";\nimport type { ExtractAdapterResolvedType } from \"types\";\n\nexport const getCacheData = <T extends RequestInstance>(\n previousResponse: ExtractAdapterResolvedType<T> | undefined,\n response: ExtractAdapterResolvedType<T> & ResponseDetailsType,\n): ExtractAdapterResolvedType<T> & ResponseDetailsType => {\n const { data, success } = response;\n\n const previousData = !success && previousResponse ? previousResponse.data : null;\n // Only missing data falls back to the previous one - falsy responses like `0`, `false` or `\"\"` are valid data\n const computedData = data ?? previousData;\n\n return { ...response, data: computedData };\n};\n\nexport const getInvalidateKey = (): string => {\n return `invalidate`;\n};\nexport const getInvalidateByKey = (key: string): string => {\n return `${key}_invalidate`;\n};\nexport const getDeleteKey = (): string => {\n return `delete`;\n};\nexport const getDeleteByKey = (key: string): string => {\n return `${key}_delete`;\n};\nexport const getCacheByKey = (key: string): string => {\n return `${key}_cache`;\n};\nexport const getCacheKey = (): string => {\n return `cache`;\n};\n\n/**\n * Check if value is a plain object (object literal or `Object.create(null)`).\n * Class instances, Dates, Maps, Blobs etc. are not plain objects.\n */\nexport const isPlainObject = (value: unknown): value is Record<string, unknown> => {\n if (Object.prototype.toString.call(value) !== \"[object Object]\") {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === null || prototype === Object.prototype;\n};\n\nconst isPlainArray = (value: unknown): value is unknown[] => {\n return Array.isArray(value) && Object.keys(value).length === value.length;\n};\n\n/**\n * Structures nested deeper than this are not compared - it keeps extremely deep data from overflowing the call stack.\n */\nconst STRUCTURAL_SHARING_MAX_DEPTH = 500;\n\n/**\n * @param ancestors containers of `next` that are being compared right now - their number is the current depth\n * and meeting one of them again means a cycle\n */\nconst shareEqualParts = <T>(prev: unknown, next: T, ancestors: Set<unknown>): T => {\n if (Object.is(prev, next)) {\n return prev as T;\n }\n\n const isArray = isPlainArray(prev) && isPlainArray(next);\n if (!isArray && !(isPlainObject(prev) && isPlainObject(next))) {\n return next;\n }\n\n // Circular and extremely deep structures are not traversed further\n if (ancestors.size > STRUCTURAL_SHARING_MAX_DEPTH || ancestors.has(next)) {\n return next;\n }\n ancestors.add(next);\n\n const prevItems = prev as Record<string, unknown>;\n const nextItems = next as Record<string, unknown>;\n const prevKeys = Object.keys(prevItems);\n const nextKeys = Object.keys(nextItems);\n const copy: Record<string, unknown> = isArray ? ([] as unknown as Record<string, unknown>) : {};\n\n let equalItems = 0;\n nextKeys.forEach((key) => {\n const prevValue = prevItems[key];\n const nextValue = nextItems[key];\n const value = shareEqualParts(prevValue, nextValue, ancestors);\n copy[key] = value;\n // undefined values are equal only when the key existed before\n // eslint-disable-next-line prefer-object-has-own -- Object.hasOwn is not available in older runtimes\n if (Object.is(value, prevValue) && (value !== undefined || Object.prototype.hasOwnProperty.call(prevItems, key))) {\n equalItems += 1;\n }\n });\n\n ancestors.delete(next);\n\n return (prevKeys.length === nextKeys.length && equalItems === prevKeys.length ? prev : copy) as T;\n};\n\n/**\n * Structural sharing - returns `next` with every part that is deeply equal to `prev` replaced by the `prev` reference.\n * When both values are deeply equal the `prev` reference is returned, so consumers can rely on `===` checks.\n * Only plain objects and arrays are traversed, other values are compared with `Object.is`.\n * Circular references and extremely deep structures are not traversed - such parts are taken from `next` as they are.\n * @param prev previous value\n * @param next incoming value\n * @returns `next` sharing unchanged references with `prev`\n */\nexport const replaceEqualDeep = <T>(prev: unknown, next: T): T => {\n return shareEqualParts(prev, next, new Set());\n};\n","import type { AdapterInstance } from \"adapter\";\nimport type { CacheValueType } from \"cache\";\nimport { getInvalidateByKey, getInvalidateKey, getCacheByKey, getCacheKey, getDeleteKey, getDeleteByKey } from \"cache\";\nimport type EventEmitter from \"events\";\n\n/** Create the cache event emitters and listeners for data changes, invalidation, and deletion. */\nexport const getCacheEvents = (emitter: EventEmitter) => ({\n /**\n * Set cache data\n * @param data\n */\n emitCacheData: <Response, Error, Adapter extends AdapterInstance>(\n data: CacheValueType<Response, Error, Adapter> & { cached: boolean },\n isTriggeredExternally = false,\n ): void => {\n emitter.emit(getCacheKey(), data, isTriggeredExternally);\n emitter.emit(getCacheByKey(data.cacheKey), data, isTriggeredExternally);\n },\n /**\n * Invalidate cache values event\n * @param cacheKey key of the invalidated element - the event data\n * @param isTriggeredExternally event comes from outside of the cache (for example from devtools)\n * @param listenersKey key the by-key listeners are subscribed with. Scoped elements are stored under\n * `scopeKey(cacheKey, scope)`, while their listeners use the `cacheKey` of the request\n */\n emitInvalidation: (cacheKey: string, isTriggeredExternally = false, listenersKey = cacheKey): void => {\n emitter.emit(getInvalidateKey(), cacheKey, isTriggeredExternally);\n // Key goes as the event data, so the external trigger flag stays at its place for the emit observers\n emitter.emit(getInvalidateByKey(listenersKey), cacheKey, isTriggeredExternally);\n },\n /**\n * Delete of cache values\n * @param cacheKey key of the deleted element - the event data\n * @param isTriggeredExternally event comes from outside of the cache (for example from devtools)\n * @param listenersKey key the by-key listeners are subscribed with. Scoped elements are stored under\n * `scopeKey(cacheKey, scope)`, while their listeners use the `cacheKey` of the request\n */\n emitDelete: (cacheKey: string, isTriggeredExternally = false, listenersKey = cacheKey): void => {\n emitter.emit(getDeleteKey(), cacheKey, isTriggeredExternally);\n // Key goes as the event data, so the external trigger flag stays at its place for the emit observers\n emitter.emit(getDeleteByKey(listenersKey), cacheKey, isTriggeredExternally);\n },\n /**\n * Cache data listener for all keys\n * @param callback\n * @returns\n */\n onData: <Response, Error, Adapter extends AdapterInstance>(\n callback: (data: CacheValueType<Response, Error, Adapter> & { cached: boolean }) => void,\n ): VoidFunction => {\n emitter.on(getCacheKey(), callback);\n return () => emitter.removeListener(getCacheKey(), callback);\n },\n /**\n * Cache data listener filtered by a specific cache key\n * @param cacheKey\n * @param callback\n * @returns\n */\n onDataByKey: <Response, Error, Adapter extends AdapterInstance>(\n cacheKey: string,\n callback: (data: CacheValueType<Response, Error, Adapter>) => void,\n ): VoidFunction => {\n emitter.on(getCacheByKey(cacheKey), callback);\n return () => emitter.removeListener(getCacheByKey(cacheKey), callback);\n },\n /**\n * Cache invalidation listener\n * @param callback\n * @returns\n */\n onInvalidate: (callback: (cacheKey: string) => void): VoidFunction => {\n emitter.on(getInvalidateKey(), callback);\n return () => emitter.removeListener(getInvalidateKey(), callback);\n },\n /**\n * Cache invalidation listener filtered by the cache key of the request.\n * Requests of every scope share that key - the callback receives the key of the invalidated element\n * (`scopeKey(cacheKey, scope)`), which tells the scopes apart.\n * @param cacheKey\n * @param callback\n * @returns\n */\n onInvalidateByKey: (cacheKey: string, callback: (invalidatedKey: string) => void): VoidFunction => {\n emitter.on(getInvalidateByKey(cacheKey), callback);\n return () => emitter.removeListener(getInvalidateByKey(cacheKey), callback);\n },\n /** Cache deletion listener for all keys */\n onDelete: (callback: (cacheKey: string) => void): VoidFunction => {\n emitter.on(getDeleteKey(), callback);\n return () => emitter.removeListener(getDeleteKey(), callback);\n },\n /**\n * Cache deletion listener filtered by the cache key of the request.\n * Requests of every scope share that key - the callback receives the key of the deleted element\n * (`scopeKey(cacheKey, scope)`), which tells the scopes apart.\n */\n onDeleteByKey: (cacheKey: string, callback: (deletedKey: string) => void): VoidFunction => {\n emitter.on(getDeleteByKey(cacheKey), callback);\n return () => emitter.removeListener(getDeleteByKey(cacheKey), callback);\n },\n});\n","export enum DispatcherMode {\n ONE_BY_ONE = \"one-by-one\",\n ALL_AT_ONCE = \"all-at-once\",\n PREVIOUS_CANCELED = \"previous-canceled\",\n DEDUPLICATED = \"deduplicated\",\n}\n","import type { QueueDataType, RunningRequestsChangeType } from \"dispatcher\";\nimport {\n getDispatcherChangeKey,\n getDispatcherChangeByKey,\n getDispatcherStatusKey,\n getDispatcherStatusByKey,\n getDispatcherDrainedKey,\n getDispatcherDrainedByKey,\n getDispatcherRunningKey,\n getDispatcherRunningByKey,\n} from \"dispatcher\";\nimport type EventEmitter from \"events\";\nimport type { RequestInstance } from \"request\";\n\nexport const getDispatcherEvents = (emitter: EventEmitter) => ({\n emitDrained: <Request extends RequestInstance>(\n values: QueueDataType<Request>,\n isTriggeredExternally?: boolean,\n ): void => {\n emitter.emit(getDispatcherDrainedKey(), values, isTriggeredExternally);\n emitter.emit(getDispatcherDrainedByKey(values.queryKey), values, isTriggeredExternally);\n },\n emitQueueStatusChanged: <Request extends RequestInstance>(\n values: QueueDataType<Request>,\n isTriggeredExternally?: boolean,\n ): void => {\n emitter.emit(getDispatcherStatusKey(), values, isTriggeredExternally);\n emitter.emit(getDispatcherStatusByKey(values.queryKey), values, isTriggeredExternally);\n },\n emitQueueChanged: <Request extends RequestInstance>(\n values: QueueDataType<Request>,\n isTriggeredExternally?: boolean,\n ): void => {\n emitter.emit(getDispatcherChangeKey(), values, isTriggeredExternally);\n emitter.emit(getDispatcherChangeByKey(values.queryKey), values, isTriggeredExternally);\n },\n emitRunningRequestsChanged: (values: RunningRequestsChangeType, isTriggeredExternally?: boolean): void => {\n emitter.emit(getDispatcherRunningKey(), values, isTriggeredExternally);\n emitter.emit(getDispatcherRunningByKey(values.queryKey), values, isTriggeredExternally);\n },\n /**\n * When queue becomes empty\n * @param callback\n * @returns\n */\n onDrained: <Request extends RequestInstance>(callback: (values: QueueDataType<Request>) => void): VoidFunction => {\n emitter.on(getDispatcherDrainedKey(), callback);\n return () => emitter.removeListener(getDispatcherDrainedKey(), callback);\n },\n /**\n * When queue becomes empty\n * @param queryKey\n * @param callback\n * @returns\n */\n onDrainedByKey: <Request extends RequestInstance>(\n queryKey: string,\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherDrainedByKey(queryKey), callback);\n return () => emitter.removeListener(getDispatcherDrainedByKey(queryKey), callback);\n },\n /**\n * When queue status change from enabled to paused or vice versa\n * @param callback\n * @returns\n */\n onQueueStatusChange: <Request extends RequestInstance>(\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherStatusKey(), callback);\n return () => emitter.removeListener(getDispatcherStatusKey(), callback);\n },\n /**\n * When queue status change from enabled to paused or vice versa\n * @param queryKey\n * @param callback\n * @returns\n */\n onQueueStatusChangeByKey: <Request extends RequestInstance>(\n queryKey: string,\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherStatusByKey(queryKey), callback);\n return () => emitter.removeListener(getDispatcherStatusByKey(queryKey), callback);\n },\n /**\n * When new elements are added or removed from the queue\n * @param queryKey\n * @param callback\n * @returns\n */\n onQueueChange: <Request extends RequestInstance>(\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherChangeKey(), callback);\n return () => emitter.removeListener(getDispatcherChangeKey(), callback);\n },\n /**\n * When new elements are added or removed from the queue\n * @param queryKey\n * @param callback\n * @returns\n */\n onQueueChangeByKey: <Request extends RequestInstance>(\n queryKey: string,\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherChangeByKey(queryKey), callback);\n return () => emitter.removeListener(getDispatcherChangeByKey(queryKey), callback);\n },\n /**\n * When requests start or stop running (sent, finished, canceled or cleared)\n * @param callback\n * @returns\n */\n onRunningRequestsChange: (callback: (values: RunningRequestsChangeType) => void): VoidFunction => {\n emitter.on(getDispatcherRunningKey(), callback);\n return () => emitter.removeListener(getDispatcherRunningKey(), callback);\n },\n /**\n * When requests start or stop running (sent, finished, canceled or cleared) for given queryKey\n * @param queryKey\n * @param callback\n * @returns\n */\n onRunningRequestsChangeByKey: (\n queryKey: string,\n callback: (values: RunningRequestsChangeType) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherRunningByKey(queryKey), callback);\n return () => emitter.removeListener(getDispatcherRunningByKey(queryKey), callback);\n },\n});\n","/* eslint-disable max-lines */\nimport type { AdapterInstance, RequestResponseType } from \"adapter\";\nimport { getErrorMessage } from \"adapter\";\nimport type { ClientInstance } from \"client\";\nimport type {\n QueueDataType,\n DispatcherAsyncStorageType,\n DispatcherOptionsType,\n DispatcherStorageType,\n ResolvedQueueDataType,\n ResolvedQueueItemType,\n RunningRequestValueType,\n} from \"dispatcher\";\nimport { getRequestType, canRetryRequest, getDispatcherEvents, DispatcherMode } from \"dispatcher\";\nimport type { ResponseDetailsType, LoggerMethods } from \"managers\";\nimport { isStaleOptimisticResponse } from \"optimistic\";\nimport type { RequestInstance, RequestJSON } from \"request\";\nimport { Request, scopeKey } from \"request\";\nimport { EventEmitter, throwOutsideLifecycle } from \"utils\";\n\n/**\n * Dispatcher controls and manages the requests that are going to be executed with adapter. It manages them based on the options provided with request.\n * This class can also run them with different modes like deduplication, cancelation, queueing or run-all-at-once mode. With it's help we can pause,\n * stop, start and cancel requests.\n */\nexport class Dispatcher<Adapter extends AdapterInstance> {\n public emitter = new EventEmitter();\n public events = getDispatcherEvents(this.emitter);\n public storage: DispatcherStorageType = new Map<string, QueueDataType<any>>();\n\n private requestCount = new Map<string, number>();\n private runningRequests = new Map<string, RunningRequestValueType[]>();\n /** Failed requests waiting for their next attempt, by requestId */\n private retryTimers = new Map<string, ReturnType<typeof setTimeout>>();\n /** Requests which got their response and are still in the queue while their listeners run */\n private answeredRequests = new Set<string>();\n /** Order in which the requests were sent - responses can come back in another one */\n private sentCount = 0;\n /** Cache element (by its storage key) to the order number of the request whose data it holds */\n private cachedOrder = new Map<string, number>();\n\n /** Sends the queue restored from the storage once the client is configured */\n private startTimer: ReturnType<typeof setTimeout> | undefined;\n /** Operations of the lazy storage run one after another, so it always ends with the latest state of the queues */\n private lazyOperations: Promise<void> = Promise.resolve();\n\n private logger: LoggerMethods;\n private client: ClientInstance<{ adapter: Adapter }>;\n\n constructor(public options?: DispatcherOptionsType) {\n this.emitter?.setMaxListeners(1000);\n\n if (this.options?.storage) {\n this.storage = this.options.storage;\n }\n if (this.options?.lazyStorage) {\n this.storage = this.withLazyStorage(this.storage, this.options.lazyStorage);\n }\n }\n\n // *********************************************************************\n // *********************************************************************\n // Lazy storage\n // *********************************************************************\n // *********************************************************************\n\n /**\n * Lazy storage is an external resource - its failures are logged, they must not take the requests down\n */\n private runLazyOperation = (action: string, queryKey: string | null, operation: () => Promise<void> | void) => {\n this.lazyOperations = this.lazyOperations.then(async () => {\n try {\n await operation();\n } catch (error) {\n this.logger?.error({ title: `Lazy storage \"${action}\" failed`, type: \"system\", extra: { queryKey, error } });\n }\n });\n };\n\n /**\n * Snapshot of the queue as JSON data - taken right away, as the queue objects change after the write is scheduled\n */\n private getLazyQueueData = (queue: QueueDataType): QueueDataType => {\n return JSON.parse(\n JSON.stringify({\n ...queue,\n requests: queue.requests.map((item) => ({\n ...item,\n request: this.isRequestJSON(item.request) ? item.request : item.request.toJSON(),\n })),\n }),\n );\n };\n\n /**\n * The sync storage stays the source of truth, its changes are written through to the lazy storage\n */\n private withLazyStorage = (\n storage: DispatcherStorageType,\n lazyStorage: DispatcherAsyncStorageType,\n ): DispatcherStorageType => ({\n get: (key) => storage.get(key),\n keys: () => storage.keys(),\n entries: () => storage.entries(),\n set: (key, data) => {\n storage.set(key, data);\n const snapshot = this.getLazyQueueData(data as QueueDataType);\n this.runLazyOperation(\"set\", key, () => lazyStorage.set(key, snapshot));\n },\n delete: (key) => {\n storage.delete(key);\n this.runLazyOperation(\"delete\", key, () => lazyStorage.delete(key));\n },\n clear: () => {\n storage.clear();\n this.runLazyOperation(\"clear\", null, async () => {\n const keys = [...(await lazyStorage.keys())];\n await Promise.all(keys.map((key) => lazyStorage.delete(key)));\n });\n },\n });\n\n /**\n * Reads the queues persisted by the previous run. Persisted requests are older than the ones added since the start,\n * so they go first. Requests already in the queue are not added twice.\n */\n private restoreLazyQueues = (lazyStorage: DispatcherAsyncStorageType) => {\n this.runLazyOperation(\"restore\", null, async () => {\n const keys = [...(await lazyStorage.keys())];\n const persistedQueues = await Promise.all(keys.map(async (key) => [key, await lazyStorage.get(key)] as const));\n\n persistedQueues.forEach(([queryKey, persisted]) => {\n if (!persisted?.requests.length) {\n return;\n }\n const queue = this.getQueue(queryKey);\n const knownIds = new Set(queue.requests.map((item) => item.requestId));\n const restored = persisted.requests\n .filter((item) => !knownIds.has(item.requestId))\n .map((item) => ({\n ...item,\n request: this.isRequestJSON(item.request) ? this.client.fromJSON(item.request) : item.request,\n }));\n\n if (restored.length) {\n this.setQueue(queryKey, { ...queue, requests: [...restored, ...queue.requests] });\n this.flushQueue(queryKey);\n }\n });\n });\n };\n\n // eslint-disable-next-line class-methods-use-this\n private isRequestJSON = (\n request: RequestInstance | RequestJSON<RequestInstance>,\n ): request is RequestJSON<RequestInstance> => {\n return !(request instanceof Request);\n };\n\n initialize = (client: ClientInstance<{ adapter: Adapter }>) => {\n this.client = client;\n this.logger = client.loggerManager.initialize(client, \"Dispatcher\");\n\n // Going back from offline should re-trigger all requests\n this.client.appManager.events.onOnline(() => {\n this.flush();\n });\n\n // A queue restored from a persistent storage (e.g. the requests left by the previous page load) has to be sent\n // on start. It waits for the next task, so the configuration chained after the client constructor - adapter,\n // interceptors, plugins - applies to the restored requests too.\n if (this.options?.lazyStorage) {\n this.restoreLazyQueues(this.options.lazyStorage);\n }\n\n clearTimeout(this.startTimer);\n if (this.getQueuesKeys().length) {\n this.startTimer = setTimeout(() => {\n this.startTimer = undefined;\n this.flush();\n });\n }\n\n return this;\n };\n\n // *********************************************************************\n // *********************************************************************\n // Queue\n // *********************************************************************\n // *********************************************************************\n\n /**\n * Start request handling by queryKey\n */\n start = (queryKey: string) => {\n // Change status to running\n const queue = this.getQueue(queryKey);\n\n // Start the queue when its stopped\n queue.stopped = false;\n this.setQueue(queryKey, queue);\n this.flushQueue(queryKey);\n this.client.triggerPlugins(\"onDispatcherQueueRunning\", { dispatcher: this, queue, status: \"running\" });\n this.events.emitQueueStatusChanged(queue);\n };\n\n /**\n * Pause request queue, but do not cancel already started requests\n */\n pause = (queryKey: string) => {\n // Change state to stopped\n const queue = this.getQueue(queryKey);\n\n queue.stopped = true;\n this.setQueue(queryKey, queue);\n this.client.triggerPlugins(\"onDispatcherQueueRunning\", { dispatcher: this, queue, status: \"paused\" });\n this.events.emitQueueStatusChanged(queue);\n };\n\n /**\n * Stop request queue and cancel all started requests - those will be treated like not started\n */\n stop = (queryKey: string) => {\n // Change state to stopped\n const queue = this.getQueue(queryKey);\n\n queue.stopped = true;\n this.setQueue(queryKey, queue);\n\n // Cancel running requests\n this.cancelRunningRequests(queryKey);\n this.client.triggerPlugins(\"onDispatcherQueueRunning\", { dispatcher: this, queue, status: \"stopped\" });\n this.events.emitQueueStatusChanged(queue);\n };\n\n /**\n * Return all queue keys currently tracked by the dispatcher storage\n */\n getQueuesKeys = () => {\n return [...this.storage.keys()];\n };\n\n /**\n * Return queue state object.\n * Automatically reconstructs any serialized (JSON) requests back into\n * proper Request class instances so the rest of the pipeline can rely on\n * having a real `RequestInstance`.\n */\n getQueue = <R extends RequestInstance = RequestInstance>(queryKey: string): ResolvedQueueDataType<R> => {\n const initialQueueState: ResolvedQueueDataType<R> = { queryKey, requests: [], stopped: false };\n const storedEntity = this.storage.get<R>(queryKey);\n\n if (!storedEntity) {\n return initialQueueState;\n }\n\n const resolvedRequests: ResolvedQueueItemType<R>[] = storedEntity.requests.map((item) => {\n if (this.isRequestJSON(item.request)) {\n return { ...item, request: this.client.fromJSON(item.request as RequestJSON<RequestInstance>) as unknown as R };\n }\n return item as ResolvedQueueItemType<R>;\n });\n\n return { ...storedEntity, requests: resolvedRequests };\n };\n\n /**\n * Return request from queue state\n */\n getRequest = <Request extends RequestInstance = RequestInstance>(queryKey: string, requestId: string) => {\n const initialQueueState: QueueDataType<Request> = { queryKey, requests: [], stopped: false };\n const storedEntity = this.storage.get<Request>(queryKey) || initialQueueState;\n\n return storedEntity.requests.find((req) => req.requestId === requestId);\n };\n\n /**\n * Get value of the active queue status based on the stopped status\n */\n getIsActiveQueue = (queryKey: string) => {\n const queue = this.getQueue(queryKey);\n const hasAvailableRequests = queue.requests.some((req) => !req.stopped);\n const isRunningQueue = !queue.stopped;\n return hasAvailableRequests && isRunningQueue;\n };\n\n /**\n * Add new element to storage\n */\n addQueueItem = <Request extends RequestInstance = RequestInstance>(\n queryKey: string,\n element: ResolvedQueueItemType<Request>,\n ) => {\n const queue = this.getQueue<Request>(queryKey);\n queue.requests.push(element);\n\n this.client.triggerPlugins(\"onDispatcherItemAdded\", { dispatcher: this, queue, queueItem: element });\n\n this.setQueue<Request>(queryKey, queue);\n };\n\n /**\n * Set new queue storage value\n */\n setQueue = <Request extends RequestInstance = RequestInstance>(\n queryKey: string,\n queue: ResolvedQueueDataType<Request>,\n ) => {\n this.storage.set<Request>(queryKey, queue as QueueDataType<Request>);\n\n // Emit Queue Changes\n this.client.triggerPlugins(\"onDispatcherQueueCreated\", { dispatcher: this, queue });\n this.events.emitQueueChanged(queue);\n\n return queue;\n };\n\n /**\n * Clear requests from queue cache\n */\n clearQueue = (queryKey: string) => {\n return this.removeQueueItems(\n queryKey,\n this.getRunningRequests(queryKey).map((running) => running.requestId),\n );\n };\n\n /**\n * Empty the queue. Requests listed in `answeredIds` are running or were just canceled, so they still report\n * their own response. All the others would never be heard of again - those are reported as removed.\n */\n private removeQueueItems = (queryKey: string, answeredIds: string[]) => {\n const queue = this.getQueue(queryKey);\n const newQueue = { queryKey, requests: [], stopped: queue.stopped };\n this.storage.set(queryKey, newQueue);\n\n // Emit Queue Changes\n this.client.triggerPlugins(\"onDispatcherQueueCleared\", { dispatcher: this, queue: newQueue });\n this.events.emitQueueChanged(newQueue);\n this.emitRemovedItems(queue.requests, answeredIds);\n this.events.emitDrained(newQueue);\n\n return newQueue;\n };\n\n private emitRemovedItems = (items: ResolvedQueueItemType[], answeredIds: string[]) => {\n items.forEach((item) => {\n this.cancelRetry(item.requestId);\n\n if (!answeredIds.includes(item.requestId)) {\n this.client.requestManager.events.emitRemove({\n requestId: item.requestId,\n request: item.request,\n resolved: item.resolved,\n });\n }\n });\n };\n\n /**\n * A request can be sent when it is not in flight, not held by `stopRequest`, not waiting for its retry,\n * not just answered and - for the requests kept for later with the `offline` option - when there is a connection.\n * Nothing is sent while the page unloads - the browser would cancel it right away.\n */\n private canPerformRequest = (item: ResolvedQueueItemType, runningIds: Set<string>) => {\n const isWaitingForNetwork = !this.client.appManager.isOnline && item.request.offline;\n\n return (\n !this.client.appManager.isUnloading &&\n !item.stopped &&\n !isWaitingForNetwork &&\n !this.retryTimers.has(item.requestId) &&\n !this.answeredRequests.has(item.requestId) &&\n !runningIds.has(item.requestId)\n );\n };\n\n /**\n * Method used to flush the queue requests\n */\n flushQueue = async (queryKey: string) => {\n const queue = this.getQueue(queryKey);\n const runningRequests = this.getRunningRequests(queryKey);\n const queueItem = queue.requests.find((request) => !request.stopped);\n\n const isStopped = queue && queue.stopped;\n const isOffline = !this.client.appManager.isOnline;\n const isConcurrent = !queueItem?.request.queued;\n const isInactive = runningRequests.length === 0;\n const isEmpty = !queueItem;\n\n // When there are no requests to flush, when its stopped, there is running request\n // or there is no request to trigger - we don't want to perform actions\n if (isStopped || isEmpty) {\n this.logger.debug({ title: \"Skipping queue trigger\", type: \"system\", extra: { isStopped, isOffline, isEmpty } });\n } else if (isConcurrent) {\n // Collected once - looking for every request in the list of the running ones gets slow with a long queue\n const runningIds = new Set(runningRequests.map((running) => running.requestId));\n queue.requests.forEach((element) => {\n if (this.canPerformRequest(element, runningIds)) {\n runningIds.add(element.requestId);\n this.performRequest(element);\n }\n });\n }\n // One by one - the first request holds the queue also while it waits for its retry or for the network\n else if (isInactive && this.canPerformRequest(queueItem, new Set())) {\n await this.performRequest(queueItem);\n this.flushQueue(queryKey);\n }\n };\n\n /**\n * Flush all available requests from all queues\n */\n flush = async () => {\n const keys = this.getQueuesKeys();\n\n // eslint-disable-next-line no-restricted-syntax\n for (const key of keys) {\n const storageItem = this.getQueue(key);\n\n if (storageItem) {\n this.flushQueue(key);\n }\n }\n };\n\n /**\n * Clear all running requests and storage\n */\n clear = () => {\n clearTimeout(this.startTimer);\n this.startTimer = undefined;\n const keys = this.getQueuesKeys();\n // Running requests are canceled and report it on their own, the waiting ones are reported as removed\n const removed = keys.map((queryKey) => ({\n items: this.getQueue(queryKey).requests,\n answeredIds: this.getRunningRequests(queryKey).map((running) => running.requestId),\n }));\n keys.forEach((queryKey) => this.cancelRunningRequests(queryKey));\n\n [...this.runningRequests.keys()].forEach((queryKey) => this.setRunningRequests(queryKey, []));\n this.runningRequests.clear();\n this.cachedOrder.clear();\n this.storage.clear();\n removed.forEach(({ items, answeredIds }) => this.emitRemovedItems(items, answeredIds));\n this.client.triggerPlugins(\"onDispatcherCleared\", { dispatcher: this });\n };\n\n /**\n * Drop the scheduled retry of the request\n */\n private cancelRetry = (requestId: string) => {\n const timer = this.retryTimers.get(requestId);\n if (timer === undefined) {\n return false;\n }\n\n clearTimeout(timer);\n return this.retryTimers.delete(requestId);\n };\n\n // *********************************************************************\n // *********************************************************************\n // Requests\n // *********************************************************************\n // *********************************************************************\n\n /**\n * Start particular request\n */\n startRequest = (queryKey: string, requestId: string) => {\n // Change status to running\n const queue = this.getQueue(queryKey);\n const request = queue.requests.find((element) => element.requestId === requestId);\n\n // Start the queue when its stopped\n if (request) {\n request.stopped = false;\n this.setQueue(queryKey, queue);\n this.flushQueue(queryKey);\n this.events.emitQueueStatusChanged(queue);\n }\n };\n\n /**\n * Stop particular request\n */\n stopRequest = (queryKey: string, requestId: string) => {\n // Change state to stopped\n const queue = this.getQueue(queryKey);\n const request = queue.requests.find((element) => element.requestId === requestId);\n\n if (request) {\n request.stopped = true;\n this.setQueue(queryKey, queue);\n\n // Cancel running requests\n this.cancelRunningRequest(queryKey, requestId);\n this.events.emitQueueStatusChanged(queue);\n }\n };\n\n /**\n * Get currently running requests from all queryKeys\n */\n getAllRunningRequests = () => {\n return [...this.runningRequests.values()].flat();\n };\n\n /**\n * Get currently running requests\n */\n getRunningRequests = (queryKey: string) => {\n return this.runningRequests.get(queryKey) || [];\n };\n\n /**\n * Get running request by id\n */\n getRunningRequest = (queryKey: string, requestId: string) => {\n const runningRequests = this.getRunningRequests(queryKey);\n return runningRequests.find((req) => req.requestId === requestId);\n };\n\n /**\n * Single place for changing the running requests - notifies about the change\n */\n private setRunningRequests = (queryKey: string, runningRequests: RunningRequestValueType[]) => {\n const previousRequests = this.getRunningRequests(queryKey);\n if (runningRequests.length > 0) {\n this.runningRequests.set(queryKey, runningRequests);\n } else {\n // Do not keep an empty list for every queryKey that was ever used\n this.runningRequests.delete(queryKey);\n }\n if (\n previousRequests.length !== runningRequests.length ||\n previousRequests.some((req, i) => req !== runningRequests[i])\n ) {\n this.events.emitRunningRequestsChanged({ queryKey, runningRequests });\n }\n };\n\n /**\n * Add request to the running requests list\n */\n addRunningRequest = (queryKey: string, requestId: string, request: RequestInstance): RunningRequestValueType => {\n const newRunningRequest = { requestId, request, timestamp: Date.now() };\n this.setRunningRequests(queryKey, [...this.getRunningRequests(queryKey), newRunningRequest]);\n return newRunningRequest;\n };\n\n /**\n * Get the value based on the currently running requests\n */\n hasRunningRequests = (queryKey: string) => {\n return this.getRunningRequests(queryKey).length > 0;\n };\n\n /**\n * Check if request is currently processing\n */\n hasRunningRequest = (queryKey: string, requestId: string) => {\n const runningRequests = this.getRunningRequests(queryKey);\n return !!runningRequests.some((req) => req.requestId === requestId);\n };\n\n /**\n * Cancel all started requests, but do NOT remove it from main storage\n */\n cancelRunningRequests = (queryKey: string) => {\n this.runningRequests.get(queryKey)?.forEach((req) => {\n const ak = scopeKey(req.request.abortKey, req.request.scope);\n this.client.requestManager.abortByRequestId(ak, req.requestId);\n });\n this.deleteRunningRequests(queryKey);\n };\n /**\n * Cancel started request, but do NOT remove it from main storage\n */\n cancelRunningRequest = (queryKey: string, requestId: string) => {\n const requests = this.getRunningRequests(queryKey).filter((request) => {\n if (request.requestId === requestId) {\n const ak = scopeKey(request.request.abortKey, request.request.scope);\n this.client.requestManager.abortByRequestId(ak, request.requestId);\n return false;\n }\n return true;\n });\n\n this.setRunningRequests(queryKey, requests);\n };\n\n /**\n * Delete all started requests, but do NOT clear it from queue and do NOT cancel them\n */\n deleteRunningRequests = (queryKey: string) => {\n this.setRunningRequests(queryKey, []);\n };\n\n /**\n * Delete request by id, but do NOT clear it from queue and do NOT cancel them\n */\n deleteRunningRequest = (queryKey: string, requestId: string) => {\n const runningRequests = this.getRunningRequests(queryKey);\n this.setRunningRequests(\n queryKey,\n runningRequests.filter((req) => req.requestId !== requestId),\n );\n };\n\n /**\n * Get count of requests from the same queryKey\n */\n getQueueRequestCount = (queryKey: string) => {\n return this.requestCount.get(queryKey) || 0;\n };\n\n /**\n * Add request count to the queryKey\n */\n incrementQueueRequestCount = (queryKey: string) => {\n const count = this.requestCount.get(queryKey) || 0;\n this.requestCount.set(queryKey, count + 1);\n };\n\n /**\n * Create storage element from request\n */\n // eslint-disable-next-line class-methods-use-this\n createStorageItem = <R extends RequestInstance>(request: R): ResolvedQueueItemType<R> => {\n const requestId = this.client.unstable_requestIdMapper(request);\n return {\n requestId,\n timestamp: Date.now(),\n request,\n retries: 0,\n stopped: false,\n resolved: false,\n };\n };\n\n // *********************************************************************\n // *********************************************************************\n // Dispatching\n // *********************************************************************\n // *********************************************************************\n\n /**\n * Add request to the dispatcher handler\n */\n add = (request: RequestInstance) => {\n const queryKey = scopeKey(request.queryKey, request.scope);\n\n // Create dump of the request to allow storing it in localStorage, AsyncStorage or any other\n // This way we don't save the Class but the instruction of the request to be done\n const storageItem = this.createStorageItem(request);\n const { requestId } = storageItem;\n\n const queue = this.getQueue(queryKey);\n const [latestRequest] = queue.requests.slice(-1);\n const requestType = getRequestType(request, latestRequest);\n\n this.logger.debug({ title: \"Adding request to queue\", type: \"system\", extra: { requestType, request, requestId } });\n\n switch (requestType) {\n case DispatcherMode.ONE_BY_ONE: {\n // Requests will go one by one\n this.addQueueItem(queryKey, storageItem);\n this.flushQueue(queryKey);\n return requestId;\n }\n case DispatcherMode.PREVIOUS_CANCELED: {\n // Cancel all previous on-going requests\n const canceledIds = this.getRunningRequests(queryKey).map((running) => running.requestId);\n this.cancelRunningRequests(queryKey);\n this.removeQueueItems(queryKey, canceledIds);\n this.addQueueItem(queryKey, storageItem);\n this.flushQueue(queryKey);\n return requestId;\n }\n case DispatcherMode.DEDUPLICATED: {\n this.client.requestManager.events.emitDeduplicated({\n request: latestRequest.request,\n requestId,\n deduplicatedRequest: request,\n });\n // Return the running requestId to fulfill the events\n return latestRequest.requestId;\n }\n default: {\n this.addQueueItem(queryKey, storageItem);\n this.flushQueue(queryKey);\n return requestId;\n }\n }\n };\n\n /**\n * Delete from the storage and cancel request\n */\n delete = (queryKey: string, requestId: string, abortKey: string) => {\n this.logger.debug({ title: \"Deleting request\", type: \"system\", extra: { queryKey, requestId, abortKey } });\n const queue = this.getQueue(queryKey);\n const queueItem = queue.requests.find((req) => req.requestId === requestId);\n\n if (!queueItem) {\n return;\n }\n\n queue.requests = queue.requests.filter((req) => req.requestId !== requestId);\n this.storage.set(queryKey, queue);\n this.cancelRetry(requestId);\n\n // Clean controllers\n if (this.hasRunningRequest(queryKey, requestId)) {\n this.deleteRunningRequest(queryKey, requestId);\n this.client.requestManager.abortByRequestId(abortKey, requestId);\n }\n\n // Emit Queue Changes\n this.client.triggerPlugins(\"onDispatcherItemDeleted\", { queue, dispatcher: this, queueItem });\n\n this.events.emitQueueChanged(queue);\n this.client.requestManager.events.emitRemove({\n requestId,\n request: queueItem.request,\n resolved: queueItem.resolved,\n });\n\n if (queue.requests.length === 0) {\n this.client.triggerPlugins(\"onDispatcherQueueDrained\", { queue, dispatcher: this });\n this.events.emitDrained(queue);\n }\n\n return queue;\n };\n\n /**\n * Save the number of used attempts on the queued request\n */\n private setQueueItemRetries = (queryKey: string, requestId: string, retries: number) => {\n const queue = this.getQueue(queryKey);\n const queueItem = queue.requests.find((item) => item.requestId === requestId);\n\n if (queueItem) {\n queueItem.retries = retries;\n this.storage.set(queryKey, queue);\n }\n };\n\n /**\n * The `retryOnError` callback belongs to the user - when it throws, the request is not retried\n */\n private getShouldRetryOnError = (request: RequestInstance, response: RequestResponseType<any>) => {\n if (!request.retryOnError) {\n return true;\n }\n try {\n return !!request.retryOnError(response);\n } catch (error) {\n this.logger.error({ title: \"The retryOnError callback failed\", type: \"system\", extra: { error, request } });\n return false;\n }\n };\n\n /**\n * Delay of the next attempt from the `retryTime` of the request. The function form belongs to the user - when it\n * throws, the request is not retried (`null`). Anything but a positive finite delay retries right away.\n */\n private getRetryDelay = (request: RequestInstance, attempt: number, response: RequestResponseType<any>) => {\n const { retryTime } = request;\n let delay: unknown = retryTime;\n if (typeof retryTime === \"function\") {\n try {\n delay = retryTime({ attempt, response });\n } catch (error) {\n this.logger.error({ title: \"The retryTime callback failed\", type: \"system\", extra: { error, request } });\n return null;\n }\n }\n return typeof delay === \"number\" && Number.isFinite(delay) && delay > 0 ? delay : 0;\n };\n\n /**\n * Request can run for some time, once it's done, we have to check if it's successful or if it was aborted\n * It can be different once the previous call was set as cancelled and removed from queue before this request got resolved\n */\n performRequest = async (storageItem: ResolvedQueueItemType) => {\n const { request, requestId } = storageItem;\n this.logger.debug({ title: \"Performing request\", type: \"system\", extra: { request, requestId } });\n\n const { retry, queryKey: rawQueryKey, abortKey: rawAbortKey, offline, scope } = request;\n const queryKey = scopeKey(rawQueryKey, scope);\n const abortKey = scopeKey(rawAbortKey, scope);\n const { adapter, requestManager, cache, appManager } = this.client;\n\n const canRetry = canRetryRequest(storageItem.retries, retry);\n // When offline not perform any request\n const isOffline = !appManager.isOnline && offline;\n // When request with this id was triggered again\n const isAlreadyRunning = this.hasRunningRequest(queryKey, requestId);\n const isStopped = storageItem.stopped;\n\n if (isOffline || isAlreadyRunning || isStopped) {\n return this.logger.warning({\n title: \"Unable to perform request\",\n type: \"system\",\n extra: { isOffline, isAlreadyRunning, isStopped },\n });\n }\n\n // Additionally keep the running request to possibly abort it later\n const runningRequest = this.addRunningRequest(queryKey, requestId, request);\n this.sentCount += 1;\n const sentOrder = this.sentCount;\n\n // Propagate the loading to all connected hooks\n requestManager.events.emitLoading({\n request,\n requestId,\n loading: true,\n isRetry: !!storageItem.retries,\n isOffline,\n });\n\n // Trigger Request\n this.incrementQueueRequestCount(queryKey);\n // Listen for aborting\n requestManager.addAbortController(abortKey, requestId);\n\n const response: RequestResponseType<any> = await adapter.fetch(request, requestId);\n\n // TODO: improve this\n // eslint-disable-next-line no-param-reassign\n storageItem.resolved = true;\n // Read before the controller is dropped - adapters may map the abort error into any shape (GraphQL uses arrays)\n const isAbortedByUser = requestManager.isCanceled(abortKey, requestId);\n // Stop listening for aborting\n requestManager.removeAbortController(abortKey, requestId);\n // Do not continue the request handling when it got stopped and request was unsuccessful\n // Or when the request was aborted/canceled\n const isOfflineResponseStatus = !appManager.isOnline;\n // If there is no running request with this id, it means it was cancelled and removed during send\n const isCancelMessage = getErrorMessage(\"abort\").message === response.error?.message;\n const isCanceled = !this.hasRunningRequest(queryKey, requestId) || isAbortedByUser || isCancelMessage;\n // The browser cancels the requests of an unloading page - the failure says nothing about the request itself\n const isUnloadFailure = !response.success && appManager.isUnloading;\n\n // Remove running request, must be called after isCancelled\n this.deleteRunningRequest(queryKey, requestId);\n\n // The request is no longer running, but it stays in the queue until its response is handled below. Listeners\n // of the response can add requests to this queue - flushing it must not send the answered request again.\n this.answeredRequests.add(requestId);\n try {\n // A request removed from the queue while it was running (cleared queue) has nothing left to retry\n const isQueued = !!this.getRequest(queryKey, requestId);\n const canRetryResponse =\n !response.success && canRetry && isQueued && !isCanceled && !isOfflineResponseStatus && !isUnloadFailure;\n const retryDelay =\n canRetryResponse && this.getShouldRetryOnError(request, response)\n ? this.getRetryDelay(request, storageItem.retries, response)\n : null;\n const willRetry = retryDelay !== null;\n\n const requestDetails: ResponseDetailsType = {\n isCanceled,\n isOffline: isOfflineResponseStatus,\n retries: storageItem.retries,\n willRetry,\n addedTimestamp: storageItem.timestamp,\n triggerTimestamp: runningRequest.timestamp,\n requestTimestamp: response.requestTimestamp,\n responseTimestamp: response.responseTimestamp,\n };\n\n // A throwing listener must not leave the request in the queue forever (and block all the queued ones behind it)\n const notify = (callback: VoidFunction) => {\n try {\n callback();\n } catch (error) {\n this.logger.error({\n title: \"Response listener failed\",\n type: \"system\",\n extra: { error, request, requestId },\n });\n throwOutsideLifecycle(error);\n }\n };\n\n // Global response emitter to handle request execution\n notify(() => requestManager.events.emitResponse({ request, requestId, response, details: requestDetails }));\n\n // Turn off loading\n notify(() =>\n requestManager.events.emitLoading({\n request,\n requestId,\n loading: false,\n isRetry: !!storageItem.retries,\n isOffline,\n }),\n );\n\n // Requests of one cache key can answer in another order than they were sent. Once the data of a request is in\n // the cache, a response of a request sent before it is outdated - it must not replace that data.\n const storageKey = scopeKey(request.cacheKey, scope);\n const isOutdated = (this.cachedOrder.get(storageKey) ?? 0) > sentOrder;\n // A pending optimistic change on the key makes the response stale - the refresh after it supplies current data.\n // Always checked, so a fetch marked as stale is released even when its response is skipped for another reason.\n let isStaleOptimistic = false;\n notify(() => {\n isStaleOptimistic = isStaleOptimisticResponse(this.client, request, requestId);\n });\n\n if (isOutdated) {\n this.logger.debug({\n title: \"Response of a request sent before the cached one, skipping the cache\",\n type: \"system\",\n extra: { requestId, request, response },\n });\n } else if (isStaleOptimistic) {\n this.logger.debug({\n title: \"Response started before a pending optimistic change settled, skipping the cache\",\n type: \"system\",\n extra: { requestId, request, response },\n });\n } else {\n if (response.success) {\n this.cachedOrder.set(storageKey, sentOrder);\n }\n // Cache event to emit the data inside and store it\n notify(() => cache.set(request, { ...response, ...requestDetails }));\n }\n this.logger.debug({\n title: \"Dispatcher processing response\",\n type: \"system\",\n extra: { requestId, request, response, details: requestDetails },\n });\n\n // On cancelled\n if (isCanceled) {\n const queue = this.getQueue(queryKey);\n const queueItem = queue.requests.find((req) => req.requestId === requestId);\n\n // do not remove cancelled request as it may be result of manual queue pause\n // if abort was done without stop action we can remove request\n if (!queue.stopped && !queueItem?.stopped) {\n this.logger.debug({ title: \"Request paused\", type: \"system\", extra: { response, requestDetails, request } });\n return this.delete(queryKey, requestId, abortKey);\n }\n return this.logger.debug({\n title: \"Request canceled\",\n type: \"system\",\n extra: { response, requestDetails, request },\n });\n }\n // On page unload - the request stays in the queue, a persistent storage sends it again on the next start\n if (isUnloadFailure) {\n return this.logger.debug({\n title: \"Page is unloading, keeping the request for the next start\",\n type: \"system\",\n extra: { response, requestDetails, request },\n });\n }\n // On offline\n if (!response.success && isOfflineResponseStatus) {\n // if we don't want to keep offline request - just delete them\n if (!offline) {\n this.logger.warning({\n title: \"Removing non-offline request\",\n type: \"system\",\n extra: { response, requestDetails, request },\n });\n return this.delete(queryKey, requestId, abortKey);\n }\n // do not remove request from store as we want to re-send it later\n return this.logger.debug({\n title: \"Awaiting for network restoration\",\n type: \"system\",\n extra: { response, requestDetails, request },\n });\n }\n // On success\n if (response.success) {\n this.delete(queryKey, requestId, abortKey);\n return this.logger.debug({\n title: \"Successful response, removing request from queue.\",\n type: \"system\",\n extra: {\n response,\n requestDetails,\n request,\n },\n });\n }\n // On retry\n if (willRetry) {\n this.logger.debug({ title: \"Waiting for retry\", type: \"system\", extra: { response, requestDetails, request } });\n const retries = storageItem.retries + 1;\n // The attempts are counted on the queued item - whatever sends it next (the timer below, a new request\n // flushing the queue, the network coming back, the queue being started) continues from this number\n this.setQueueItemRetries(queryKey, requestId, retries);\n // Only the latest failure schedules the retry\n this.cancelRetry(requestId);\n // Perform retry once request is failed\n const retryTimer = setTimeout(async () => {\n this.retryTimers.delete(requestId);\n const queueItem = this.getRequest(queryKey, requestId);\n\n // Dispatcher methods cancel this timer, so the item was taken directly from the storage and nobody announced it\n if (!queueItem) {\n this.logger.debug({\n title: \"Request no longer in queue, skipping retry\",\n type: \"request\",\n extra: { response, requestDetails, request, requestId },\n });\n requestManager.events.emitRemove({ requestId, request, resolved: storageItem.resolved });\n return;\n }\n // Stopped while waiting - it will be sent again when the request gets started\n if (queueItem.stopped) {\n return;\n }\n\n this.logger.warning({\n title: \"Error response, performing retry\",\n type: \"request\",\n extra: { response, requestDetails, request, requestId },\n });\n await this.performRequest({\n ...storageItem,\n retries,\n });\n // Let the queue go on when it was held by this request\n this.flushQueue(queryKey);\n }, retryDelay);\n this.retryTimers.set(requestId, retryTimer);\n // Announced once the retry is scheduled - listeners see the request waiting for it\n notify(() =>\n requestManager.events.emitRetry({\n request,\n requestId,\n response,\n details: requestDetails,\n retry: retries,\n delay: retryDelay,\n }),\n );\n } else {\n if (request.retry) {\n this.logger.error({\n title: \"All retries have been used. Removing request from queue.\",\n type: \"request\",\n extra: { response, requestDetails, request, requestId },\n });\n }\n this.delete(queryKey, requestId, abortKey);\n }\n } finally {\n this.answeredRequests.delete(requestId);\n // A request which stays in the queue was skipped by the flushes made from its listeners - for example\n // the one of the network coming back - so it gets its chance now\n if (this.getRequest(queryKey, requestId)) {\n this.flushQueue(queryKey);\n }\n }\n };\n}\n","import type { ResolvedQueueItemType } from \"dispatcher\";\nimport { DispatcherMode } from \"dispatcher\";\nimport type { RequestInstance } from \"request\";\n\n// Events\n\nexport const getDispatcherDrainedKey = (): string => {\n return `drained-event`;\n};\nexport const getDispatcherDrainedByKey = (key: string): string => {\n return `${key}-drained-event`;\n};\nexport const getDispatcherStatusKey = (): string => {\n return `status-event`;\n};\nexport const getDispatcherStatusByKey = (key: string): string => {\n return `${key}-status-event`;\n};\nexport const getDispatcherChangeKey = (): string => {\n return `change-event`;\n};\nexport const getDispatcherChangeByKey = (key: string): string => {\n return `${key}-change-event`;\n};\nexport const getDispatcherRunningKey = (): string => {\n return `running-event`;\n};\nexport const getDispatcherRunningByKey = (key: string): string => {\n return `${key}-running-event`;\n};\n\n// Requesting\n\nexport const getIsEqualTimestamp = (currentTimestamp: number, threshold: number, queueTimestamp?: number): boolean => {\n if (!queueTimestamp) {\n return false;\n }\n return queueTimestamp - currentTimestamp <= threshold;\n};\n\nexport const canRetryRequest = (currentRetries: number, retry: number | undefined) => {\n if (retry && currentRetries < retry) {\n return true;\n }\n return false;\n};\n\nconst isInDeduplicateRange = (request: RequestInstance, latestRequest: ResolvedQueueItemType) => {\n if (request.deduplicateTime) {\n return Date.now() - latestRequest.timestamp <= request.deduplicateTime;\n }\n return true;\n};\n\nexport const getRequestType = (request: RequestInstance, latestRequest: ResolvedQueueItemType | undefined) => {\n const { queued, cancelable, deduplicate, used } = request;\n const canDeduplicate = latestRequest ? isInDeduplicateRange(request, latestRequest) : false;\n // Only join requests that are genuinely still ongoing. A resolved item already emitted its\n // response (a late joiner would wait forever), and a stopped item may never fire at all.\n const isOngoing = latestRequest ? !latestRequest.resolved && !latestRequest.stopped : false;\n\n if (queued) {\n return DispatcherMode.ONE_BY_ONE;\n }\n if (cancelable) {\n return DispatcherMode.PREVIOUS_CANCELED;\n }\n // A request marked with setUsed(true) is an intentional resend, like the auth interceptor\n // retrying after a token refresh. Deduplicating it against the original in-flight request\n // would deadlock: the retry would wait for a response that is blocked on the interceptor.\n if (canDeduplicate && isOngoing && deduplicate && !used) {\n return DispatcherMode.DEDUPLICATED;\n }\n return DispatcherMode.ALL_AT_ONCE;\n};\n","import { Time } from \"constants/time.constants\";\n\nimport type { HttpAdapterExtraType } from \"./http-adapter.types\";\n\nexport const defaultTimeout = Time.SEC * 5;\n\n/**\n * Default `extra` of the `HttpAdapter`. It holds the response headers, so it starts empty and is used until a response\n * arrives, and for requests that fail before the server answers.\n */\nexport const httpExtra: HttpAdapterExtraType = {\n headers: {},\n};\n\n/**\n * @deprecated Use `httpExtra`. The `HttpAdapter` sends requests with `fetch`, not `XMLHttpRequest`.\n */\nexport const xhrExtra: HttpAdapterExtraType = httpExtra;\n","import type { QueryParamsType, QueryParamType, QueryParamValuesType } from \"adapter\";\nimport { getErrorMessage } from \"adapter\";\nimport { stringifyDefaultOptions } from \"client\";\nimport type { RequestInstance } from \"request\";\nimport type { ExtractErrorType, EmptyTypes } from \"types\";\n\nimport type { BufferEncoding, QueryStringifyOptionsType } from \"./http-adapter.types\";\n\n// Utils\n\nexport const getResponseHeaders = (headersString: string): Record<string, string> => {\n const arr = headersString.trim().split(/[\\r\\n]+/);\n\n const headers: Record<string, string> = {};\n arr.forEach((line) => {\n const parts = line.split(\": \");\n const header = parts.shift();\n const value = parts.join(\": \");\n if (header) {\n headers[header] = value;\n }\n });\n\n return headers;\n};\n\n// Responses\n\nexport const parseResponse = (response: string | unknown) => {\n try {\n return JSON.parse(response as string);\n } catch {\n return response;\n }\n};\n\nexport const handleResponse = (responseChunks: any[], responseType: string, responseEncoding: BufferEncoding) => {\n const bufferedResponse = Buffer.concat(responseChunks);\n switch (responseType) {\n case \"arraybuffer\": {\n return bufferedResponse;\n }\n case \"json\": {\n return parseResponse(bufferedResponse.toString(responseEncoding));\n }\n default: {\n return bufferedResponse.toString(responseEncoding);\n }\n }\n};\n\nexport const parseErrorResponse = <T extends RequestInstance>(response: unknown): ExtractErrorType<T> => {\n return response ? parseResponse(response) : (getErrorMessage() as ExtractErrorType<T>);\n};\n\n// Stringify\n\nconst isValidValue = (options: QueryStringifyOptionsType) => {\n return (value: QueryParamType) => {\n const { skipNull, skipEmptyString } = options;\n\n if (skipEmptyString && value === undefined) {\n return false;\n }\n if (skipEmptyString && value === \"\") {\n return false;\n }\n if (skipNull && value === null) {\n return false;\n }\n return true;\n };\n};\n\nconst encodeValue = (\n value: string,\n { encode, strict }: Pick<QueryStringifyOptionsType, \"encode\" | \"strict\">,\n): string => {\n if (encode && strict) {\n return encodeURIComponent(value).replaceAll(/[!'()*]/g, (s) => `%${s.codePointAt(0)!.toString(16).toUpperCase()}`);\n }\n if (encode) {\n return encodeURIComponent(value);\n }\n return value;\n};\n\nconst parseValue = (value: QueryParamValuesType, options: QueryStringifyOptionsType): string => {\n if (value instanceof Date) {\n return options.dateParser?.(value) || value.toISOString();\n }\n\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n return options.objectParser?.(value) || JSON.stringify(value);\n }\n\n return String(value);\n};\n\nconst encodeParams = (key: string, value: QueryParamType, options: QueryStringifyOptionsType) => {\n const shouldSkip = !isValidValue(options)(value);\n\n if (!key || shouldSkip) {\n return \"\";\n }\n\n return `${encodeValue(key, options)}=${encodeValue(parseValue(value as QueryParamValuesType, options), options)}`;\n};\n\nconst encodeArray = (key: string, array: QueryParamValuesType[], options: QueryStringifyOptionsType): string => {\n const { arrayFormat, arraySeparator } = options;\n const separator = arraySeparator || \"|\";\n const encodedKey = encodeValue(key, options);\n\n return array\n .filter(isValidValue(options))\n .reduce<string[]>((acc, value, index) => {\n const encodedValue = encodeValue(parseValue(value, options), options);\n\n switch (arrayFormat) {\n case \"index\": {\n acc.push(`${encodedKey}[${encodeValue(String(index), options)}]=${encodedValue}`);\n break;\n }\n case \"bracket\": {\n acc.push(`${encodedKey}[]=${encodedValue}`);\n break;\n }\n case \"comma\": {\n const keyValue = (acc.length === 0 && `${encodedKey}=`) || \"\";\n return [[...acc, `${keyValue}${encodedValue}`].join(\",\")];\n }\n case \"separator\": {\n const keyValue = (acc.length === 0 && `${encodedKey}=`) || \"\";\n return [[...acc, `${keyValue}${encodedValue}`].join(separator)];\n }\n case \"bracket-separator\": {\n const keyValue = (acc.length === 0 && `${encodedKey}[]=`) || \"\";\n return [[...acc, `${keyValue}${encodedValue}`].join(separator)];\n }\n default: {\n acc.push(`${encodedKey}=${encodedValue}`);\n }\n }\n\n return acc;\n }, [])\n .join(\"&\");\n};\n\nexport const stringifyQueryParams = (\n queryParams: QueryParamsType | string | EmptyTypes,\n options?: QueryStringifyOptionsType,\n): string => {\n // Merge with defaults so a partial config (e.g. `{ arrayFormat: \"comma\" }`) keeps encoding and skipping enabled\n const config: QueryStringifyOptionsType = { ...stringifyDefaultOptions, ...options };\n\n if (!queryParams || Object.keys(queryParams).length === 0) {\n return \"\";\n }\n\n if (typeof queryParams === \"string\") {\n const hasQuestionMark = queryParams[0] === \"?\";\n return hasQuestionMark ? queryParams : `?${queryParams}`;\n }\n\n const stringified = Object.entries(queryParams)\n .map(([key, value]): string => {\n if (Array.isArray(value)) {\n return encodeArray(key, value, config);\n }\n\n return encodeParams(key, value, config);\n })\n .filter(Boolean)\n .join(\"&\");\n\n if (stringified) {\n return `?${stringified}`;\n }\n return \"\";\n};\n","import type { QueryParamsType } from \"adapter\";\nimport { HttpMethods, SAFE_HTTP_METHODS } from \"constants/http.constants\";\nimport type { HttpMethodsType, HttpStatusType } from \"types\";\n\nimport { Adapter } from \"../adapter/adapter\";\nimport { defaultTimeout, httpExtra } from \"./http-adapter.constants\";\nimport type { HttpAdapterExtraType, FetchAdapterOptionsType, FetchResponseType } from \"./http-adapter.types\";\nimport { parseErrorResponse, parseResponse, stringifyQueryParams } from \"./http-adapter.utils\";\n\nconst defaultExtra = httpExtra;\n\n/**\n * Size in bytes of a body that fetch sends as it is. Form data and streams get their size from the browser while they\n * are sent, so it is unknown up front.\n */\nconst getBodySize = (body: unknown): number | undefined => {\n if (typeof body === \"string\") return new Blob([body]).size;\n if (typeof Blob !== \"undefined\" && body instanceof Blob) return body.size;\n if (body instanceof ArrayBuffer) return body.byteLength;\n if (ArrayBuffer.isView(body)) return body.byteLength;\n if (typeof URLSearchParams !== \"undefined\" && body instanceof URLSearchParams) {\n return new Blob([body.toString()]).size;\n }\n return undefined;\n};\n\n/**\n * Body of a successful response in the shape picked with the `responseType` option\n */\nconst readResponseBody = (bytes: Uint8Array, responseType: FetchResponseType | undefined, contentType: string | null) => {\n switch (responseType) {\n case \"arrayBuffer\": {\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n }\n case \"blob\": {\n return new Blob([bytes as BlobPart], { type: contentType ?? \"\" });\n }\n case \"text\": {\n return new TextDecoder().decode(bytes);\n }\n default: {\n return parseResponse(new TextDecoder().decode(bytes));\n }\n }\n};\n\nexport const getAdapter = () =>\n new Adapter<\n FetchAdapterOptionsType,\n HttpMethodsType,\n HttpStatusType,\n HttpAdapterExtraType,\n QueryParamsType | string | null,\n undefined,\n string\n >({\n name: \"http\",\n defaultMethod: HttpMethods.GET,\n defaultExtra,\n systemErrorStatus: 0 as number,\n systemErrorExtra: defaultExtra,\n })\n .setQueryParamsMapper(stringifyQueryParams)\n // Safe reads (GET, QUERY) deduplicate by default: concurrent identical requests collapse\n // into one network call. Explicit `deduplicate` in request options still wins.\n .setRequestDefaults((options) => {\n const method = options.method ?? HttpMethods.GET;\n if (SAFE_HTTP_METHODS.includes(method)) {\n return { deduplicate: true };\n }\n return {};\n })\n .setFetcher(\n async ({\n request,\n url,\n endpoint,\n queryParams,\n adapterOptions,\n headers,\n payload,\n onError,\n onResponseEnd,\n onTimeoutError,\n onRequestEnd,\n createAbortListener,\n getAbortController,\n onResponseProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onSuccess,\n }) => {\n const { method } = request;\n const fullUrl = `${url}${endpoint}${queryParams}`;\n\n const controller = getAbortController();\n const {\n timeout: timeoutMs = defaultTimeout,\n streaming = false,\n responseType,\n ...restOptions\n } = adapterOptions || {};\n\n let timedOut = false;\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n // Abort listener handles user-initiated aborts (e.g. request.abort())\n // For fetch, onAbort is a no-op since the signal is already passed to fetch()\n const unmountListener = createAbortListener({\n status: 0,\n extra: defaultExtra,\n });\n\n if (timeoutMs > 0 && controller) {\n timeoutId = setTimeout(() => {\n timedOut = true;\n unmountListener();\n controller.abort();\n }, timeoutMs);\n }\n\n const body = payload && method !== \"GET\" && method !== \"HEAD\" ? (payload as BodyInit) : undefined;\n const bodySize = getBodySize(body);\n\n onBeforeRequest();\n onRequestStart(bodySize ? { total: bodySize, loaded: 0 } : undefined);\n\n try {\n const init: RequestInit = {\n method,\n headers: headers as Record<string, string>,\n signal: controller?.signal,\n ...restOptions,\n };\n\n if (body) {\n init.body = body;\n }\n\n const response = await fetch(fullUrl, init);\n\n // Fetch has no upload events. The response is the first sign that the whole body was sent.\n onRequestEnd();\n\n // The timeout covers the whole exchange - a body that stops arriving has to end with the timeout error.\n // Only a streamed body is handed over to the user as soon as the headers arrive.\n if (timeoutId && streaming && response.body) {\n clearTimeout(timeoutId);\n }\n\n onResponseStart();\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n const extra: HttpAdapterExtraType = { headers: responseHeaders };\n const { status } = response;\n\n if (streaming && response.body) {\n onResponseEnd();\n unmountListener();\n\n if (response.ok) {\n onSuccess({ data: response.body as any, status, extra });\n } else {\n const errorBody = await response.text();\n const error = parseErrorResponse(errorBody);\n onError({ error, status, extra });\n }\n } else {\n // The body is read as bytes from the stream. Without a stream reader (e.g. React Native) it is read with\n // the method matching the response type - text for the default one, so nothing more than text is needed.\n let body: { bytes: Uint8Array } | { text: string } | { data: Blob | ArrayBuffer };\n\n if (response.body && typeof response.body.getReader === \"function\") {\n const reader = response.body.getReader();\n // Fetch gives the decompressed body, while Content-Length tells the size of the encoded one - the total\n // of an encoded body is unknown\n const contentEncoding = response.headers.get(\"content-encoding\");\n const isEncoded = !!contentEncoding && contentEncoding !== \"identity\";\n const contentLength = isEncoded ? 0 : parseInt(response.headers.get(\"content-length\") || \"0\", 10);\n let receivedLength = 0;\n const chunks: Uint8Array[] = [];\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n // eslint-disable-next-line no-await-in-loop\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n chunks.push(value);\n receivedLength += value.length;\n onResponseProgress({ total: contentLength || receivedLength, loaded: receivedLength } as ProgressEvent);\n }\n\n const allChunks = new Uint8Array(receivedLength);\n let position = 0;\n // eslint-disable-next-line no-restricted-syntax\n for (const chunk of chunks) {\n allChunks.set(chunk, position);\n position += chunk.length;\n }\n body = { bytes: allChunks };\n } else if (response.ok && responseType === \"blob\") {\n body = { data: await response.blob() };\n } else if (response.ok && responseType === \"arrayBuffer\") {\n body = { data: await response.arrayBuffer() };\n } else {\n body = { text: await response.text() };\n }\n\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n onResponseEnd();\n unmountListener();\n\n const getText = () => (\"text\" in body ? body.text : new TextDecoder().decode(\"bytes\" in body ? body.bytes : undefined));\n\n if (response.ok) {\n let data: unknown;\n if (\"data\" in body) {\n data = body.data;\n } else if (\"bytes\" in body) {\n data = readResponseBody(body.bytes, responseType, response.headers.get(\"content-type\"));\n } else {\n data = responseType === \"text\" ? body.text : parseResponse(body.text);\n }\n onSuccess({ data, status, extra });\n } else {\n const error = parseErrorResponse(getText());\n onError({ error, status, extra });\n }\n }\n } catch (error: any) {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n unmountListener();\n\n if (controller?.signal?.aborted) {\n if (timedOut) {\n onTimeoutError({ status: 0, extra: defaultExtra });\n }\n return;\n }\n\n onError({ error, status: 0, extra: defaultExtra });\n }\n },\n );\n","import type { HttpAdapterType } from \"http-adapter/http-adapter.types\";\n\nimport { getAdapter } from \"./http-adapter.fetch\";\n\nexport const HttpAdapter = (): HttpAdapterType => {\n return getAdapter();\n};\n","import type { AppManagerOptionsType } from \"managers\";\nimport { appManagerInitialOptions, getAppManagerEvents, hasDocument, onWindowEvent } from \"managers\";\nimport { EventEmitter } from \"utils\";\n\n/**\n * App manager handles main application states - focus and online. Those two values can answer questions:\n * - Is the tab or current view instance focused and visible for user?\n * - Is our application online or offline?\n * With the app manager it is not a problem to get the valid answer for this question.\n *\n * @caution\n * Make sure to apply valid focus/online handlers for different environments like for example for native mobile applications.\n */\nexport class AppManager {\n emitter = new EventEmitter();\n events = getAppManagerEvents(this.emitter);\n\n isBrowser: boolean;\n isOnline: boolean;\n isFocused: boolean;\n /**\n * True while the browser page is being unloaded (closed, reloaded or navigated away). The browser cancels the\n * requests in flight then - their failures are not real answers, so the dispatcher keeps them for the next start.\n */\n isUnloading = false;\n\n private unmountCallbacks: VoidFunction[] = [];\n private hasFocusUpdate = false;\n private hasOnlineUpdate = false;\n\n constructor(public options?: AppManagerOptionsType) {\n this.emitter?.setMaxListeners(1000);\n const {\n initiallyFocused = appManagerInitialOptions.initiallyFocused,\n initiallyOnline = appManagerInitialOptions.initiallyOnline,\n } = this.options || appManagerInitialOptions;\n\n this.setInitialFocus(initiallyFocused);\n this.setInitialOnline(initiallyOnline);\n\n this.isBrowser = hasDocument();\n }\n\n /**\n * Subscribes to the environment focus and network changes. Calling it again replaces the previous subscriptions,\n * so the listeners are never registered twice.\n */\n initialize = () => {\n const { focusEvent = appManagerInitialOptions.focusEvent, onlineEvent = appManagerInitialOptions.onlineEvent } =\n this.options || appManagerInitialOptions;\n\n this.unmount();\n\n [\n focusEvent(this.setFocused),\n onlineEvent(this.setOnline),\n onWindowEvent(\"pagehide\", () => {\n this.isUnloading = true;\n }),\n // The page can come back from the back-forward cache\n onWindowEvent(\"pageshow\", () => {\n this.isUnloading = false;\n }),\n ].forEach((unmount) => {\n if (typeof unmount === \"function\") {\n this.unmountCallbacks.push(unmount);\n }\n });\n };\n\n /**\n * Removes the environment listeners registered by `initialize()`. Listeners added with `events` are kept.\n */\n unmount = () => {\n const callbacks = this.unmountCallbacks;\n this.unmountCallbacks = [];\n callbacks.forEach((unmount) => unmount());\n };\n\n private setInitialFocus = (initValue: Exclude<AppManagerOptionsType[\"initiallyFocused\"], undefined>) => {\n this.isFocused = this.readInitialValue(initValue, (isFocused) => {\n // The environment could report the state in the meantime - it is more recent than the initial value\n if (!this.hasFocusUpdate && isFocused !== this.isFocused) {\n this.setFocused(isFocused);\n }\n });\n };\n\n private setInitialOnline = (initValue: Exclude<AppManagerOptionsType[\"initiallyOnline\"], undefined>) => {\n this.isOnline = this.readInitialValue(initValue, (isOnline) => {\n // The environment could report the state in the meantime - it is more recent than the initial value\n if (!this.hasOnlineUpdate && isOnline !== this.isOnline) {\n this.setOnline(isOnline);\n }\n });\n };\n\n /**\n * Reads the initial state from a value or a getter. Synchronous getters apply right away, so there is no moment\n * with a wrong value. Asynchronous ones start with `false` and apply once resolved - the change is emitted like\n * any other, so the modules waiting for the focus or the network get notified.\n * A getter which throws or rejects leaves the state unknown, so it falls back to `true` - just like the defaults do.\n */\n private readInitialValue = (\n initValue: boolean | (() => boolean | Promise<boolean>),\n onResolved: (value: boolean) => void,\n ): boolean => {\n if (typeof initValue !== \"function\") {\n return initValue;\n }\n\n try {\n const value = initValue();\n if (typeof value === \"boolean\") {\n return value;\n }\n\n Promise.resolve(value).then(\n (resolved) => onResolved(resolved),\n () => onResolved(true),\n );\n return false;\n } catch {\n return true;\n }\n };\n\n setFocused = (isFocused: boolean) => {\n this.hasFocusUpdate = true;\n this.isFocused = isFocused;\n\n if (isFocused) {\n this.events.emitFocus();\n } else {\n this.events.emitBlur();\n }\n };\n\n setOnline = (isOnline: boolean) => {\n this.hasOnlineUpdate = true;\n this.isOnline = isOnline;\n\n if (isOnline) {\n this.events.emitOnline();\n } else {\n this.events.emitOffline();\n }\n };\n}\n","export const hasWindow = () => {\n try {\n return Boolean(window && window.addEventListener);\n } catch {\n /* istanbul ignore next */\n return false;\n }\n};\n\nexport const hasDocument = () => {\n try {\n return Boolean(hasWindow() && window.document && window.document.addEventListener);\n } catch {\n /* istanbul ignore next */\n return false;\n }\n};\n\n/**\n * Reads the current network state from the browser. Falls back to `true` when it is unknown - e.g. in Node.js or\n * React Native, where `navigator.onLine` is not available.\n */\nexport const isNavigatorOnline = () => {\n try {\n return typeof navigator.onLine === \"boolean\" ? navigator.onLine : true;\n } catch {\n /* istanbul ignore next */\n return true;\n }\n};\n\nexport const onWindowEvent = <K extends keyof WindowEventMap>(\n key: K,\n listener: (this: Window, ev: WindowEventMap[K]) => any,\n options?: boolean | AddEventListenerOptions | undefined,\n): VoidFunction => {\n /* istanbul ignore next */\n if (hasWindow()) {\n // Keep the target - the cleanup has to reach the same object, even when the global one is already gone\n const target = window;\n target.addEventListener(key, listener, options);\n return () => target.removeEventListener(key, listener, options);\n }\n /* istanbul ignore next */\n return () => null;\n};\n\nexport const onDocumentEvent = <K extends keyof DocumentEventMap>(\n key: K,\n listener: (this: Document, ev: DocumentEventMap[K]) => any,\n options?: boolean | AddEventListenerOptions | undefined,\n): VoidFunction => {\n /* istanbul ignore next */\n if (hasDocument()) {\n // Keep the target - the cleanup has to reach the same object, even when the global one is already gone\n const target = window.document;\n target.addEventListener(key, listener, options);\n return () => target.removeEventListener(key, listener, options);\n }\n /* istanbul ignore next */\n return () => null;\n};\n","import type EventEmitter from \"events\";\nimport { AppEvents } from \"managers\";\n\n/** Create event emitters and listeners for application-level focus, blur, online, and offline state changes. */\nexport const getAppManagerEvents = (emitter: EventEmitter) => ({\n /** Emit when the application window gains focus */\n emitFocus: (): void => {\n emitter.emit(AppEvents.FOCUS);\n },\n /** Emit when the application window loses focus */\n emitBlur: (): void => {\n emitter.emit(AppEvents.BLUR);\n },\n /** Emit when the application transitions to online state */\n emitOnline: (): void => {\n emitter.emit(AppEvents.ONLINE);\n },\n /** Emit when the application transitions to offline state */\n emitOffline: (): void => {\n emitter.emit(AppEvents.OFFLINE);\n },\n /** Listen for focus events */\n onFocus: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.FOCUS, callback);\n return () => emitter.removeListener(AppEvents.FOCUS, callback);\n },\n /** Listen for blur events */\n onBlur: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.BLUR, callback);\n return () => emitter.removeListener(AppEvents.BLUR, callback);\n },\n /** Listen for online state transitions */\n onOnline: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.ONLINE, callback);\n return () => emitter.removeListener(AppEvents.ONLINE, callback);\n },\n /** Listen for offline state transitions */\n onOffline: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.OFFLINE, callback);\n return () => emitter.removeListener(AppEvents.OFFLINE, callback);\n },\n});\n","import type { AppManagerOptionsType } from \"managers\";\nimport type { RequiredKeys } from \"types\";\n\nimport { onWindowEvent, onDocumentEvent, isNavigatorOnline } from \"./app.manager.utils\";\n\n/** Document is visible unless the browser reports it as hidden - when the state is unknown we assume it is visible */\nconst isDocumentVisible = () => {\n try {\n return window.document.visibilityState !== \"hidden\";\n } catch {\n /* istanbul ignore next */\n return true;\n }\n};\n\nexport enum AppEvents {\n FOCUS = \"focus\",\n BLUR = \"blur\",\n ONLINE = \"online\",\n OFFLINE = \"offline\",\n}\n\nexport const appManagerInitialOptions: RequiredKeys<AppManagerOptionsType> = {\n initiallyFocused: true,\n initiallyOnline: isNavigatorOnline,\n focusEvent: (setFocused) => {\n // Visibility changes in both directions - hidden document means the application lost the focus\n const unmountVisibility = onDocumentEvent(\"visibilitychange\", () => setFocused(isDocumentVisible()));\n const unmountFocus = onWindowEvent(\"focus\", () => setFocused(true));\n const unmountBlur = onWindowEvent(\"blur\", () => setFocused(false));\n\n return () => {\n unmountVisibility();\n unmountFocus();\n unmountBlur();\n };\n },\n onlineEvent: (setOnline) => {\n const unmountOnline = onWindowEvent(\"online\", () => setOnline(true));\n const unmountOffline = onWindowEvent(\"offline\", () => setOnline(false));\n\n return () => {\n unmountOnline();\n unmountOffline();\n };\n },\n};\n","import { getRequestManagerEvents } from \"managers\";\nimport { EventEmitter } from \"utils\";\n\n/**\n * **Request Manager** is used to emit `request lifecycle events` like - request start, request end, upload and download progress.\n * It is also the place of `request aborting` system, here we store all the keys and controllers that are isolated for each client instance.\n */\nexport class RequestManager {\n emitter = new EventEmitter();\n events = getRequestManagerEvents(this.emitter);\n\n constructor() {\n this.emitter?.setMaxListeners(1000);\n }\n\n abortControllers = new Map<string, Map<string, AbortController>>();\n /** Controllers aborted through this manager, i.e. by the user and not by an adapter's own timeout */\n private canceledControllers = new WeakSet<AbortController>();\n\n addAbortController = (abortKey: string, requestId: string) => {\n let abortGroup = this.abortControllers.get(abortKey);\n if (!abortGroup) {\n const newAbortGroup = new Map();\n abortGroup = newAbortGroup;\n this.abortControllers.set(abortKey, newAbortGroup);\n }\n\n const abortController = abortGroup.get(requestId);\n if (!abortController || abortController.signal.aborted) {\n abortGroup.set(requestId, new AbortController());\n }\n };\n\n getAbortController = (abortKey: string, requestId: string) => {\n return this.abortControllers.get(abortKey)?.get(requestId);\n };\n\n removeAbortController = (abortKey: string, requestId: string) => {\n const abortGroup = this.abortControllers.get(abortKey);\n abortGroup?.delete(requestId);\n\n // Do not keep an empty group for every abortKey (and every scope) that was ever used\n if (abortGroup?.size === 0) {\n this.abortControllers.delete(abortKey);\n }\n };\n\n // Aborting\n\n useAbortController = (abortKey: string, requestId: string) => {\n const controller = this.abortControllers.get(abortKey)?.get(requestId);\n if (controller) {\n this.canceledControllers.add(controller);\n controller.abort();\n }\n };\n\n /**\n * Whether the request was aborted on purpose (`request.abort()`, `abortByKey`...). Tells canceled requests apart\n * from failed ones whatever shape the adapter gives its errors.\n */\n isCanceled = (abortKey: string, requestId: string) => {\n const controller = this.abortControllers.get(abortKey)?.get(requestId);\n return !!controller && this.canceledControllers.has(controller);\n };\n\n abortByKey = (abortKey: string) => {\n const controllers = this.abortControllers.get(abortKey);\n\n if (controllers) {\n const entries = [...controllers.entries()];\n entries.forEach(([key]) => {\n this.useAbortController(abortKey, key);\n });\n }\n };\n\n abortByRequestId = (abortKey: string, requestId: string) => {\n this.useAbortController(abortKey, requestId);\n };\n\n abortAll = () => {\n const entries = [...this.abortControllers.entries()];\n entries.forEach(([abortKey, value]) => {\n const controllers = [...value.entries()];\n controllers.forEach(([requestId]) => {\n this.useAbortController(abortKey, requestId);\n });\n });\n };\n}\n","// Events\n\nexport const getLoadingKey = (): string => `loading-event-any`;\nexport const getLoadingByQueryKey = (queryKey: string): string => `${queryKey}-loading-event`;\nexport const getLoadingByCacheKey = (cacheKey: string): string => `${cacheKey}-loading-cache-event`;\nexport const getLoadingByIdKey = (id: string): string => `${id}-loading-event-by-id`;\nexport const getRemoveKey = (): string => `remove-event-any`;\nexport const getRemoveByQueryKey = (queryKey: string): string => `${queryKey}-remove-event`;\nexport const getRemoveByIdKey = (id: string): string => `${id}-remove-event-by-id`;\nexport const getAbortKey = () => `request-abort-any`;\nexport const getAbortByAbortKey = (abortKey: string) => `${abortKey}-request-abort`;\nexport const getAbortByIdKey = (id: string) => `${id}-request-abort-by-id`;\nexport const getResponseKey = () => `response-any`;\nexport const getResponseByCacheKey = (cacheKey: string) => `${cacheKey}-response`;\nexport const getResponseByIdKey = (id: string) => `${id}-response-by-id`;\nexport const getRequestStartKey = () => `request-start-any`;\nexport const getRequestStarByQueryKey = (queryKey: string) => `${queryKey}-request-start`;\nexport const getRequestStartByIdKey = (id: string) => `${id}-request-start-by-id`;\nexport const getResponseStartKey = () => `response-start-any`;\nexport const getResponseStartByQueryKey = (queryKey: string) => `${queryKey}-response-start`;\nexport const getResponseStartByIdKey = (id: string) => `${id}-response-start-by-id`;\nexport const getUploadProgressKey = () => `request-progress-any`;\nexport const getUploadProgressByQueryKey = (queryKey: string) => `${queryKey}-request-progress`;\nexport const getUploadProgressByIdKey = (id: string) => `${id}-request-progress-by-id`;\nexport const getDownloadProgressKey = () => `response-progress-any`;\nexport const getDownloadProgressByQueryKey = (queryKey: string) => `${queryKey}-response-progress`;\nexport const getDownloadProgressByIdKey = (id: string) => `${id}-response-progress-by-id`;\nexport const getRetryKey = () => `request-retry-any`;\nexport const getRetryByQueryKey = (queryKey: string) => `${queryKey}-request-retry`;\nexport const getRetryByIdKey = (id: string) => `${id}-request-retry-by-id`;\nexport const getRequestDeduplicatedKey = () => `request-deduplicated-any`;\nexport const getRequestDeduplicatedByQueryKey = (queryKey: string) => `${queryKey}-query-request-deduplicated`;\nexport const getRequestDeduplicatedByCacheKey = (cacheKey: string) => `${cacheKey}-cache-request-deduplicated`;\nexport const getRequestDeduplicatedByIdKey = (id: string) => `${id}-request-deduplicated-by-id`;\n","import type { AdapterInstance } from \"adapter\";\nimport type { Client } from \"client\";\n/* eslint-disable max-params */\nimport type EventEmitter from \"events\";\nimport type {\n RequestEventType,\n RequestLoadingEventType,\n RequestProgressEventType,\n RequestResponseEventType,\n RequestRemovedEventType,\n RequestDeduplicatedEventType,\n RequestRetryEventType,\n} from \"managers\";\nimport {\n getRequestStarByQueryKey,\n getResponseStartByQueryKey,\n getDownloadProgressByQueryKey,\n getUploadProgressByQueryKey,\n getResponseByIdKey,\n getAbortByAbortKey,\n getAbortByIdKey,\n getResponseByCacheKey,\n getUploadProgressByIdKey,\n getDownloadProgressByIdKey,\n getResponseStartByIdKey,\n getRequestStartByIdKey,\n getLoadingByQueryKey,\n getLoadingByIdKey,\n getRemoveByQueryKey,\n getRemoveByIdKey,\n getLoadingKey,\n getRequestStartKey,\n getUploadProgressKey,\n getDownloadProgressKey,\n getResponseKey,\n getAbortKey,\n getRemoveKey,\n getResponseStartKey,\n getLoadingByCacheKey,\n getRequestDeduplicatedKey,\n getRequestDeduplicatedByIdKey,\n getRequestDeduplicatedByCacheKey,\n getRequestDeduplicatedByQueryKey,\n getRetryKey,\n getRetryByIdKey,\n getRetryByQueryKey,\n} from \"managers\";\nimport type { RequestInstance } from \"request\";\nimport type { ExtendRequest } from \"types\";\n\n/** Create event emitters and listeners for the request lifecycle: loading, progress, response, retry, abort, deduplication, and removal. */\nexport const getRequestManagerEvents = (emitter: EventEmitter) => ({\n /**\n * Emitters\n */\n\n /** Emit when a request is deduplicated (skipped because an identical one is in-flight) */\n emitDeduplicated: (data: RequestDeduplicatedEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getRequestDeduplicatedKey(), data, isTriggeredExternally);\n emitter.emit(getRequestDeduplicatedByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getRequestDeduplicatedByCacheKey(data.request.cacheKey), data, isTriggeredExternally);\n emitter.emit(getRequestDeduplicatedByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit loading state changes for a request */\n emitLoading: (data: RequestLoadingEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getLoadingKey(), data, isTriggeredExternally);\n emitter.emit(getLoadingByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getLoadingByCacheKey(data.request.cacheKey), data, isTriggeredExternally);\n emitter.emit(getLoadingByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit when a request starts being sent */\n emitRequestStart: (data: RequestEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getRequestStartKey(), data, isTriggeredExternally);\n emitter.emit(getRequestStartByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getRequestStarByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n /** Emit when the response starts being received */\n emitResponseStart: (data: RequestEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getResponseStartKey(), data, isTriggeredExternally);\n emitter.emit(getResponseStartByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getResponseStartByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit upload progress updates */\n emitUploadProgress: (data: RequestProgressEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getUploadProgressKey(), data, isTriggeredExternally);\n emitter.emit(getUploadProgressByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getUploadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n /** Emit download progress updates */\n emitDownloadProgress: (data: RequestProgressEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getDownloadProgressKey(), data, isTriggeredExternally);\n emitter.emit(getDownloadProgressByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getDownloadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit when a response is received */\n emitResponse: <Adapter extends AdapterInstance>(\n data: RequestResponseEventType<ExtendRequest<RequestInstance, { client: Client<any, Adapter> }>>,\n isTriggeredExternally = false,\n ): void => {\n emitter.emit(getResponseKey(), data, isTriggeredExternally);\n emitter.emit(getResponseByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getResponseByCacheKey(data.request.cacheKey), data, isTriggeredExternally);\n },\n\n /** Emit when a failed attempt schedules a retry - after its response, before the wait for the next attempt */\n emitRetry: (data: RequestRetryEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getRetryKey(), data, isTriggeredExternally);\n emitter.emit(getRetryByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getRetryByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit when a request is aborted */\n emitAbort: (data: RequestEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getAbortKey(), data, isTriggeredExternally);\n emitter.emit(getAbortByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getAbortByAbortKey(data.request.abortKey), data, isTriggeredExternally);\n },\n\n /** Emit when a request is removed from the dispatcher queue */\n emitRemove: (data: RequestRemovedEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getRemoveKey(), data, isTriggeredExternally);\n emitter.emit(getRemoveByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getRemoveByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /**\n * Listeners\n */\n\n /** Listen for deduplicated request events */\n onDeduplicated: <T extends RequestInstance>(\n callback: (data: RequestDeduplicatedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestDeduplicatedKey(), callback);\n return () => emitter.removeListener(getRequestDeduplicatedKey(), callback);\n },\n onDeduplicatedByQueue: <T extends RequestInstance>(\n queryKey: string,\n callback: (data: RequestDeduplicatedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestDeduplicatedByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getRequestDeduplicatedByQueryKey(queryKey), callback);\n },\n onDeduplicatedByCache: <T extends RequestInstance>(\n cacheKey: string,\n callback: (data: RequestDeduplicatedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestDeduplicatedByCacheKey(cacheKey), callback);\n return () => emitter.removeListener(getRequestDeduplicatedByCacheKey(cacheKey), callback);\n },\n onDeduplicatedById: <T extends RequestInstance>(\n requestId: string,\n callback: (data: RequestDeduplicatedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestDeduplicatedByIdKey(requestId), callback);\n return () => emitter.removeListener(getRequestDeduplicatedByIdKey(requestId), callback);\n },\n\n // Loading\n onLoading: <T extends RequestInstance>(callback: (data: RequestLoadingEventType<T>) => void): VoidFunction => {\n emitter.on(getLoadingKey(), callback);\n return () => emitter.removeListener(getLoadingKey(), callback);\n },\n onLoadingByQueue: <T extends RequestInstance>(\n queryKey: string,\n callback: (data: RequestLoadingEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getLoadingByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getLoadingByQueryKey(queryKey), callback);\n },\n onLoadingByCache: <T extends RequestInstance>(\n cacheKey: string,\n callback: (data: RequestLoadingEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getLoadingByCacheKey(cacheKey), callback);\n return () => emitter.removeListener(getLoadingByCacheKey(cacheKey), callback);\n },\n onLoadingById: <T extends RequestInstance>(\n requestId: string,\n callback: (data: RequestLoadingEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getLoadingByIdKey(requestId), callback);\n return () => emitter.removeListener(getLoadingByIdKey(requestId), callback);\n },\n\n // Request Start\n onRequestStart: <T extends RequestInstance>(callback: (details: RequestEventType<T>) => void): VoidFunction => {\n emitter.on(getRequestStartKey(), callback);\n return () => emitter.removeListener(getRequestStartKey(), callback);\n },\n onRequestStartByQueue: <T extends RequestInstance>(\n queryKey: string,\n callback: (details: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestStarByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getRequestStarByQueryKey(queryKey), callback);\n },\n onRequestStartById: <T extends RequestInstance>(\n requestId: string,\n callback: (details: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestStartByIdKey(requestId), callback);\n return () => emitter.removeListener(getRequestStartByIdKey(requestId), callback);\n },\n\n // Response Start\n onResponseStart: <T extends RequestInstance>(callback: (details: RequestEventType<T>) => void): VoidFunction => {\n emitter.on(getResponseStartKey(), callback);\n return () => emitter.removeListener(getResponseStartKey(), callback);\n },\n onResponseStartByQueue: <T extends RequestInstance>(\n queryKey: string,\n callback: (details: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseStartByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getResponseStartByQueryKey(queryKey), callback);\n },\n onResponseStartById: <T extends RequestInstance>(\n requestId: string,\n callback: (details: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseStartByIdKey(requestId), callback);\n return () => emitter.removeListener(getResponseStartByIdKey(requestId), callback);\n },\n\n // Progress\n onUploadProgress: <T extends RequestInstance = RequestInstance>(\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getUploadProgressKey(), callback);\n return () => emitter.removeListener(getUploadProgressKey(), callback);\n },\n onUploadProgressByQueue: <T extends RequestInstance = RequestInstance>(\n queryKey: string,\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getUploadProgressByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getUploadProgressByQueryKey(queryKey), callback);\n },\n onUploadProgressById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getUploadProgressByIdKey(requestId), callback);\n return () => emitter.removeListener(getUploadProgressByIdKey(requestId), callback);\n },\n\n onDownloadProgress: <T extends RequestInstance = RequestInstance>(\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getDownloadProgressKey(), callback);\n return () => emitter.removeListener(getDownloadProgressKey(), callback);\n },\n onDownloadProgressByQueue: <T extends RequestInstance = RequestInstance>(\n queryKey: string,\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getDownloadProgressByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getDownloadProgressByQueryKey(queryKey), callback);\n },\n onDownloadProgressById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getDownloadProgressByIdKey(requestId), callback);\n return () => emitter.removeListener(getDownloadProgressByIdKey(requestId), callback);\n },\n\n // Response\n onResponse: <T extends RequestInstance>(callback: (data: RequestResponseEventType<T>) => void): VoidFunction => {\n emitter.on(getResponseKey(), callback);\n return () => emitter.removeListener(getResponseKey(), callback);\n },\n onResponseByCache: <T extends RequestInstance>(\n cacheKey: string,\n callback: (data: RequestResponseEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseByCacheKey(cacheKey), callback);\n return () => emitter.removeListener(getResponseByCacheKey(cacheKey), callback);\n },\n onResponseById: <T extends RequestInstance>(\n requestId: string,\n callback: (data: RequestResponseEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseByIdKey(requestId), callback);\n return () => emitter.removeListener(getResponseByIdKey(requestId), callback);\n },\n\n // Abort\n onAbort: <T extends RequestInstance = RequestInstance>(\n callback: (request: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getAbortKey(), callback);\n return () => emitter.removeListener(getAbortKey(), callback);\n },\n onAbortByKey: <T extends RequestInstance = RequestInstance>(\n abortKey: string,\n callback: (request: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getAbortByAbortKey(abortKey), callback);\n return () => emitter.removeListener(getAbortByAbortKey(abortKey), callback);\n },\n onAbortById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getAbortByIdKey(requestId), callback);\n return () => emitter.removeListener(getAbortByIdKey(requestId), callback);\n },\n\n // Retry\n /** Listen to every scheduled retry - the event carries the failed response, the retry number and its delay */\n onRetry: <T extends RequestInstance = RequestInstance>(\n callback: (data: RequestRetryEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRetryKey(), callback);\n return () => emitter.removeListener(getRetryKey(), callback);\n },\n /** Listen to the retries scheduled by the requests of the queue */\n onRetryByQueue: <T extends RequestInstance = RequestInstance>(\n queryKey: string,\n callback: (data: RequestRetryEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRetryByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getRetryByQueryKey(queryKey), callback);\n },\n /** Listen to the retries scheduled by one request */\n onRetryById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestRetryEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRetryByIdKey(requestId), callback);\n return () => emitter.removeListener(getRetryByIdKey(requestId), callback);\n },\n\n // Remove\n onRemove: <T extends RequestInstance = RequestInstance>(\n callback: (data: RequestRemovedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRemoveKey(), callback);\n return () => emitter.removeListener(getRemoveKey(), callback);\n },\n onRemoveByQueue: <T extends RequestInstance = RequestInstance>(\n queryKey: string,\n callback: (data: RequestRemovedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRemoveByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getRemoveByQueryKey(queryKey), callback);\n },\n onRemoveById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestRemovedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRemoveByIdKey(requestId), callback);\n return () => emitter.removeListener(getRemoveByIdKey(requestId), callback);\n },\n});\n","import type { ClientInstance } from \"client\";\nimport EventEmitter from \"events\";\nimport type { LogLevel, LoggerArgs, LoggerOptionsType, LoggerType, LoggerMethods } from \"managers\";\nimport { logger, logLevelOrder } from \"managers\";\n\n/**\n * This class is used across the Hyper Fetch library to provide unified logging system with necessary setup per each client.\n * We can set up the logging level based on available values. This manager enable to initialize the logging instance per individual module\n * like Client, Request etc. Which can give you better feedback on the logging itself.\n */\nexport class LoggerManager {\n logger: LoggerType;\n level: LogLevel;\n modules: string[] | undefined;\n\n public emitter = new EventEmitter();\n\n private client: Pick<ClientInstance, \"debug\">;\n\n constructor(private options?: LoggerOptionsType) {\n this.emitter?.setMaxListeners(1000);\n this.logger = this.options?.logger || logger;\n this.level = this.options?.level || \"warning\";\n this.modules = this.options?.modules;\n }\n\n setSeverity = (level: LogLevel) => {\n this.level = level;\n };\n\n setModules = (modules: string[] | undefined) => {\n this.modules = modules;\n };\n\n initialize = (client: Pick<ClientInstance, \"debug\">, module: string): LoggerMethods => {\n this.client = client;\n\n // Modules keep their logger methods for the whole lifetime. When they come from the logger manager of the client,\n // the logs have to follow the manager currently assigned to it - otherwise `client.setLogger()` would affect\n // only the modules initialized later.\n const getClientManager = () => (client as Partial<Pick<ClientInstance, \"loggerManager\">>).loggerManager;\n const isClientManager = getClientManager() === this;\n\n const log: LoggerType = (data) => {\n const clientManager = getClientManager();\n const manager = isClientManager && clientManager instanceof LoggerManager ? clientManager : this;\n manager.log(data, client);\n };\n\n return {\n error: (data) => log({ ...data, level: \"error\", module }),\n warning: (data) => log({ ...data, level: \"warning\", module }),\n info: (data) => log({ ...data, level: \"info\", module }),\n debug: (data) => log({ ...data, level: \"debug\", module }),\n };\n };\n\n private log = (data: LoggerArgs, client: Pick<ClientInstance, \"debug\"> = this.client) => {\n if (!client.debug) {\n return;\n }\n // Level is the least severe type of the logs to show - logs of this level and the more severe ones are printed\n if (logLevelOrder.indexOf(this.level) < logLevelOrder.indexOf(data.level)) {\n return;\n }\n if (this.modules && !this.modules.includes(data.module)) {\n return;\n }\n this.logger(data);\n };\n}\n","/* eslint-disable no-console */\nimport type { LoggerType } from \"managers\";\nimport { loggerColors, loggerStyles } from \"managers\";\n\nexport const getTime = () => {\n const d = new Date();\n return `${d.toLocaleTimeString()}`;\n};\n\nconst getModuleName = (data: Parameters<LoggerType>[0]) => {\n if (data.type === \"request\" || data.type === \"response\") {\n return `${data.extra.request.endpoint}`;\n }\n return `[${data.module}]`;\n};\n\n// Logger\nexport const logger: LoggerType = (log) => {\n const styles = loggerStyles[log.level];\n const color = loggerColors[log.level];\n const message = `%c[${getTime()}]%c${log.title}%c${getModuleName(log)}`;\n\n const style1 = `${styles}${color}font-weight:600;border-radius: 4px 0 0 4px;`;\n const style2 = `${styles}${color}font-weight:600;`;\n const style3 = `${styles}font-weight:normal;border-radius: 0 4px 4px 0;`;\n\n if (log.extra ? Object.keys(log.extra)?.length : false) {\n console.groupCollapsed(message, style1, style2, style3);\n console.log(log.extra);\n console.groupEnd();\n } else {\n console.log(message, styles);\n }\n};\n","import type { LogLevel } from \"./logger.manager.types\";\n\nexport const logLevelOrder: LogLevel[] = [\"error\", \"warning\", \"info\", \"debug\"];\n\nconst defaultStyles = \"padding:2px 5px;\";\n\nexport const loggerStyles: Record<LogLevel, string> = {\n error: `${defaultStyles};background:#db252520;`,\n warning: `${defaultStyles};background:#e1941e20;`,\n info: `${defaultStyles};background:#1e74e120;`,\n debug: `${defaultStyles};background:#00000020;`,\n};\n\nexport const loggerColors: Record<LogLevel, string> = {\n error: \"color:#ff3737;\",\n warning: \"color:#ffc107;\",\n info: \"color:#34a8ff;\",\n debug: \"color:#cccccc;\",\n};\n","import type { ResponseType } from \"adapter\";\nimport type { RequestInstance } from \"request\";\nimport type { ExtendRequest, ExtractClientAdapterType } from \"types\";\n\nimport type {\n ClientInstance,\n ClientMode,\n ClientModeOption,\n RequestInterceptorType,\n ResponseInterceptorType,\n} from \"./client.types\";\n\n/**\n * Picks effective {@link ClientMode}: explicit override, else environment detection.\n *\n * Auto mode picks `\"client\"` in runtimes that serve one user: a browser, React Native and every Electron process.\n * Anything else, like Node.js, Deno, Bun or an edge runtime, may serve many users and gets `\"server\"`.\n */\nexport function resolveClientMode(modeOption: ClientModeOption | undefined): ClientMode {\n if (modeOption === \"client\" || modeOption === \"server\") {\n return modeOption;\n }\n\n const inBrowser = typeof window !== \"undefined\" && typeof document !== \"undefined\";\n // React Native has a window but no document, and marks itself on navigator.product\n const inReactNative = typeof navigator !== \"undefined\" && navigator.product === \"ReactNative\";\n // The Electron main process has neither window nor document, but it is one desktop user's app\n const inElectron = typeof process !== \"undefined\" && !!process.versions?.electron;\n\n if (inBrowser || inReactNative || inElectron) {\n return \"client\";\n }\n\n return \"server\";\n}\n\nexport const interceptRequest = async (interceptors: RequestInterceptorType[], request: RequestInstance) => {\n let newRequest = request;\n if (!request.requestOptions.disableRequestInterceptors) {\n // eslint-disable-next-line no-restricted-syntax\n for (const interceptor of interceptors) {\n // Interceptors create a pipeline - each one receives the request returned by the previous one\n // eslint-disable-next-line no-await-in-loop\n newRequest = (await interceptor(newRequest)) as RequestInstance;\n if (!newRequest) {\n throw new Error(\"Request modifier must return request\");\n }\n }\n }\n return newRequest;\n};\n\nexport const interceptResponse = async <GlobalErrorType, Client extends ClientInstance>(\n interceptors: ResponseInterceptorType<Client>[],\n response: ResponseType<any, GlobalErrorType, ExtractClientAdapterType<Client>>,\n request: ExtendRequest<RequestInstance, { client: Client }>,\n) => {\n let newResponse = response;\n if (!request.requestOptions.disableResponseInterceptors) {\n // eslint-disable-next-line no-restricted-syntax\n for (const interceptor of interceptors) {\n // Interceptors create a pipeline - each one receives the response returned by the previous one\n // eslint-disable-next-line no-await-in-loop\n newResponse = await interceptor(newResponse, request);\n if (!newResponse) {\n throw new Error(\"Response modifier must return data\");\n }\n }\n }\n return newResponse;\n};\n","import type { AdapterInstance, ResponseType } from \"adapter\";\nimport { Cache } from \"cache\";\nimport type {\n ClientErrorType,\n ClientInstance,\n ClientMode,\n ClientOptionsType,\n RequestGenericType,\n RequestInterceptorType,\n ResponseInterceptorType,\n} from \"client\";\nimport { Dispatcher } from \"dispatcher\";\nimport type { HttpAdapterType } from \"http-adapter\";\nimport { parseResponse, HttpAdapter } from \"http-adapter\";\nimport type { LogLevel } from \"managers\";\nimport { AppManager, LoggerManager, RequestManager } from \"managers\";\nimport { resetOptimisticState } from \"optimistic\";\nimport type { PluginInstance, PluginMethodParameters, PluginMethods } from \"plugin\";\nimport type {\n ExtractEndpointPayloadType,\n ExtractEndpointResponseType,\n RequestInstance,\n RequestJSON,\n RequestOptionsType,\n} from \"request\";\nimport { getRequestKey, getSimpleKey, Request, scopeKey } from \"request\";\nimport type {\n EmptyTypes,\n TypeWithDefaults,\n ExtractAdapterMethodType,\n ExtractAdapterOptionsType,\n ExtractAdapterQueryParamsType,\n ExtractAdapterEndpointType,\n ExtractUnionAdapter,\n HydrateDataType,\n HydrationOptions,\n ExtractAdapterDefaultQueryParamsType,\n ExtractAdapterRequestOptionsType,\n} from \"types\";\nimport { getUniqueRequestId, throwOutsideLifecycle } from \"utils\";\n\nimport { interceptRequest, interceptResponse, resolveClientMode } from \"./client.utils\";\n\n/**\n * Response interceptors run when the adapter is already done, so nothing else can handle their failure.\n * A throwing or rejecting interceptor ends the request with the error response - the same way as failing request\n * interceptors do - instead of leaving it pending forever.\n */\nconst interceptResponseSafely = async <GlobalErrorType, Adapter extends AdapterInstance>({\n client,\n interceptors,\n response,\n request,\n}: {\n client: Client<any, Adapter>;\n interceptors: ResponseInterceptorType<ClientInstance>[];\n response: ResponseType<any, GlobalErrorType, Adapter>;\n request: RequestInstance;\n}): Promise<ResponseType<any, GlobalErrorType, Adapter>> => {\n try {\n return (await interceptResponse<GlobalErrorType, ClientInstance>(\n interceptors,\n response as ResponseType<any, GlobalErrorType, AdapterInstance>,\n request,\n )) as ResponseType<any, GlobalErrorType, Adapter>;\n } catch (error) {\n const { adapter } = client;\n client.logger.error({ title: \"Response interceptor failed\", type: \"system\", extra: { error, request } });\n\n return {\n data: null,\n error: adapter.unstable_internalErrorMapping(error as Parameters<Adapter[\"unstable_internalErrorMapping\"]>[0]),\n status: adapter.systemErrorStatus,\n success: false,\n extra: adapter.systemErrorExtra,\n requestTimestamp: response.requestTimestamp,\n responseTimestamp: response.responseTimestamp,\n };\n }\n};\n\n/**\n * **Client** is a class that allows you to configure the connection with the server and then use it to create\n * requests. It allows you to set global defaults for the requests configuration, query params configuration.\n * It is also orchestrator for all of the HyperFetch modules like Cache, Dispatcher, AppManager, LoggerManager,\n * RequestManager and more.\n */\nexport class Client<\n GlobalErrorType extends ClientErrorType = Error,\n Adapter extends AdapterInstance = HttpAdapterType,\n> {\n url: string;\n readonly mode: ClientMode;\n public debug: boolean;\n\n // Private\n unstable_onErrorCallbacks: ResponseInterceptorType<ClientInstance>[] = [];\n unstable_onSuccessCallbacks: ResponseInterceptorType<ClientInstance>[] = [];\n unstable_onResponseCallbacks: ResponseInterceptorType<ClientInstance>[] = [];\n unstable_onAuthCallbacks: RequestInterceptorType[] = [];\n unstable_onRequestCallbacks: RequestInterceptorType[] = [];\n\n // Managers\n loggerManager: LoggerManager = new LoggerManager();\n requestManager: RequestManager = new RequestManager();\n appManager: AppManager;\n\n // Config\n adapter: Adapter;\n cache: Cache<Adapter>;\n fetchDispatcher: Dispatcher<Adapter>;\n submitDispatcher: Dispatcher<Adapter>;\n isMockerEnabled = true;\n\n // Registered requests effect\n plugins: PluginInstance[] = [];\n\n /** @internal */\n unstable_abortKeyMapper: (request: RequestInstance) => string = getSimpleKey;\n\n /** @internal */\n unstable_cacheKeyMapper: (request: RequestInstance) => string = getRequestKey;\n\n /** @internal */\n unstable_queryKeyMapper: (request: RequestInstance) => string = getRequestKey;\n\n /** @internal */\n unstable_requestIdMapper: (request: RequestInstance) => string = getUniqueRequestId;\n\n // Logger\n logger = this.loggerManager.initialize(this, \"Client\");\n\n constructor(public options: ClientOptionsType<Client<GlobalErrorType, Adapter>>) {\n const { url, appManager, cache, fetchDispatcher, submitDispatcher, mode: modeOption } = this.options;\n this.url = url;\n this.mode = resolveClientMode(modeOption);\n this.adapter = HttpAdapter() as Adapter;\n\n this.appManager = appManager?.() || new AppManager();\n this.cache = cache?.() || new Cache();\n this.fetchDispatcher = fetchDispatcher?.() || new Dispatcher();\n this.submitDispatcher = submitDispatcher?.() || new Dispatcher();\n\n // IMPORTANT: Do not change initialization order as it's crucial for dependencies injection\n this.adapter.initialize(this);\n this.appManager.initialize();\n this.cache.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n this.fetchDispatcher.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n this.submitDispatcher.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n }\n\n /**\n * Set the base url used by the next requests - e.g. when switching tenants, regions or environments at runtime.\n * Cache keys don't include the base url, so data cached for the previous url stays in place unless you pass\n * `invalidate: true`. Pass `abort: true` to cancel the requests that are still in progress for the previous url.\n * @param url new base url\n * @param options.abort abort all ongoing requests\n * @param options.invalidate invalidate the cache (and requests aborted by `abort`), so active consumers refetch\n */\n setUrl = (url: string, options: { abort?: boolean; invalidate?: boolean } = {}): Client<GlobalErrorType, Adapter> => {\n if (url === this.url) {\n return this;\n }\n\n const { abort = false, invalidate = false } = options;\n const runningRequests = this.fetchDispatcher.getAllRunningRequests().map(({ request }) => request);\n\n this.url = url;\n\n if (abort) {\n this.requestManager.abortAll();\n }\n if (invalidate) {\n this.cache.invalidate();\n // Aborted requests never land in the cache, so the full invalidation above would not notify their consumers\n if (abort && runningRequests.length > 0) {\n this.cache.invalidate(runningRequests);\n }\n }\n\n return this;\n };\n\n /**\n * This method enables the logger usage and display the logs in console\n */\n setDebug = (enabled: boolean): Client<GlobalErrorType, Adapter> => {\n this.debug = enabled;\n return this;\n };\n\n /**\n * Set the logger severity of the messages displayed to the console\n */\n setLogLevel = (severity: LogLevel): Client<GlobalErrorType, Adapter> => {\n this.loggerManager.setSeverity(severity);\n return this;\n };\n\n /**\n * Set the new logger instance to the Client\n */\n setLogger = (callback: (Client: ClientInstance) => LoggerManager): Client<GlobalErrorType, Adapter> => {\n this.loggerManager = callback(this);\n this.logger = this.loggerManager.initialize(this, \"Client\");\n return this;\n };\n\n /**\n * Set globally if mocking should be enabled or disabled for all client requests.\n * @param isMockerEnabled\n */\n setEnableGlobalMocking = (isMockerEnabled: boolean) => {\n this.isMockerEnabled = isMockerEnabled;\n return this;\n };\n\n /**\n * Set custom http adapter to handle graphql, rest, firebase or others\n */\n setAdapter = <NewAdapter extends AdapterInstance>(adapter: NewAdapter): Client<GlobalErrorType, NewAdapter> => {\n this.adapter = adapter as unknown as Adapter;\n this.adapter.initialize(this);\n return this as unknown as Client<GlobalErrorType, NewAdapter>;\n };\n\n /**\n * Method of manipulating requests before sending the request. We can for example add custom header with token to the request which request had the auth set to true.\n */\n onAuth = (callback: RequestInterceptorType): Client<GlobalErrorType, Adapter> => {\n this.unstable_onAuthCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing listeners on auth.\n * */\n removeOnAuthInterceptors = (callbacks: RequestInterceptorType[]): Client<GlobalErrorType, Adapter> => {\n this.unstable_onAuthCallbacks = this.unstable_onAuthCallbacks.filter((callback) => !callbacks.includes(callback));\n return this;\n };\n\n /**\n * Method for intercepting error responses. It can be used for example to refresh tokens.\n */\n onError = <ErrorType = null>(\n callback: ResponseInterceptorType<ClientInstance, any, ErrorType | GlobalErrorType>,\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onErrorCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing listeners on error.\n * */\n removeOnErrorInterceptors = (\n callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[],\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onErrorCallbacks = this.unstable_onErrorCallbacks.filter((callback) => !callbacks.includes(callback));\n return this;\n };\n\n /**\n * Method for intercepting success responses.\n */\n onSuccess = <ErrorType = null>(\n callback: ResponseInterceptorType<ClientInstance, any, ErrorType | GlobalErrorType>,\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onSuccessCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing listeners on success.\n * */\n removeOnSuccessInterceptors = (\n callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[],\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onSuccessCallbacks = this.unstable_onSuccessCallbacks.filter(\n (callback) => !callbacks.includes(callback),\n );\n return this;\n };\n\n /**\n * Method of manipulating requests before sending the request.\n */\n onRequest = (callback: RequestInterceptorType): Client<GlobalErrorType, Adapter> => {\n this.unstable_onRequestCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing listeners on request.\n * */\n removeOnRequestInterceptors = (callbacks: RequestInterceptorType[]): Client<GlobalErrorType, Adapter> => {\n this.unstable_onRequestCallbacks = this.unstable_onRequestCallbacks.filter(\n (callback) => !callbacks.includes(callback),\n );\n return this;\n };\n\n /**\n * Method for intercepting any responses.\n */\n onResponse = <ErrorType = null>(\n callback: ResponseInterceptorType<ClientInstance, any, ErrorType | GlobalErrorType>,\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onResponseCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing response interceptors.\n * */\n removeOnResponseInterceptors = (\n callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[],\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onResponseCallbacks = this.unstable_onResponseCallbacks.filter(\n (callback) => !callbacks.includes(callback),\n );\n return this;\n };\n\n /**\n * Add persistent plugins which trigger on the request lifecycle\n */\n addPlugin = (plugin: PluginInstance) => {\n this.plugins.push(plugin);\n\n plugin.initialize(this);\n plugin.trigger(\"onMount\", { client: this });\n\n return this;\n };\n\n /**\n * Remove plugins from Client\n */\n removePlugin = (plugin: PluginInstance) => {\n const pluginCount = this.plugins.length;\n this.plugins = this.plugins.filter((p) => p !== plugin);\n\n if (this.plugins.length !== pluginCount) {\n plugin.trigger(\"onUnmount\", { client: this });\n }\n\n return this;\n };\n\n triggerPlugins = <Key extends keyof PluginMethods<Client>>(key: Key, data: PluginMethodParameters<Key, Client>) => {\n if (this.plugins.length === 0) {\n return this;\n }\n\n this.plugins.forEach((plugin) => {\n try {\n plugin.trigger(key, data);\n } catch (error) {\n // Plugins only observe the lifecycle - a failing one can't break the requests, the cache or other plugins\n this.logger.error({\n title: `Plugin \"${plugin.name}\" failed`,\n type: \"system\",\n extra: { plugin: plugin.name, method: key, error },\n });\n throwOutsideLifecycle(error);\n }\n });\n\n return this;\n };\n\n /**\n * Key setters\n */\n\n /** Set a custom mapper that generates the abort key used to cancel in-flight requests. */\n setAbortKeyMapper = (callback: (request: RequestInstance) => string) => {\n this.unstable_abortKeyMapper = callback;\n return this;\n };\n /** Set a custom mapper that generates the cache key used to store and retrieve cached responses. */\n setCacheKeyMapper = (callback: (request: RequestInstance) => string) => {\n this.unstable_cacheKeyMapper = callback;\n return this;\n };\n /** Set a custom mapper that generates the query key used to identify requests in the dispatcher queue. */\n setQueryKeyMapper = (callback: (request: RequestInstance) => string) => {\n this.unstable_queryKeyMapper = callback;\n return this;\n };\n /** Set a custom mapper that generates the unique request ID for deduplication and tracking. */\n setRequestIdMapper = (callback: (request: RequestInstance) => string) => {\n this.unstable_requestIdMapper = callback;\n return this;\n };\n\n /**\n * Helper used by http adapter to apply the modifications on response error\n * @private\n */\n unstable_modifyAuth = async (request: RequestInstance) => interceptRequest(this.unstable_onAuthCallbacks, request);\n\n /**\n * Private helper to run async pre-request processing\n * @private\n */\n unstable_modifyRequest = async (request: RequestInstance) =>\n interceptRequest(this.unstable_onRequestCallbacks, request);\n\n /**\n * Private helper to run async on-error response processing\n * @private\n */\n unstable_modifyErrorResponse = async (\n response: ResponseType<any, GlobalErrorType, Adapter>,\n request: RequestInstance,\n ) =>\n interceptResponseSafely<GlobalErrorType, Adapter>({\n client: this,\n interceptors: this.unstable_onErrorCallbacks,\n response,\n request,\n });\n\n /**\n * Private helper to run async on-success response processing\n * @private\n */\n unstable_modifySuccessResponse = async (\n response: ResponseType<any, GlobalErrorType, Adapter>,\n request: RequestInstance,\n ) =>\n interceptResponseSafely<GlobalErrorType, Adapter>({\n client: this,\n interceptors: this.unstable_onSuccessCallbacks,\n response,\n request,\n });\n\n /**\n * Private helper to run async response processing\n * @private\n */\n unstable_modifyResponse = async (response: ResponseType<any, GlobalErrorType, Adapter>, request: RequestInstance) =>\n interceptResponseSafely<GlobalErrorType, Adapter>({\n client: this,\n interceptors: this.unstable_onResponseCallbacks,\n response,\n request,\n });\n\n /**\n * Reconstruct a Request class instance from its serialized JSON form.\n * Useful when dispatcher storage serializes queue data (e.g. MMKV, AsyncStorage)\n * and the deserialized request loses its class identity.\n */\n fromJSON = <RequestProperties extends RequestGenericType<ExtractAdapterQueryParamsType<Adapter>> = {}>(\n json: RequestJSON<RequestInstance>,\n ) => {\n type DefaultQueryParams = ExtractAdapterDefaultQueryParamsType<Adapter>;\n\n type Response = TypeWithDefaults<RequestProperties, \"response\", undefined>;\n type Payload = TypeWithDefaults<RequestProperties, \"payload\", undefined>;\n type LocalError = TypeWithDefaults<RequestProperties, \"error\", GlobalErrorType>;\n type QueryParams = TypeWithDefaults<RequestProperties, \"queryParams\", DefaultQueryParams, never>;\n type Endpoint = TypeWithDefaults<RequestProperties, \"endpoint\", string>;\n\n return Request.fromJSON(this as unknown as ClientInstance, json) as unknown as Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint extends string ? Endpoint : string,\n Client<GlobalErrorType, Adapter>\n >;\n };\n\n /**\n * Clears the Client instance and remove all listeners on it's dependencies\n */\n clear = () => {\n const { appManager, cache, fetchDispatcher, submitDispatcher } = this.options;\n\n // Queued and ongoing requests are removed while their listeners still exist - it aborts the ongoing ones\n // and resolves the pending `send()` promises, which otherwise would never settle\n [this.fetchDispatcher, this.submitDispatcher].forEach((dispatcher) => {\n dispatcher.getQueuesKeys().forEach((queryKey) => {\n dispatcher.getQueue(queryKey).requests.forEach(({ request, requestId }) => {\n dispatcher.delete(queryKey, requestId, scopeKey(request.abortKey, request.scope));\n });\n });\n });\n // Requests sent outside of the dispatchers\n this.requestManager.abortAll();\n\n this.requestManager.abortControllers.clear();\n resetOptimisticState(this);\n this.fetchDispatcher.clear();\n this.submitDispatcher.clear();\n this.cache.clear();\n\n this.requestManager.emitter.removeAllListeners();\n this.fetchDispatcher.emitter.removeAllListeners();\n this.submitDispatcher.emitter.removeAllListeners();\n this.cache.emitter.removeAllListeners();\n this.appManager.unmount();\n // App manager can be shared between the clears, so the listeners of the removed modules have to go away\n this.appManager.emitter.removeAllListeners();\n\n this.cache = cache?.() || new Cache();\n this.appManager = appManager?.() || new AppManager();\n this.fetchDispatcher = fetchDispatcher?.() || new Dispatcher();\n this.submitDispatcher = submitDispatcher?.() || new Dispatcher();\n\n // DO NOT CHANGE INITIALIZATION ORDER\n this.appManager.initialize();\n this.cache.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n this.fetchDispatcher.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n this.submitDispatcher.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n };\n\n /**\n * Hydrate your SSR cache data\n * @param hydrationData\n * @param options\n */\n hydrate = (\n hydrationData: (HydrateDataType | EmptyTypes)[],\n options?: Partial<HydrationOptions> | ((item: HydrateDataType) => Partial<HydrationOptions>),\n ) => {\n hydrationData?.forEach((item) => {\n if (!item) {\n return;\n }\n\n const { cacheKey, scope, response, ...fallbackOptions } = item;\n const defaults = {\n cache: true,\n override: true,\n } satisfies Partial<HydrationOptions>;\n const config =\n typeof options === \"function\"\n ? { ...defaults, ...fallbackOptions, ...options(item) }\n : { ...defaults, ...fallbackOptions, ...options };\n\n if (!config.override) {\n const cachedData = this.cache.get(scopeKey(cacheKey, scope));\n if (cachedData) {\n return;\n }\n }\n\n const parsedData = parseResponse(response);\n this.cache.set(\n { ...config, cacheKey, scope },\n {\n // Hydrated responses did not go through the dispatcher, so the request details get their neutral values\n retries: 0,\n isCanceled: false,\n isOffline: false,\n willRetry: false,\n addedTimestamp: parsedData?.requestTimestamp,\n triggerTimestamp: parsedData?.requestTimestamp,\n ...parsedData,\n hydrated: true,\n },\n );\n });\n };\n\n /**\n * Create requests based on the Client setup\n *\n * @template Response Your response\n */\n createRequest = <RequestProperties extends RequestGenericType<ExtractAdapterQueryParamsType<Adapter>> = {}>(\n /**\n * `createRequest` must be initialized twice(currying).\n *\n * ✅ Good:\n * ```ts\n * const request = createRequest<RequestProperties>()(params)\n * ```\n * ⛔ Bad:\n * ```ts\n * const request = createRequest<RequestProperties>(params)\n * ```\n *\n * We are using currying to achieve auto generated types for the endpoint string.\n *\n * This solution will be removed once https://github.com/microsoft/TypeScript/issues/10571 get resolved.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _USE_DOUBLE_INITIALIZATION?: never,\n ) => {\n type DefaultQueryParams = ExtractAdapterDefaultQueryParamsType<Adapter>;\n\n type LocalError = TypeWithDefaults<RequestProperties, \"error\", GlobalErrorType>;\n /** we pass never to prevent the type from being empty, but we allow it to be undefined (optional) */\n type QueryParams = TypeWithDefaults<RequestProperties, \"queryParams\", DefaultQueryParams, never>;\n\n return <\n EndpointType extends ExtractAdapterEndpointType<Adapter>,\n AdapterOptions extends ExtractAdapterOptionsType<Adapter>,\n MethodType extends ExtractAdapterMethodType<Adapter>,\n >(\n params: RequestOptionsType<EndpointType, AdapterOptions, MethodType> & ExtractAdapterRequestOptionsType<Adapter>,\n ) => {\n type Endpoint = TypeWithDefaults<RequestProperties, \"endpoint\", EndpointType>;\n // A typed endpoint (like a TypedDocumentNode) fills the response and the payload the generics leave out\n type Response = TypeWithDefaults<RequestProperties, \"response\", ExtractEndpointResponseType<EndpointType>>;\n type Payload = TypeWithDefaults<RequestProperties, \"payload\", ExtractEndpointPayloadType<EndpointType>>;\n\n const endpoint = this.adapter.unstable_endpointMapper(params.endpoint);\n\n // Splitting this type prevents \"Type instantiation is excessively deep and possibly infinite\" error\n type ExtractedAdapter = ExtractUnionAdapter<\n Adapter,\n {\n method: MethodType;\n options: AdapterOptions;\n queryParams: QueryParams;\n }\n >;\n type ExtractedAdapterType = ExtractedAdapter extends EmptyTypes ? Adapter : ExtractedAdapter;\n\n const mappedParams: RequestOptionsType<\n Endpoint extends string ? Endpoint : typeof endpoint,\n AdapterOptions,\n MethodType\n > = {\n ...params,\n endpoint: String(endpoint) as Endpoint extends string ? Endpoint : typeof endpoint,\n };\n\n const request = new Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint extends string ? Endpoint : typeof endpoint,\n Client<GlobalErrorType, ExtractedAdapterType>\n >(this as unknown as Client<GlobalErrorType, ExtractedAdapterType>, mappedParams);\n\n this.plugins.forEach((plugin) => plugin.trigger(\"onRequestCreate\", { request }));\n\n return request;\n };\n };\n}\n","export const stringifyDefaultOptions = {\n strict: true,\n encode: true,\n arrayFormat: \"bracket\",\n arraySeparator: \"|\",\n sort: false,\n skipNull: true,\n skipEmptyString: true,\n} as const;\n","import type { ClientErrorType, ClientOptionsType } from \"client\";\nimport { Client } from \"client\";\nimport type { HttpAdapterType } from \"http-adapter\";\nimport type { TypeWithDefaults } from \"types\";\n\nexport type ClientGenericType = {\n error?: ClientErrorType;\n};\n\nexport function createClient<ClientProperties extends ClientGenericType = {}>(\n options: ClientOptionsType<Client<NonNullable<TypeWithDefaults<ClientProperties, \"error\", Error>>>>,\n): Client<NonNullable<TypeWithDefaults<ClientProperties, \"error\", Error>>, HttpAdapterType> {\n return new Client<NonNullable<TypeWithDefaults<ClientProperties, \"error\", Error>>, HttpAdapterType>(options);\n}\n","import type { ClientInstance } from \"client\";\nimport type { RequestInstance, RetryTimeType } from \"request\";\nimport { Request } from \"request\";\nimport type {\n ExtractEndpointType,\n ExtractResponseType,\n ExtractPayloadType,\n ExtractQueryParamsType,\n ExtractLocalErrorType,\n ExtractHasPayloadType,\n ExtractHasParamsType,\n ExtractHasQueryParamsType,\n ExtractMutationContextType,\n} from \"types\";\n\nexport type RecursiveSchemaType = Record<\n string, // for example users / $userId / posts / $postId\n any\n>;\n\n/**\n * Recursively walks a schema and rebuilds every `Request` leaf with the SDK's actual client\n * type injected into the `Client` generic slot. Lets users omit `client` from their\n * `RequestModel<{...}>` declarations - the SDK fills it in from the client passed to\n * `createSdk(client)`.\n *\n * Non-Request leaves (primitive values, plain types) are passed through unchanged. Nested\n * schema objects are recursed into. Depth is guarded at 10 levels to keep the type checker\n * within reasonable bounds.\n */\n/**\n * Keys every request has at runtime - its public properties and the private ones. Below the top level, the SDK reads\n * such a key from the request instead of treating it as a path segment or procedure name.\n */\ntype SdkReservedKey = keyof RequestInstance | \"updatedAbortKey\" | \"updatedCacheKey\" | \"updatedQueryKey\" | \"paramsMapper\";\n\n/**\n * Type of a schema key the SDK can't reach, because every request has a property with the same name - for example a\n * procedure called `send`. Using it fails to compile instead of crashing at runtime. Rename the key, or set the path\n * with a `$`-prefixed key.\n */\nexport type SdkReservedKeyError<Key extends PropertyKey> = {\n __sdkError: `\"${Key & string}\" is a property of every request, so the SDK can't reach a path or procedure with this name. Rename it in the schema.`;\n};\n\nexport type InjectClient<T, TClient extends ClientInstance, Depth extends unknown[] = []> = Depth[\"length\"] extends 10\n ? T\n : T extends RequestInstance\n ? Request<\n ExtractResponseType<T>,\n ExtractPayloadType<T>,\n ExtractQueryParamsType<T>,\n ExtractLocalErrorType<T>,\n ExtractEndpointType<T> extends string ? ExtractEndpointType<T> : string,\n TClient,\n ExtractHasPayloadType<T> extends boolean ? ExtractHasPayloadType<T> : false,\n ExtractHasParamsType<T> extends boolean ? ExtractHasParamsType<T> : false,\n ExtractHasQueryParamsType<T> extends boolean ? ExtractHasQueryParamsType<T> : false,\n ExtractMutationContextType<T>\n >\n : T extends Record<string, any>\n ? {\n // The top level is not a request, so only the nested keys can clash with the request properties\n [K in keyof T]: Depth[\"length\"] extends 0\n ? InjectClient<T[K], TClient, [...Depth, unknown]>\n : K extends SdkReservedKey\n ? SdkReservedKeyError<K>\n : InjectClient<T[K], TClient, [...Depth, unknown]>;\n }\n : T;\n\n/**\n * Per-request defaults that can be applied via SDK configuration.\n * These mirror the chainable setters on Request (headers, cache, retry, etc.).\n */\nexport type SdkRequestDefaults = {\n headers?: HeadersInit;\n auth?: boolean;\n cache?: boolean;\n cacheTime?: number;\n staleTime?: number;\n retry?: number;\n retryTime?: RetryTimeType;\n cancelable?: boolean;\n queued?: boolean;\n offline?: boolean;\n deduplicate?: boolean;\n deduplicateTime?: number | null;\n structuralSharing?: boolean;\n throwOnError?: boolean;\n};\n\n/**\n * Configuration value: either a static property bag or a function that receives\n * the request and returns a modified request (full access to every Request setter).\n */\nexport type SdkConfigurationValue = SdkRequestDefaults | ((request: RequestInstance) => RequestInstance);\n\n/**\n * Recursively extracts all endpoint strings from an SDK schema type.\n * Leaf nodes (keys starting with $) are RequestInstance — extract endpoint from those.\n * Other keys are nested schema segments to recurse into.\n */\ntype ExtractSdkEndpoints<T, Depth extends unknown[] = []> = Depth[\"length\"] extends 10\n ? never\n : {\n [K in keyof T]: K extends `$${string}`\n ? T[K] extends RequestInstance\n ? ExtractEndpointType<T[K]>\n : never\n : T[K] extends Record<string, any>\n ? ExtractSdkEndpoints<T[K], [...Depth, unknown]>\n : never;\n }[keyof T];\n\n/**\n * Recursively extracts dot-path accessor keys from an SDK schema.\n * These mirror the SDK property chain: \"users.$get\", \"users.$userId.$get\", etc.\n */\ntype ExtractSdkPaths<T, Prefix extends string = \"\", Depth extends unknown[] = []> = Depth[\"length\"] extends 10\n ? never\n : {\n [K in keyof T & string]: T[K] extends RequestInstance\n ? `${Prefix}${K}`\n : T[K] extends Record<string, any>\n ? ExtractSdkPaths<T[K], `${Prefix}${K}.`, [...Depth, unknown]>\n : never;\n }[keyof T & string];\n\n/**\n * Builds the set of valid configuration keys from an SDK schema:\n * - \"*\" (global wildcard)\n * - exact endpoint paths extracted from RequestInstance nodes (group keys)\n * - wildcard patterns like \"/users/*\" (group keys)\n * - dot-path accessor keys like \"users.$get\" (method-specific keys)\n */\ntype SdkConfigurationKeys<Schema extends RecursiveSchemaType> =\n | \"*\"\n | ExtractSdkEndpoints<Schema>\n | `${ExtractSdkEndpoints<Schema> & string}/*`\n | ExtractSdkPaths<Schema>;\n\n/**\n * Maps endpoint paths, wildcard patterns, or dot-path accessor keys to request defaults.\n * Keys are validated against the SDK schema.\n *\n * Values can be:\n * - A plain `SdkRequestDefaults` object (shorthand for common settings)\n * - A function `(request) => request` for full access to every Request setter\n */\nexport type SdkConfigurationMap<Schema extends RecursiveSchemaType = RecursiveSchemaType> = Partial<\n Record<SdkConfigurationKeys<Schema>, SdkConfigurationValue>\n>;\n\nexport type CreateSdkOptions<Schema extends RecursiveSchemaType = RecursiveSchemaType> = {\n /** @default true */\n camelCaseToKebabCase?: boolean;\n /**\n * URL segment of a schema key, when it differs from the key - for example `{ findByStatus: \"findByStatus\" }` keeps\n * the camelCase segment that `camelCaseToKebabCase` would turn into `find-by-status`. Mapped keys are not converted.\n * SDKs generated by the CLI fill it from the paths of the API schema.\n */\n pathSegments?: Record<string, string>;\n /** @default (method) => method.toUpperCase() */\n methodTransform?: (method: string) => string;\n /** Per-endpoint request defaults */\n defaults?: SdkConfigurationMap<Schema>;\n};\n\nconst OPTIONAL_REQUEST_FIELDS = Request.OPTIONAL_FIELDS;\n\nconst getMethod = (key: string, options?: CreateSdkOptions<any>) => {\n const { methodTransform = (method: string) => method.toUpperCase() } = options ?? {};\n return methodTransform(key);\n};\n\nconst endpointMatchesPattern = (endpoint: string, pattern: string): boolean => {\n if (pattern === \"*\") {return true;}\n if (pattern === endpoint) {return true;}\n // Simple wildcard: \"/users/*\" matches \"/users/:userId\", \"/users/:userId/posts\", etc.\n if (pattern.endsWith(\"/*\")) {\n const prefix = pattern.slice(0, -1);\n return endpoint.startsWith(prefix) || endpoint === prefix.slice(0, -1);\n }\n return false;\n};\n\nconst isDotPath = (key: string): boolean => {\n return key.includes(\".\") && !key.startsWith(\"/\");\n};\n\nconst applyObjectDefaults = (request: RequestInstance, config: SdkRequestDefaults): RequestInstance => {\n let result = request;\n if (config.headers) {result = result.setHeaders(config.headers);}\n if (config.auth !== undefined) {result = result.setAuth(config.auth);}\n if (config.cache !== undefined) {result = result.setCache(config.cache);}\n if (config.cacheTime !== undefined) {result = result.setCacheTime(config.cacheTime);}\n if (config.staleTime !== undefined) {result = result.setStaleTime(config.staleTime);}\n if (config.retry !== undefined) {result = result.setRetry(config.retry);}\n if (config.retryTime !== undefined) {result = result.setRetryTime(config.retryTime);}\n if (config.cancelable !== undefined) {result = result.setCancelable(config.cancelable);}\n if (config.queued !== undefined) {result = result.setQueued(config.queued);}\n if (config.offline !== undefined) {result = result.setOffline(config.offline);}\n if (config.deduplicate !== undefined) {result = result.setDeduplicate(config.deduplicate);}\n if (config.deduplicateTime !== undefined && config.deduplicateTime !== null) {\n result = result.setDeduplicateTime(config.deduplicateTime);\n }\n if (config.structuralSharing !== undefined) {\n result = result.setStructuralSharing(config.structuralSharing);\n }\n if (config.throwOnError !== undefined) {\n result = result.setThrowOnError(config.throwOnError);\n }\n return result;\n};\n\nconst applyDefaults = (\n request: RequestInstance,\n context: { endpoint: string; sdkPath: string; defaults?: Partial<Record<string, SdkConfigurationValue>> },\n): RequestInstance => {\n const { endpoint, sdkPath, defaults } = context;\n if (!defaults) {return request;}\n\n let result = request;\n const entries = Object.entries(defaults);\n\n // Sort: \"*\" first, then endpoint groups (start with \"/\"), then dot-path (method-specific) last\n const globalEntries: [string, SdkConfigurationValue][] = [];\n const groupEntries: [string, SdkConfigurationValue][] = [];\n const pathEntries: [string, SdkConfigurationValue][] = [];\n\n for (let i = 0; i < entries.length; i += 1) {\n const [key, value] = entries[i];\n if (!value) {continue;}\n const entry: [string, SdkConfigurationValue] = [key, value];\n if (entry[0] === \"*\") {\n globalEntries.push(entry);\n } else if (isDotPath(entry[0])) {\n pathEntries.push(entry);\n } else {\n groupEntries.push(entry);\n }\n }\n\n const sorted = [...globalEntries, ...groupEntries, ...pathEntries];\n\n for (let i = 0; i < sorted.length; i += 1) {\n const [pattern, config] = sorted[i];\n\n let matches = false;\n if (isDotPath(pattern)) {\n matches = pattern === sdkPath;\n } else {\n matches = endpointMatchesPattern(endpoint, pattern);\n }\n\n if (matches) {\n if (typeof config === \"function\") {\n result = config(result);\n } else {\n result = applyObjectDefaults(result, config);\n }\n }\n }\n\n return result;\n};\n\nconst createRecursiveProxy = (\n client: ClientInstance,\n context: { path: string[]; sdkKeys: string[]; options?: CreateSdkOptions<any> },\n): any => {\n const { path, sdkKeys, options } = context;\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n return new Proxy(() => {}, {\n get: (_target, key: string) => {\n if (typeof key === \"symbol\" || key === \"inspect\") {\n return;\n }\n\n // Check if this is a method (starts with $) or a path segment\n let isMethod = false;\n let methodName = key;\n let pathSegment = key;\n\n if (key.startsWith(\"$\")) {\n isMethod = true;\n methodName = key.slice(1);\n pathSegment = `:${key.slice(1)}`;\n } else if (options?.pathSegments && Object.prototype.hasOwnProperty.call(options.pathSegments, key)) {\n pathSegment = options.pathSegments[key];\n } else if (options?.camelCaseToKebabCase) {\n pathSegment = key.replaceAll(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n }\n\n // Build the sdk dot-path for method-specific configuration matching\n const currentSdkKeys = [...sdkKeys, key];\n const sdkPath = currentSdkKeys.join(\".\");\n\n // Always create a request assuming this is a method call\n const endpoint = `/${path.join(\"/\")}`;\n const method = getMethod(isMethod ? methodName : key, options);\n let request: RequestInstance = client.createRequest()({ endpoint, method });\n request = applyDefaults(request, { endpoint, sdkPath, defaults: options?.defaults });\n\n // But also, assume the key is a new path segment for a deeper call\n const newPath = [...path, pathSegment];\n const deeperProxy = createRecursiveProxy(client, { path: newPath, sdkKeys: currentSdkKeys, options });\n\n // Return a new proxy that wraps both the request and the deeper proxy\n return new Proxy(request, {\n get: (reqTarget, reqKey: string) => {\n // If the property exists on the request instance (like .send(), .setParams()), return it.\n // Optional fields are checked by name as well: transpilers that compile class\n // properties in loose mode (Metro on React Native) drop uninitialized field\n // declarations, and falling through to the deeper proxy would hand callers a\n // truthy path proxy where they expect undefined.\n if (reqKey in reqTarget || (OPTIONAL_REQUEST_FIELDS as readonly string[]).includes(reqKey)) {\n return reqTarget[reqKey as keyof typeof reqTarget];\n }\n // Otherwise, it's a deeper path, so delegate to the deeper proxy.\n return deeperProxy[reqKey];\n },\n });\n },\n });\n};\n\n/**\n * The fully-resolved SDK instance type returned by `createSdk`.\n *\n * The schema is rewritten via {@link InjectClient} so every `Request` leaf carries the\n * actual client type passed to `createSdk(client)` - users do not need to repeat\n * `client: AppClient` in every `RequestModel<{...}>` declaration.\n */\nexport type SdkInstance<\n Schema extends RecursiveSchemaType,\n TClient extends ClientInstance = ClientInstance,\n> = InjectClient<Schema, TClient> & {\n /**\n * Apply request defaults to the SDK. Returns a new SDK instance with the configuration applied.\n * Use \"*\" to match all endpoints, or specific endpoint strings / wildcard patterns.\n */\n $configure: (defaults: SdkConfigurationMap<Schema>) => SdkInstance<Schema, TClient>;\n};\n\nexport const createSdk = <Client extends ClientInstance, RecursiveSchema extends RecursiveSchemaType>(\n client: Client,\n options?: CreateSdkOptions<RecursiveSchema>,\n): SdkInstance<RecursiveSchema, Client> => {\n const {\n camelCaseToKebabCase = true,\n methodTransform = (method: string) => method.toUpperCase(),\n ...rest\n } = options ?? {};\n\n const mergedOptions: CreateSdkOptions<RecursiveSchema> = { camelCaseToKebabCase, methodTransform, ...rest };\n // Break inference for TypeDoc / tsserver (TS2589) — runtime value is unchanged.\n const proxy = createRecursiveProxy(client, { path: [], sdkKeys: [], options: mergedOptions as never });\n\n return new Proxy(proxy, {\n get: (target, key: string) => {\n if (key === \"$configure\") {\n return (defaults: SdkConfigurationMap<RecursiveSchema>) => {\n const existingDefaults = mergedOptions.defaults || {};\n return createSdk<Client, RecursiveSchema>(client, {\n ...mergedOptions,\n defaults: { ...existingDefaults, ...defaults } as SdkConfigurationMap<RecursiveSchema>,\n });\n };\n }\n return target[key];\n },\n }) as SdkInstance<RecursiveSchema, Client>;\n};\n\n/**\n * Type-safe factory for creating SDK configuration maps.\n *\n * @example\n * const config = createConfiguration<MySdkSchema>()({ \"*\": { retry: 3 } })\n */\nexport const createConfiguration = <Schema extends RecursiveSchemaType>() => {\n return (defaults: SdkConfigurationMap<Schema>): SdkConfigurationMap<Schema> => defaults;\n};\n","import type { RequestInstance } from \"request\";\nimport { stringifyKey } from \"request/request.utils\";\n\nimport type { CachedInfinitePage, PaginationConfig, PaginationMode, PaginationPageContext } from \"./infinite.types\";\n\nconst isEmptyCursor = (value: unknown) => value === null || value === undefined || value === \"\";\n\nconst toNumber = (value: unknown): number | undefined => {\n if (value === null || value === undefined || value === \"\") {\n return undefined;\n }\n const number = Number(value);\n return Number.isFinite(number) ? number : undefined;\n};\n\n/**\n * Tells how the list is paged. Throws for a missing or incomplete pagination, because a list without it\n * would silently fetch the same page forever.\n */\nexport const getPaginationMode = (pagination: PaginationConfig): PaginationMode => {\n if (pagination?.cursor) {\n if (!pagination.next) {\n throw new Error('Cursor pagination requires the \"next\" option');\n }\n return \"cursor\";\n }\n if (pagination?.offset) {\n return \"offset\";\n }\n if (pagination?.page) {\n return \"page\";\n }\n throw new Error('Infinite requests require the \"pagination\" option with a \"page\", \"offset\" or \"cursor\" field');\n};\n\nconst getPagingField = (pagination: PaginationConfig) => {\n return (pagination.cursor ?? pagination.offset ?? pagination.page) as string;\n};\n\nconst getSourceValues = (request: RequestInstance, pagination: PaginationConfig): Record<string, unknown> => {\n const values = request[pagination.in ?? \"queryParams\"];\n return values && typeof values === \"object\" ? (values as Record<string, unknown>) : {};\n};\n\nconst getPageLimit = (request: RequestInstance, pagination: PaginationConfig) => {\n if (!pagination.limit) {\n return;\n }\n const limit = toNumber(getSourceValues(request, pagination)[pagination.limit]);\n return limit && limit > 0 ? limit : undefined;\n};\n\n/**\n * The value the list starts from: what the request already holds, otherwise the first page.\n */\nexport const getInitialPageParam = (request: RequestInstance, pagination: PaginationConfig): unknown => {\n const mode = getPaginationMode(pagination);\n const value = getSourceValues(request, pagination)[getPagingField(pagination)];\n\n if (mode === \"cursor\") {\n return isEmptyCursor(value) ? undefined : value;\n }\n return toNumber(value) ?? (mode === \"page\" ? 1 : 0);\n};\n\n// Lists numbered from zero say so by starting at zero, any other start means numbering from one\nconst getFirstPageNumber = (request: RequestInstance, pagination: PaginationConfig) => {\n return getInitialPageParam(request, pagination) === 0 ? 0 : 1;\n};\n\nconst setPagingValue = (request: RequestInstance, pagination: PaginationConfig, value: unknown): RequestInstance => {\n const values = { ...getSourceValues(request, pagination), [getPagingField(pagination)]: value };\n\n switch (pagination.in) {\n case \"params\": {\n return request.setParams(values as any) as RequestInstance;\n }\n case \"payload\": {\n return request.setPayload(values as any) as RequestInstance;\n }\n default: {\n return request.setQueryParams(values as any) as RequestInstance;\n }\n }\n};\n\nconst keyDependencies = new WeakMap<RequestInstance, { cacheKey: boolean; queryKey: boolean }>();\n\n/**\n * Generated keys contain the query params, so usually every page has its own. A custom key, or paging inside\n * the payload, gives all the pages the same key - they would overwrite each other in one cache slot.\n */\nconst getKeyDependencies = (request: RequestInstance, pagination: PaginationConfig) => {\n let dependencies = keyDependencies.get(request);\n if (!dependencies) {\n const first = setPagingValue(request, pagination, \"__hyper_fetch_page_a__\");\n const second = setPagingValue(request, pagination, \"__hyper_fetch_page_b__\");\n dependencies = {\n cacheKey: first.cacheKey !== second.cacheKey,\n queryKey: first.queryKey !== second.queryKey,\n };\n keyDependencies.set(request, dependencies);\n }\n return dependencies;\n};\n\n/**\n * Creates the request of a single page. Generated keys are left untouched, so a page shares its cache\n * with any other request for the same data.\n */\nexport const getPageRequest = <R extends RequestInstance>(\n request: R,\n pagination: PaginationConfig,\n param: unknown,\n): R => {\n if (param === undefined) {\n return request;\n }\n\n const dependencies = getKeyDependencies(request, pagination);\n let page = setPagingValue(request, pagination, param);\n\n if (!dependencies.cacheKey) {\n page = page.setCacheKey(`${page.cacheKey}_${stringifyKey(param)}`) as RequestInstance;\n }\n if (!dependencies.queryKey) {\n page = page.setQueryKey(`${page.queryKey}_${stringifyKey(param)}`) as RequestInstance;\n }\n return page as R;\n};\n\nconst getCallbackContext = ({ data, param, pages }: PaginationPageContext) => ({ data, param, pages });\n\nconst readOption = (option: unknown, context: PaginationPageContext): unknown => {\n if (typeof option === \"function\") {\n return option(getCallbackContext(context));\n }\n return typeof option === \"string\" ? context.data?.[option] : undefined;\n};\n\n/**\n * Items of a single page\n */\nexport const getPageItems = (context: PaginationPageContext): unknown[] => {\n const { pagination, data } = context;\n const items = pagination.items === undefined ? data : readOption(pagination.items, context);\n return Array.isArray(items) ? items : [];\n};\n\n/**\n * Size of the whole list, when the pagination declares it\n */\nexport const getPageTotal = (context: PaginationPageContext): number | null => {\n return toNumber(readOption(context.pagination.total, context)) ?? null;\n};\n\n/**\n * Paging value of the page after the given one\n */\nexport const getNextPageParam = (context: PaginationPageContext): unknown => {\n const { request, pagination, param } = context;\n const mode = getPaginationMode(pagination);\n\n if (mode === \"cursor\") {\n const cursor = readOption(pagination.next, context);\n return isEmptyCursor(cursor) ? undefined : cursor;\n }\n if (mode === \"page\") {\n return Number(param) + 1;\n }\n return Number(param) + (getPageLimit(request, pagination) ?? getPageItems(context).length);\n};\n\n/**\n * Paging value of the page before the given one\n */\nexport const getPreviousPageParam = (context: PaginationPageContext): unknown => {\n const { request, pagination, param } = context;\n const mode = getPaginationMode(pagination);\n\n if (mode === \"cursor\") {\n const cursor = readOption(pagination.previous, context);\n return isEmptyCursor(cursor) ? undefined : cursor;\n }\n if (mode === \"page\") {\n const previous = Number(param) - 1;\n return previous >= getFirstPageNumber(request, pagination) ? previous : undefined;\n }\n if (Number(param) <= 0) {\n return undefined;\n }\n const size = getPageLimit(request, pagination) ?? getPageItems(context).length;\n return Math.max(0, Number(param) - size);\n};\n\n/**\n * Tells whether the list continues after the given page\n */\nexport const getHasNextPage = (context: PaginationPageContext): boolean => {\n const { request, pagination, param } = context;\n const mode = getPaginationMode(pagination);\n\n if (getNextPageParam(context) === undefined) {\n return false;\n }\n if (pagination.hasNext) {\n return !!pagination.hasNext(getCallbackContext(context));\n }\n if (mode === \"cursor\") {\n return true;\n }\n\n const items = getPageItems(context);\n if (items.length === 0) {\n return false;\n }\n\n const limit = getPageLimit(request, pagination);\n const total = getPageTotal(context);\n if (total !== null) {\n if (mode === \"offset\") {\n return Number(param) + items.length < total;\n }\n const pageIndex = Number(param) - getFirstPageNumber(request, pagination);\n return (pageIndex + 1) * (limit ?? items.length) < total;\n }\n\n return limit === undefined || items.length >= limit;\n};\n\n/**\n * Tells whether the list continues before the given page\n */\nexport const getHasPreviousPage = (context: PaginationPageContext): boolean => {\n if (getPreviousPageParam(context) === undefined) {\n return false;\n }\n return context.pagination.hasPrevious ? !!context.pagination.hasPrevious(getCallbackContext(context)) : true;\n};\n\n/**\n * Rebuilds a list from already stored pages: from the starting page forwards, then backwards, until a page\n * is missing. Nothing has to remember which pages were loaded.\n */\nexport const getCachedPages = <T extends { data: unknown }>({\n request,\n pagination,\n read,\n maxPages = Infinity,\n}: {\n request: RequestInstance;\n pagination: PaginationConfig;\n read: (pageRequest: RequestInstance) => T | null | undefined;\n maxPages?: number;\n}): CachedInfinitePage<T>[] => {\n const pages: CachedInfinitePage<T>[] = [];\n // Cursors returned by the server could point back at an earlier page\n const visited = new Set<string>();\n\n const readPage = (param: unknown) => {\n const key = stringifyKey(param);\n if (visited.has(key) || pages.length >= maxPages) {\n return null;\n }\n visited.add(key);\n\n const pageRequest = getPageRequest(request, pagination, param);\n const value = read(pageRequest);\n return value ? { param, request: pageRequest, value } : null;\n };\n\n const getContext = (page: CachedInfinitePage<T>): PaginationPageContext => ({\n request,\n pagination,\n data: page.value.data,\n param: page.param,\n pages: pages.map((item) => item.value.data),\n });\n\n const first = readPage(getInitialPageParam(request, pagination));\n if (!first) {\n return pages;\n }\n pages.push(first);\n\n while (true) {\n const last = pages.at(-1) as CachedInfinitePage<T>;\n const param = getHasNextPage(getContext(last)) ? getNextPageParam(getContext(last)) : undefined;\n const page = param === undefined ? null : readPage(param);\n if (!page) {\n break;\n }\n pages.push(page);\n }\n\n while (true) {\n const param = getHasPreviousPage(getContext(pages[0])) ? getPreviousPageParam(getContext(pages[0])) : undefined;\n const page = param === undefined ? null : readPage(param);\n if (!page) {\n break;\n }\n pages.unshift(page);\n }\n\n return pages;\n};\n","import type { RequestInstance } from \"request\";\nimport type { HydrateDataType } from \"types\";\n\nimport type { FetchInfiniteOptions, FetchInfiniteResult, Pagination, PaginationConfig } from \"./infinite.types\";\nimport {\n getHasNextPage,\n getInitialPageParam,\n getNextPageParam,\n getPageItems,\n getPageRequest,\n getPageTotal,\n} from \"./infinite.utils\";\n\n/**\n * Fetches the first pages of a list one after another, without touching the cache or the queues.\n * Made for server rendering: pass `dehydrated` to the `Hydrate` component to render them on the client.\n *\n * @example\n * ```ts\n * const { dehydrated } = await fetchInfinite(getFeed, {\n * pagination: { cursor: \"cursor\", next: \"nextCursor\", items: \"data\" },\n * pages: 2,\n * });\n * ```\n */\nexport const fetchInfinite = async <R extends RequestInstance, const P extends Pagination<R>>(\n request: R,\n options: FetchInfiniteOptions<P>,\n): Promise<FetchInfiniteResult<R, P>> => {\n const pagination = options.pagination as PaginationConfig;\n const pageCount = Math.max(1, options.pages ?? 1);\n\n const result: FetchInfiniteResult<any, any> = {\n items: [],\n pages: [],\n pageParams: [],\n total: null,\n hasNextPage: false,\n error: null,\n responses: [],\n dehydrated: [],\n };\n\n let param = getInitialPageParam(request, pagination);\n\n for (let index = 0; index < pageCount; index += 1) {\n const pageRequest = getPageRequest(request, pagination, param);\n // Pages depend on each other, so they cannot be requested at the same time\n // A failed page ends the loop below - it must not reject, whatever `throwOnError` the request has\n // eslint-disable-next-line no-await-in-loop\n const response = await (pageRequest as RequestInstance).exec({ throwOnError: false });\n\n result.responses.push(response);\n\n if (!response.success) {\n result.error = response.error;\n break;\n }\n\n const context = { request, pagination, data: response.data, param, pages: result.pages };\n\n result.pages.push(response.data);\n result.pageParams.push(param);\n (result.items as unknown[]).push(...getPageItems(context));\n result.total = getPageTotal(context) ?? result.total;\n result.hasNextPage = getHasNextPage(context);\n result.dehydrated.push(pageRequest.dehydrate({ response }) as HydrateDataType);\n\n if (!result.hasNextPage) {\n break;\n }\n param = getNextPageParam(context);\n }\n\n return result as FetchInfiniteResult<R, P>;\n};\n"],"x_google_ignoreList":[4],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,IAAa,SAAb,MAAuF;CACrF;CACA;CAEA,SAAoC,KAAA;CAEpC,gBAAwD,EAAE;CAE1D,YAAY,QAA8C;AAAvC,OAAA,SAAA;AACjB,OAAK,OAAO,OAAO;AACnB,MAAI,OAAO,KACT,MAAK,OAAO,OAAO;;;CAKvB,cAAc,WAAmB;AAC/B,OAAK,SAAS;AACd,SAAO;;;CAIT,WAAoD,QAAa,SAA8C;EAC7G,MAAM,WAAW,KAAK,cAAc;AACpC,MAAI,SACF,UAAS,KAAY;;;;;CAWzB,W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