@zayne-labs/callapi 1.8.8 → 1.8.10
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/README.md +3 -3
- package/dist/esm/{common-D7kwLndy.d.ts → common-CmLbOQH8.d.ts} +54 -27
- package/dist/esm/index.d.ts +4 -4
- package/dist/esm/index.js +64 -79
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/utils/index.d.ts +1 -1
- package/dist/esm/utils/index.js +1 -1
- package/dist/esm/{utils-BbmhntpS.js → utils-BMQYfuNI.js} +17 -4
- package/dist/esm/utils-BMQYfuNI.js.map +1 -0
- package/package.json +10 -11
- package/dist/esm/utils-BbmhntpS.js.map +0 -1
package/dist/esm/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.js","names":["response: Response","parser: Parser","responseType?: ResponseTypeUnion","parser?: Parser","details: CallApiResultErrorVariant<unknown> | CallApiResultSuccessVariant<unknown>","data: unknown","info: SuccessInfo","error: unknown","info: ErrorInfo","errorResult: ErrorResult","customErrorInfo: { message: string | undefined }","hooksArray: Array<AnyFunction | undefined>","mergedHooksExecutionMode: CallApiExtraOptionsForHooks[\"mergedHooksExecutionMode\"]","ctx: unknown","hookResultsOrPromise: Array<Awaitable<unknown>>","hookInfo: ExecuteHookInfo","options: {\n\tchunk: Uint8Array;\n\ttotalBytes: number;\n\ttransferredBytes: number;\n}","requestBody: Request[\"body\"] | null","existingTotalBytes: number","context: ToStreamableRequestContext","context: StreamableResponseContext","dedupeKey: DedupeOptions[\"dedupeKey\"]","fullURL: DedupeContext[\"options\"][\"fullURL\"]","context: DedupeContext","$GlobalRequestInfoCache","deferContext: {\n\t\toptions: DedupeContext[\"options\"];\n\t\trequest: DedupeContext[\"request\"];\n\t}","plugin: TPlugin","plugins: CallApiExtraOptions[\"plugins\"] | undefined","basePlugins: BaseCallApiExtraOptions[\"plugins\"] | undefined","context: PluginInitContext","pluginHooks: Required<CallApiPlugin>[\"hooks\"]","pluginInit: CallApiPlugin[\"init\"]","resolvedHooks: Hooks","currentAttemptCount: number","options: RetryOptions<unknown>","ctx: ErrorContext<unknown> & RequestContext","validator: Extract<CallApiSchema[keyof CallApiSchema], AnyFunction>","inputData: TInput","schema: TSchema","inputData: InferSchemaInput<TSchema>","response?: Response | null","baseSchema: TBaseSchema","schema: TSchema | undefined","validationOptions: ValidationOptions<TSchema>","validationOptions: ExtraOptionsValidationOptions","validatedResultObject: Prettify<\n\t\tPick<CallApiExtraOptions, (typeof extraOptionsToBeValidated)[number]>\n\t>","validationOptions: RequestOptionsValidationOptions","validatedResultObject: Prettify<\n\t\tPick<CallApiRequestOptions, (typeof requestOptionsToBeValidated)[number]>\n\t>","validationOptions: ExtraOptionsValidationOptions & RequestOptionsValidationOptions","url: string","params: CallApiExtraOptions[\"params\"]","query: CallApiExtraOptions[\"query\"]","schemaConfig: CallApiSchemaConfig | undefined","initURL: string | undefined","options: GetMethodOptions","initURL: string","options: GetFullURLOptions","$GlobalRequestInfoCache: RequestInfoCache","initBaseConfig: BaseCallApiConfig<\n\t\tTBaseData,\n\t\tTBaseErrorData,\n\t\tTBaseResultMode,\n\t\tTBaseThrowOnError,\n\t\tTBaseResponseType,\n\t\tTBaseSchema,\n\t\tTBaseSchemaConfig,\n\t\tTBasePluginArray\n\t>","$LocalRequestInfoCache: RequestInfoCache","callApi","hookError","message: string | undefined"],"sources":["../../src/result.ts","../../src/hooks.ts","../../src/stream.ts","../../src/dedupe.ts","../../src/plugins.ts","../../src/retry.ts","../../src/validation.ts","../../src/url.ts","../../src/createFetchClient.ts","../../src/defineParameters.ts"],"sourcesContent":["import { commonDefaults, responseDefaults } from \"./constants/default-options\";\nimport type { HTTPError, ValidationError } from \"./error\";\nimport type { CallApiExtraOptions, ThrowOnErrorUnion } from \"./types\";\nimport type { DefaultDataType } from \"./types/default-types\";\nimport type { AnyString, Awaitable, UnmaskType } from \"./types/type-helpers\";\nimport { isHTTPErrorInstance, isValidationErrorInstance } from \"./utils/guards\";\n\ntype Parser = (responseString: string) => Awaitable<Record<string, unknown>>;\n\nexport const getResponseType = <TResponse>(response: Response, parser: Parser) => ({\n\tarrayBuffer: () => response.arrayBuffer(),\n\tblob: () => response.blob(),\n\tformData: () => response.formData(),\n\tjson: async () => {\n\t\tconst text = await response.text();\n\t\treturn parser(text) as TResponse;\n\t},\n\tstream: () => response.body,\n\ttext: () => response.text(),\n});\n\ntype InitResponseTypeMap<TResponse = unknown> = ReturnType<typeof getResponseType<TResponse>>;\n\nexport type ResponseTypeUnion = keyof InitResponseTypeMap | null;\n\nexport type ResponseTypeMap<TResponse> = {\n\t[Key in keyof InitResponseTypeMap<TResponse>]: Awaited<ReturnType<InitResponseTypeMap<TResponse>[Key]>>;\n};\n\nexport type GetResponseType<\n\tTResponse,\n\tTResponseType extends ResponseTypeUnion,\n\tTComputedResponseTypeMap extends ResponseTypeMap<TResponse> = ResponseTypeMap<TResponse>,\n> =\n\tnull extends TResponseType ? TComputedResponseTypeMap[\"json\"]\n\t: TResponseType extends NonNullable<ResponseTypeUnion> ? TComputedResponseTypeMap[TResponseType]\n\t: never;\n\nexport const resolveResponseData = <TResponse>(\n\tresponse: Response,\n\tresponseType?: ResponseTypeUnion,\n\tparser?: Parser\n) => {\n\tconst selectedParser = parser ?? responseDefaults.responseParser;\n\tconst selectedResponseType = responseType ?? responseDefaults.responseType;\n\n\tconst RESPONSE_TYPE_LOOKUP = getResponseType<TResponse>(response, selectedParser);\n\n\tif (!Object.hasOwn(RESPONSE_TYPE_LOOKUP, selectedResponseType)) {\n\t\tthrow new Error(`Invalid response type: ${responseType}`);\n\t}\n\n\treturn RESPONSE_TYPE_LOOKUP[selectedResponseType]();\n};\n\nexport type CallApiResultSuccessVariant<TData> = {\n\tdata: NoInfer<TData>;\n\terror: null;\n\tresponse: Response;\n};\n\nexport type PossibleJavaScriptError = UnmaskType<{\n\terrorData: false;\n\tmessage: string;\n\tname: \"AbortError\" | \"Error\" | \"SyntaxError\" | \"TimeoutError\" | \"TypeError\" | AnyString;\n\toriginalError: DOMException | Error | SyntaxError | TypeError;\n}>;\n\nexport type PossibleHTTPError<TErrorData> = UnmaskType<{\n\terrorData: NoInfer<TErrorData>;\n\tmessage: string;\n\tname: \"HTTPError\";\n\toriginalError: HTTPError;\n}>;\n\nexport type PossibleValidationError = UnmaskType<{\n\terrorData: ValidationError[\"errorData\"];\n\tmessage: string;\n\tname: \"ValidationError\";\n\toriginalError: ValidationError;\n}>;\n\nexport type PossibleJavaScriptOrValidationError = UnmaskType<\n\tPossibleJavaScriptError | PossibleValidationError\n>;\n\nexport type CallApiResultErrorVariant<TErrorData> =\n\t| {\n\t\t\tdata: null;\n\t\t\terror: PossibleHTTPError<TErrorData>;\n\t\t\tresponse: Response;\n\t }\n\t| {\n\t\t\tdata: null;\n\t\t\terror: PossibleJavaScriptOrValidationError;\n\t\t\tresponse: Response | null;\n\t };\n\nexport type ResultModeMap<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTComputedData = GetResponseType<TData, TResponseType>,\n\tTComputedErrorData = GetResponseType<TErrorData, TResponseType>,\n> = UnmaskType<{\n\t/* eslint-disable perfectionist/sort-union-types -- I need the first one to be first */\n\tall: CallApiResultSuccessVariant<TComputedData> | CallApiResultErrorVariant<TComputedErrorData>;\n\n\tallWithException: CallApiResultSuccessVariant<TComputedData>;\n\n\tonlySuccess:\n\t\t| CallApiResultErrorVariant<TComputedErrorData>[\"data\"]\n\t\t| CallApiResultSuccessVariant<TComputedData>[\"data\"];\n\n\tonlySuccessWithException: CallApiResultSuccessVariant<TComputedData>[\"data\"];\n\t/* eslint-enable perfectionist/sort-union-types -- I need the first one to be first */\n}>;\n\nexport type ResultModeUnion = keyof ResultModeMap | null;\n\nexport type GetCallApiResult<\n\tTData,\n\tTErrorData,\n\tTResultMode extends ResultModeUnion,\n\tTThrowOnError extends ThrowOnErrorUnion,\n\tTResponseType extends ResponseTypeUnion,\n> =\n\tTErrorData extends false ? ResultModeMap<TData, TErrorData, TResponseType>[\"onlySuccessWithException\"]\n\t: TErrorData extends false | undefined ?\n\t\tResultModeMap<TData, TErrorData, TResponseType>[\"onlySuccessWithException\"]\n\t: TErrorData extends false | null ? ResultModeMap<TData, TErrorData, TResponseType>[\"onlySuccess\"]\n\t: null extends TResultMode ?\n\t\tTThrowOnError extends true ?\n\t\t\tResultModeMap<TData, TErrorData, TResponseType>[\"allWithException\"]\n\t\t:\tResultModeMap<TData, TErrorData, TResponseType>[\"all\"]\n\t: TResultMode extends NonNullable<ResultModeUnion> ?\n\t\tResultModeMap<TData, TErrorData, TResponseType>[TResultMode]\n\t:\tnever;\n\ntype SuccessInfo = {\n\tresponse: Response;\n\tresultMode: CallApiExtraOptions[\"resultMode\"];\n};\n\ntype LazyResultModeMap = {\n\t[key in keyof ResultModeMap]: () => ResultModeMap[key];\n};\n\nconst getResultModeMap = (\n\tdetails: CallApiResultErrorVariant<unknown> | CallApiResultSuccessVariant<unknown>\n) => {\n\tconst resultModeMap = {\n\t\tall: () => details,\n\t\tallWithException: () => resultModeMap.all() as never,\n\t\tonlySuccess: () => details.data,\n\t\tonlySuccessWithException: () => resultModeMap.onlySuccess(),\n\t} satisfies LazyResultModeMap as LazyResultModeMap;\n\n\treturn resultModeMap;\n};\n\ntype SuccessResult = CallApiResultSuccessVariant<unknown> | null;\n\n// == The CallApiResult type is used to cast all return statements due to a design limitation in ts.\n// LINK - See https://www.zhenghao.io/posts/type-functions for more info\nexport const resolveSuccessResult = (data: unknown, info: SuccessInfo): SuccessResult => {\n\tconst { response, resultMode } = info;\n\n\tconst details = {\n\t\tdata,\n\t\terror: null,\n\t\tresponse,\n\t} satisfies CallApiResultSuccessVariant<unknown>;\n\n\tconst resultModeMap = getResultModeMap(details);\n\n\tconst successResult = resultModeMap[resultMode ?? \"all\"]();\n\n\treturn successResult as SuccessResult;\n};\n\nexport type ErrorInfo = {\n\tcloneResponse: CallApiExtraOptions[\"cloneResponse\"];\n\tdefaultErrorMessage: CallApiExtraOptions[\"defaultErrorMessage\"];\n\tmessage?: string;\n\tresultMode: CallApiExtraOptions[\"resultMode\"];\n};\n\ntype ErrorResult = CallApiResultErrorVariant<unknown> | null;\n\nexport const resolveErrorResult = (error: unknown, info: ErrorInfo): ErrorResult => {\n\tconst { cloneResponse, defaultErrorMessage, message: customErrorMessage, resultMode } = info;\n\n\tlet details = {\n\t\tdata: null,\n\t\terror: {\n\t\t\terrorData: false,\n\t\t\tmessage: customErrorMessage ?? (error as Error).message,\n\t\t\tname: (error as Error).name,\n\t\t\toriginalError: error as Error,\n\t\t},\n\t\tresponse: null,\n\t} satisfies CallApiResultErrorVariant<unknown> as CallApiResultErrorVariant<unknown>;\n\n\tif (isValidationErrorInstance(error)) {\n\t\tconst { errorData, message, response } = error;\n\n\t\tdetails = {\n\t\t\tdata: null,\n\t\t\terror: { errorData, message, name: \"ValidationError\", originalError: error },\n\t\t\tresponse,\n\t\t};\n\t}\n\n\tif (isHTTPErrorInstance<never>(error)) {\n\t\tconst selectedDefaultErrorMessage = defaultErrorMessage ?? commonDefaults.defaultErrorMessage;\n\n\t\tconst { errorData, message = selectedDefaultErrorMessage, name, response } = error;\n\n\t\tdetails = {\n\t\t\tdata: null,\n\t\t\terror: { errorData, message, name, originalError: error },\n\t\t\tresponse: cloneResponse ? response.clone() : response,\n\t\t};\n\t}\n\n\tconst resultModeMap = getResultModeMap(details);\n\n\tconst errorResult = resultModeMap[resultMode ?? \"all\"]();\n\n\treturn errorResult as ErrorResult;\n};\n\nexport const getCustomizedErrorResult = (\n\terrorResult: ErrorResult,\n\tcustomErrorInfo: { message: string | undefined }\n): ErrorResult => {\n\tif (!errorResult) {\n\t\treturn null;\n\t}\n\n\tconst { message = errorResult.error.message } = customErrorInfo;\n\n\treturn {\n\t\t...errorResult,\n\t\terror: {\n\t\t\t...errorResult.error,\n\t\t\tmessage,\n\t\t} satisfies NonNullable<ErrorResult>[\"error\"] as never,\n\t};\n};\n","import type { ValidationError } from \"./error\";\nimport {\n\ttype CallApiResultErrorVariant,\n\ttype CallApiResultSuccessVariant,\n\ttype ErrorInfo,\n\ttype PossibleHTTPError,\n\ttype PossibleJavaScriptOrValidationError,\n\tresolveErrorResult,\n} from \"./result\";\nimport type { StreamProgressEvent } from \"./stream\";\nimport type {\n\tBaseCallApiExtraOptions,\n\tCallApiExtraOptions,\n\tCallApiExtraOptionsForHooks,\n\tCallApiRequestOptions,\n\tCallApiRequestOptionsForHooks,\n} from \"./types/common\";\nimport type { DefaultDataType } from \"./types/default-types\";\nimport type { AnyFunction, Awaitable, UnmaskType } from \"./types/type-helpers\";\n\nexport type PluginExtraOptions<TPluginOptions = unknown> = {\n\toptions: Partial<TPluginOptions>;\n};\n\n/* eslint-disable perfectionist/sort-intersection-types -- Plugin options should come last */\nexport interface Hooks<TData = DefaultDataType, TErrorData = DefaultDataType, TPluginOptions = unknown> {\n\t/**\n\t * Hook that will be called when any error occurs within the request/response lifecycle, regardless of whether the error is from the api or not.\n\t * It is basically a combination of `onRequestError` and `onResponseError` hooks\n\t */\n\tonError?: (\n\t\tcontext: ErrorContext<TErrorData> & PluginExtraOptions<TPluginOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called just before the request is being made.\n\t */\n\tonRequest?: (context: RequestContext & PluginExtraOptions<TPluginOptions>) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when an error occurs during the fetch request.\n\t */\n\tonRequestError?: (\n\t\tcontext: RequestErrorContext & PluginExtraOptions<TPluginOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when upload stream progress is tracked\n\t */\n\tonRequestStream?: (\n\t\tcontext: RequestStreamContext & PluginExtraOptions<TPluginOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when any response is received from the api, whether successful or not\n\t */\n\tonResponse?: (\n\t\tcontext: ResponseContext<TData, TErrorData> & PluginExtraOptions<TPluginOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when an error response is received from the api.\n\t */\n\tonResponseError?: (\n\t\tcontext: ResponseErrorContext<TErrorData> & PluginExtraOptions<TPluginOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when download stream progress is tracked\n\t */\n\tonResponseStream?: (\n\t\tcontext: ResponseStreamContext & PluginExtraOptions<TPluginOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when a request is retried.\n\t */\n\tonRetry?: (\n\t\tresponse: RetryContext<TErrorData> & PluginExtraOptions<TPluginOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when a successful response is received from the api.\n\t */\n\tonSuccess?: (context: SuccessContext<TData> & PluginExtraOptions<TPluginOptions>) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when a validation error occurs.\n\t */\n\tonValidationError?: (\n\t\tcontext: ValidationErrorContext & PluginExtraOptions<TPluginOptions>\n\t) => Awaitable<unknown>;\n}\n/* eslint-enable perfectionist/sort-intersection-types -- Plugin options should come last */\n\nexport type HooksOrHooksArray<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTMoreOptions = unknown,\n> = {\n\t[Key in keyof Hooks<TData, TErrorData, TMoreOptions>]:\n\t\t| Hooks<TData, TErrorData, TMoreOptions>[Key]\n\t\t// eslint-disable-next-line perfectionist/sort-union-types -- I need arrays to be last\n\t\t| Array<Hooks<TData, TErrorData, TMoreOptions>[Key]>;\n};\n\nexport type RequestContext = {\n\t/**\n\t * Config object passed to createFetchClient\n\t */\n\tbaseConfig: BaseCallApiExtraOptions & CallApiRequestOptions;\n\t/**\n\t * Config object passed to the callApi instance\n\t */\n\tconfig: CallApiExtraOptions & CallApiRequestOptions;\n\t/**\n\t * Merged options consisting of extra options from createFetchClient, the callApi instance and default options.\n\t *\n\t */\n\toptions: CallApiExtraOptionsForHooks;\n\t/**\n\t * Merged request consisting of request options from createFetchClient, the callApi instance and default request options.\n\t */\n\trequest: CallApiRequestOptionsForHooks;\n};\n\nexport type ResponseContext<TData, TErrorData> = UnmaskType<\n\tRequestContext & (CallApiResultErrorVariant<TErrorData> | CallApiResultSuccessVariant<TData>)\n>;\n\nexport type ValidationErrorContext = UnmaskType<\n\tRequestContext & {\n\t\terror: ValidationError;\n\t\tresponse: Response | null;\n\t}\n>;\n\nexport type SuccessContext<TData> = UnmaskType<\n\tRequestContext & {\n\t\tdata: TData;\n\t\tresponse: Response;\n\t}\n>;\n\nexport type RequestErrorContext = RequestContext & {\n\terror: PossibleJavaScriptOrValidationError;\n\tresponse: null;\n};\n\nexport type ErrorContext<TErrorData> = UnmaskType<\n\tRequestContext\n\t\t& (\n\t\t\t| {\n\t\t\t\t\terror: PossibleHTTPError<TErrorData>;\n\t\t\t\t\tresponse: Response;\n\t\t\t }\n\t\t\t| {\n\t\t\t\t\terror: PossibleJavaScriptOrValidationError;\n\t\t\t\t\tresponse: Response | null;\n\t\t\t }\n\t\t)\n>;\n\nexport type ResponseErrorContext<TErrorData> = UnmaskType<\n\tExtract<ErrorContext<TErrorData>, { error: PossibleHTTPError<TErrorData> }> & RequestContext\n>;\n\nexport type RetryContext<TErrorData> = UnmaskType<\n\tErrorContext<TErrorData> & { retryAttemptCount: number }\n>;\n\nexport type RequestStreamContext = UnmaskType<\n\tRequestContext & {\n\t\tevent: StreamProgressEvent;\n\t\trequestInstance: Request;\n\t}\n>;\n\nexport type ResponseStreamContext = UnmaskType<\n\tRequestContext & {\n\t\tevent: StreamProgressEvent;\n\t\tresponse: Response;\n\t}\n>;\n\ntype HookRegistries = Required<{\n\t[Key in keyof Hooks]: Set<Hooks[Key]>;\n}>;\n\nexport const hookRegistries = {\n\tonError: new Set(),\n\tonRequest: new Set(),\n\tonRequestError: new Set(),\n\tonRequestStream: new Set(),\n\tonResponse: new Set(),\n\tonResponseError: new Set(),\n\tonResponseStream: new Set(),\n\tonRetry: new Set(),\n\tonSuccess: new Set(),\n\tonValidationError: new Set(),\n} satisfies HookRegistries;\n\nexport const composeAllHooks = (\n\thooksArray: Array<AnyFunction | undefined>,\n\tmergedHooksExecutionMode: CallApiExtraOptionsForHooks[\"mergedHooksExecutionMode\"]\n) => {\n\tconst mergedHook = async (ctx: unknown) => {\n\t\tif (mergedHooksExecutionMode === \"sequential\") {\n\t\t\tfor (const hook of hooksArray) {\n\t\t\t\t// eslint-disable-next-line no-await-in-loop -- This is necessary in this case\n\t\t\t\tawait hook?.(ctx);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif (mergedHooksExecutionMode === \"parallel\") {\n\t\t\tawait Promise.all(hooksArray.map((uniqueHook) => uniqueHook?.(ctx)));\n\t\t}\n\t};\n\n\treturn mergedHook;\n};\n\nexport const executeHooksInTryBlock = async (...hookResultsOrPromise: Array<Awaitable<unknown>>) => {\n\tawait Promise.all(hookResultsOrPromise);\n};\n\nexport type ExecuteHookInfo = {\n\terrorInfo: ErrorInfo;\n\tshouldThrowOnError: boolean | undefined;\n};\n\nexport const executeHooksInCatchBlock = async (\n\thookResultsOrPromise: Array<Awaitable<unknown>>,\n\thookInfo: ExecuteHookInfo\n) => {\n\tconst { errorInfo, shouldThrowOnError } = hookInfo;\n\n\ttry {\n\t\tawait Promise.all(hookResultsOrPromise);\n\n\t\treturn null;\n\t} catch (hookError) {\n\t\tconst hookErrorResult = resolveErrorResult(hookError, errorInfo);\n\n\t\tif (shouldThrowOnError) {\n\t\t\tthrow hookError;\n\t\t}\n\n\t\treturn hookErrorResult;\n\t}\n};\n","import { executeHooksInTryBlock, type RequestContext } from \"./hooks\";\nimport { isObject } from \"./utils/guards\";\n\nexport type StreamProgressEvent = {\n\t/**\n\t * Current chunk of data being streamed\n\t */\n\tchunk: Uint8Array;\n\t/**\n\t * Progress in percentage\n\t */\n\tprogress: number;\n\t/**\n\t * Total size of data in bytes\n\t */\n\ttotalBytes: number;\n\t/**\n\t * Amount of data transferred so far\n\t */\n\ttransferredBytes: number;\n};\n\ndeclare global {\n\tinterface ReadableStream<R> {\n\t\t[Symbol.asyncIterator]: () => AsyncIterableIterator<R>;\n\t}\n}\n\nconst createProgressEvent = (options: {\n\tchunk: Uint8Array;\n\ttotalBytes: number;\n\ttransferredBytes: number;\n}): StreamProgressEvent => {\n\tconst { chunk, totalBytes, transferredBytes } = options;\n\n\treturn {\n\t\tchunk,\n\t\tprogress: Math.round((transferredBytes / totalBytes) * 100) || 0,\n\t\ttotalBytes,\n\t\ttransferredBytes,\n\t};\n};\n\nconst calculateTotalBytesFromBody = async (\n\trequestBody: Request[\"body\"] | null,\n\texistingTotalBytes: number\n) => {\n\tlet totalBytes = existingTotalBytes;\n\n\tif (!requestBody) {\n\t\treturn totalBytes;\n\t}\n\n\tfor await (const chunk of requestBody) {\n\t\ttotalBytes += chunk.byteLength;\n\t}\n\n\treturn totalBytes;\n};\n\ntype ToStreamableRequestContext = RequestContext & { requestInstance: Request };\n\nexport const toStreamableRequest = async (context: ToStreamableRequestContext) => {\n\tconst { baseConfig, config, options, request, requestInstance } = context;\n\n\tif (!options.onRequestStream || !requestInstance.body) return;\n\n\tconst contentLength =\n\t\trequestInstance.headers.get(\"content-length\")\n\t\t?? new Headers(request.headers as HeadersInit).get(\"content-length\")\n\t\t?? (request.body as Blob | null)?.size;\n\n\tlet totalBytes = Number(contentLength ?? 0);\n\n\tconst shouldForcefullyCalcStreamSize =\n\t\tisObject(options.forcefullyCalculateStreamSize) ?\n\t\t\toptions.forcefullyCalculateStreamSize.request\n\t\t:\toptions.forcefullyCalculateStreamSize;\n\n\t// If no content length is present, we read the total bytes from the body\n\tif (!contentLength && shouldForcefullyCalcStreamSize) {\n\t\ttotalBytes = await calculateTotalBytesFromBody(requestInstance.clone().body, totalBytes);\n\t}\n\n\tlet transferredBytes = 0;\n\n\tawait executeHooksInTryBlock(\n\t\toptions.onRequestStream({\n\t\t\tbaseConfig,\n\t\t\tconfig,\n\t\t\tevent: createProgressEvent({ chunk: new Uint8Array(), totalBytes, transferredBytes }),\n\t\t\toptions,\n\t\t\trequest,\n\t\t\trequestInstance,\n\t\t})\n\t);\n\n\tconst body = requestInstance.body as ReadableStream<Uint8Array> | null;\n\n\tvoid new ReadableStream({\n\t\tstart: async (controller) => {\n\t\t\tif (!body) return;\n\n\t\t\tfor await (const chunk of body) {\n\t\t\t\ttransferredBytes += chunk.byteLength;\n\n\t\t\t\ttotalBytes = Math.max(totalBytes, transferredBytes);\n\n\t\t\t\tawait executeHooksInTryBlock(\n\t\t\t\t\toptions.onRequestStream?.({\n\t\t\t\t\t\tbaseConfig,\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tevent: createProgressEvent({ chunk, totalBytes, transferredBytes }),\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\trequestInstance,\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\t\t\tcontroller.close();\n\t\t},\n\t});\n};\n\ntype StreamableResponseContext = RequestContext & { response: Response };\n\nexport const toStreamableResponse = async (context: StreamableResponseContext): Promise<Response> => {\n\tconst { baseConfig, config, options, request, response } = context;\n\n\tif (!options.onResponseStream || !response.body) {\n\t\treturn response;\n\t}\n\n\tconst contentLength = response.headers.get(\"content-length\");\n\n\tlet totalBytes = Number(contentLength ?? 0);\n\n\tconst shouldForceContentLengthCalc =\n\t\tisObject(options.forcefullyCalculateStreamSize) ?\n\t\t\toptions.forcefullyCalculateStreamSize.response\n\t\t:\toptions.forcefullyCalculateStreamSize;\n\n\t// If no content length is present and `forceContentLengthCalculation` is enabled, we read the total bytes from the body\n\tif (!contentLength && shouldForceContentLengthCalc) {\n\t\ttotalBytes = await calculateTotalBytesFromBody(response.clone().body, totalBytes);\n\t}\n\n\tlet transferredBytes = 0;\n\n\tawait executeHooksInTryBlock(\n\t\toptions.onResponseStream({\n\t\t\tbaseConfig,\n\t\t\tconfig,\n\t\t\tevent: createProgressEvent({ chunk: new Uint8Array(), totalBytes, transferredBytes }),\n\t\t\toptions,\n\t\t\trequest,\n\t\t\tresponse,\n\t\t})\n\t);\n\n\tconst body = response.body as ReadableStream<Uint8Array> | null;\n\n\tconst stream = new ReadableStream({\n\t\tstart: async (controller) => {\n\t\t\tif (!body) return;\n\n\t\t\tfor await (const chunk of body) {\n\t\t\t\ttransferredBytes += chunk.byteLength;\n\n\t\t\t\ttotalBytes = Math.max(totalBytes, transferredBytes);\n\n\t\t\t\tawait executeHooksInTryBlock(\n\t\t\t\t\toptions.onResponseStream?.({\n\t\t\t\t\t\tbaseConfig,\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tevent: createProgressEvent({ chunk, totalBytes, transferredBytes }),\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\tresponse,\n\t\t\t\t\t})\n\t\t\t\t);\n\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\n\t\t\tcontroller.close();\n\t\t},\n\t});\n\n\treturn new Response(stream, response);\n};\n","import { dedupeDefaults } from \"./constants/default-options\";\nimport type { RequestContext } from \"./hooks\";\nimport { toStreamableRequest, toStreamableResponse } from \"./stream\";\nimport { getFetchImpl, waitFor } from \"./utils/common\";\nimport { isReadableStream } from \"./utils/guards\";\n\ntype RequestInfo = {\n\tcontroller: AbortController;\n\tresponsePromise: Promise<Response>;\n};\n\nexport type RequestInfoCache = Map<string | null, RequestInfo>;\n\ntype DedupeContext = RequestContext & {\n\t$GlobalRequestInfoCache: RequestInfoCache;\n\t$LocalRequestInfoCache: RequestInfoCache;\n\tnewFetchController: AbortController;\n};\n\nexport const getAbortErrorMessage = (\n\tdedupeKey: DedupeOptions[\"dedupeKey\"],\n\tfullURL: DedupeContext[\"options\"][\"fullURL\"]\n) => {\n\treturn dedupeKey ?\n\t\t\t`Duplicate request detected - Aborting previous request with key '${dedupeKey}' as a new request was initiated`\n\t\t:\t`Duplicate request detected - Aborting previous request to '${fullURL}' as a new request with identical options was initiated`;\n};\n\nexport const createDedupeStrategy = async (context: DedupeContext) => {\n\tconst {\n\t\t$GlobalRequestInfoCache,\n\t\t$LocalRequestInfoCache,\n\t\tbaseConfig,\n\t\tconfig,\n\t\tnewFetchController,\n\t\toptions: globalOptions,\n\t\trequest: globalRequest,\n\t} = context;\n\n\tconst dedupeStrategy = globalOptions.dedupeStrategy ?? dedupeDefaults.dedupeStrategy;\n\n\tconst generateDedupeKey = () => {\n\t\tconst shouldHaveDedupeKey = dedupeStrategy === \"cancel\" || dedupeStrategy === \"defer\";\n\n\t\tif (!shouldHaveDedupeKey) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn `${globalOptions.fullURL}-${JSON.stringify({ options: globalOptions, request: globalRequest })}`;\n\t};\n\n\tconst dedupeKey = globalOptions.dedupeKey ?? generateDedupeKey();\n\n\tconst dedupeCacheScope = globalOptions.dedupeCacheScope ?? dedupeDefaults.dedupeCacheScope;\n\n\tconst $RequestInfoCache = (\n\t\t{\n\t\t\tglobal: $GlobalRequestInfoCache,\n\t\t\tlocal: $LocalRequestInfoCache,\n\t\t} satisfies Record<NonNullable<DedupeOptions[\"dedupeCacheScope\"]>, RequestInfoCache>\n\t)[dedupeCacheScope];\n\n\t// == This is to ensure cache operations only occur when key is available\n\tconst $RequestInfoCacheOrNull = dedupeKey !== null ? $RequestInfoCache : null;\n\n\t/******\n\t * == Add a small delay to the execution to ensure proper request deduplication when multiple requests with the same key start simultaneously.\n\t * == This gives time for the cache to be updated with the previous request info before the next request checks it.\n\t ******/\n\tif (dedupeKey !== null) {\n\t\tawait waitFor(0.1);\n\t}\n\n\tconst prevRequestInfo = $RequestInfoCacheOrNull?.get(dedupeKey);\n\n\tconst handleRequestCancelStrategy = () => {\n\t\tconst shouldCancelRequest = prevRequestInfo && dedupeStrategy === \"cancel\";\n\n\t\tif (!shouldCancelRequest) return;\n\n\t\tconst message = getAbortErrorMessage(globalOptions.dedupeKey, globalOptions.fullURL);\n\n\t\tconst reason = new DOMException(message, \"AbortError\");\n\n\t\tprevRequestInfo.controller.abort(reason);\n\n\t\t// == Adding this just so that eslint forces me put await when calling the function (it looks better that way tbh)\n\t\treturn Promise.resolve();\n\t};\n\n\tconst handleRequestDeferStrategy = async (deferContext: {\n\t\toptions: DedupeContext[\"options\"];\n\t\trequest: DedupeContext[\"request\"];\n\t}) => {\n\t\t// == Local options and request are needed so that transformations are applied can be applied to both from call site\n\t\tconst { options: localOptions, request: localRequest } = deferContext;\n\n\t\tconst fetchApi = getFetchImpl(localOptions.customFetchImpl);\n\n\t\tconst shouldUsePromiseFromCache = prevRequestInfo && dedupeStrategy === \"defer\";\n\n\t\tconst requestObjectForStream =\n\t\t\tisReadableStream(localRequest.body) ?\n\t\t\t\t{ ...localRequest, duplex: localRequest.duplex ?? \"half\" }\n\t\t\t:\tlocalRequest;\n\n\t\tconst requestInstance = new Request(\n\t\t\tlocalOptions.fullURL as NonNullable<typeof localOptions.fullURL>,\n\t\t\trequestObjectForStream as RequestInit\n\t\t);\n\n\t\tawait toStreamableRequest({\n\t\t\tbaseConfig,\n\t\t\tconfig,\n\t\t\toptions: localOptions,\n\t\t\trequest: localRequest,\n\t\t\trequestInstance: requestInstance.clone(),\n\t\t});\n\n\t\tconst getFetchApiPromise = () => {\n\t\t\tif (isReadableStream(localRequest.body)) {\n\t\t\t\treturn fetchApi(requestInstance.clone());\n\t\t\t}\n\n\t\t\treturn fetchApi(\n\t\t\t\tlocalOptions.fullURL as NonNullable<typeof localOptions.fullURL>,\n\t\t\t\tlocalRequest as RequestInit\n\t\t\t);\n\t\t};\n\n\t\tconst responsePromise =\n\t\t\tshouldUsePromiseFromCache ? prevRequestInfo.responsePromise : getFetchApiPromise();\n\n\t\t$RequestInfoCacheOrNull?.set(dedupeKey, { controller: newFetchController, responsePromise });\n\n\t\tconst streamableResponse = toStreamableResponse({\n\t\t\tbaseConfig,\n\t\t\tconfig,\n\t\t\toptions: localOptions,\n\t\t\trequest: localRequest,\n\t\t\tresponse: await responsePromise,\n\t\t});\n\n\t\treturn streamableResponse;\n\t};\n\n\tconst removeDedupeKeyFromCache = () => {\n\t\t$RequestInfoCacheOrNull?.delete(dedupeKey);\n\t};\n\n\treturn {\n\t\tdedupeStrategy,\n\t\thandleRequestCancelStrategy,\n\t\thandleRequestDeferStrategy,\n\t\tremoveDedupeKeyFromCache,\n\t};\n};\n\nexport type DedupeOptions = {\n\t/**\n\t * Defines the scope of the deduplication cache, can be set to \"global\" | \"local\".\n\t * - If set to \"global\", the deduplication cache will be shared across all requests, regardless of whether they shared the same `createFetchClient` or not.\n\t * - If set to \"local\", the deduplication cache will be scoped to the current request.\n\t * @default \"local\"\n\t */\n\tdedupeCacheScope?: \"global\" | \"local\";\n\n\t/**\n\t * Custom request key to be used to identify a request in the fetch deduplication strategy.\n\t * @default the full request url + string formed from the request options\n\t */\n\tdedupeKey?: string;\n\n\t/**\n\t * Defines the deduplication strategy for the request, can be set to \"none\" | \"defer\" | \"cancel\".\n\t * - If set to \"cancel\", the previous pending request with the same request key will be cancelled and lets the new request through.\n\t * - If set to \"defer\", all new request with the same request key will be share the same response, until the previous one is completed.\n\t * - If set to \"none\", deduplication is disabled.\n\t * @default \"cancel\"\n\t */\n\tdedupeStrategy?: \"cancel\" | \"defer\" | \"none\";\n};\n","import { hookDefaults } from \"./constants/default-options\";\nimport {\n\tcomposeAllHooks,\n\ttype Hooks,\n\ttype HooksOrHooksArray,\n\thookRegistries,\n\ttype PluginExtraOptions,\n\ttype RequestContext,\n} from \"./hooks\";\nimport type {\n\tBaseCallApiExtraOptions,\n\tCallApiExtraOptions,\n\tCallApiRequestOptions,\n\tCallApiRequestOptionsForHooks,\n} from \"./types/common\";\nimport type { AnyFunction, Awaitable } from \"./types/type-helpers\";\nimport type { InitURLOrURLObject } from \"./url\";\nimport { isArray, isFunction, isPlainObject, isString } from \"./utils/guards\";\n\nexport type PluginInitContext<TPluginExtraOptions = unknown> = RequestContext // eslint-disable-next-line perfectionist/sort-intersection-types -- Allow\n\t& PluginExtraOptions<TPluginExtraOptions> & { initURL: string };\n\nexport type PluginInitResult = Partial<\n\tOmit<PluginInitContext, \"initURL\" | \"request\"> & {\n\t\tinitURL: InitURLOrURLObject;\n\t\trequest: CallApiRequestOptions;\n\t}\n>;\n\nexport type PluginHooksWithMoreOptions<TMoreOptions = unknown> = HooksOrHooksArray<\n\tnever,\n\tnever,\n\tTMoreOptions\n>;\n\nexport type PluginHooks<TData = never, TErrorData = never, TMoreOptions = unknown> = HooksOrHooksArray<\n\tTData,\n\tTErrorData,\n\tTMoreOptions\n>;\n\nexport interface CallApiPlugin {\n\t/**\n\t * Defines additional options that can be passed to callApi\n\t */\n\tdefineExtraOptions?: (...params: never[]) => unknown;\n\n\t/**\n\t * A description for the plugin\n\t */\n\tdescription?: string;\n\n\t/**\n\t * Hooks / Interceptors for the plugin\n\t */\n\thooks?: PluginHooks;\n\n\t/**\n\t * A unique id for the plugin\n\t */\n\tid: string;\n\n\t/**\n\t * A function that will be called when the plugin is initialized. This will be called before the any of the other internal functions.\n\t */\n\tinit?: (context: PluginInitContext) => Awaitable<PluginInitResult> | Awaitable<void>;\n\n\t/**\n\t * A name for the plugin\n\t */\n\tname: string;\n\n\t/**\n\t * A version for the plugin\n\t */\n\tversion?: string;\n}\n\nexport const definePlugin = <\n\t// eslint-disable-next-line perfectionist/sort-union-types -- Let the first one be first\n\tTPlugin extends CallApiPlugin | AnyFunction<CallApiPlugin>,\n>(\n\tplugin: TPlugin\n) => {\n\treturn plugin;\n};\n\nconst resolvePluginArray = (\n\tplugins: CallApiExtraOptions[\"plugins\"] | undefined,\n\tbasePlugins: BaseCallApiExtraOptions[\"plugins\"] | undefined\n) => {\n\tif (!plugins) {\n\t\treturn [];\n\t}\n\n\tif (isFunction(plugins)) {\n\t\treturn plugins({ basePlugins: basePlugins ?? [] });\n\t}\n\n\treturn plugins;\n};\n\nexport const initializePlugins = async (context: PluginInitContext) => {\n\tconst { baseConfig, config, initURL, options, request } = context;\n\n\tconst clonedHookRegistries = structuredClone(hookRegistries);\n\n\tconst addMainHooks = () => {\n\t\tfor (const key of Object.keys(clonedHookRegistries) as Array<keyof Hooks>) {\n\t\t\tconst baseHook = baseConfig;\n\t\t\tconst instanceHook = config[key];\n\n\t\t\tconst overriddenHook = options[key] as HooksOrHooksArray[typeof key];\n\n\t\t\t// If the base hook is an array and instance hook is defined, we need to compose it with the overridden hook\n\t\t\tconst mainHook =\n\t\t\t\tisArray(baseHook) && Boolean(instanceHook) ? [baseHook, instanceHook].flat() : overriddenHook;\n\n\t\t\tif (!mainHook) continue;\n\n\t\t\tclonedHookRegistries[key].add(mainHook as never);\n\t\t}\n\t};\n\n\tconst addPluginHooks = (pluginHooks: Required<CallApiPlugin>[\"hooks\"]) => {\n\t\tfor (const key of Object.keys(clonedHookRegistries) as Array<keyof Hooks>) {\n\t\t\tconst pluginHook = pluginHooks[key];\n\n\t\t\tif (!pluginHook) continue;\n\n\t\t\tclonedHookRegistries[key].add(pluginHook as never);\n\t\t}\n\t};\n\n\tconst mergedHooksExecutionOrder =\n\t\toptions.mergedHooksExecutionOrder ?? hookDefaults.mergedHooksExecutionOrder;\n\n\tif (mergedHooksExecutionOrder === \"mainHooksBeforePlugins\") {\n\t\taddMainHooks();\n\t}\n\n\tconst resolvedPlugins = resolvePluginArray(options.plugins, baseConfig.plugins);\n\n\tlet resolvedInitURL = initURL;\n\tlet resolvedOptions = options;\n\tlet resolvedRequestOptions = request;\n\n\tconst executePluginInit = async (pluginInit: CallApiPlugin[\"init\"]) => {\n\t\tif (!pluginInit) return;\n\n\t\tconst initResult = await pluginInit({\n\t\t\tbaseConfig,\n\t\t\tconfig,\n\t\t\tinitURL,\n\t\t\toptions,\n\t\t\trequest,\n\t\t});\n\n\t\tif (!isPlainObject(initResult)) return;\n\n\t\tconst urlString = initResult.initURL?.toString();\n\n\t\tif (isString(urlString)) {\n\t\t\tresolvedInitURL = urlString;\n\t\t}\n\n\t\tif (isPlainObject(initResult.request)) {\n\t\t\tresolvedRequestOptions = initResult.request as CallApiRequestOptionsForHooks;\n\t\t}\n\n\t\tif (isPlainObject(initResult.options)) {\n\t\t\tresolvedOptions = initResult.options;\n\t\t}\n\t};\n\n\tfor (const plugin of resolvedPlugins) {\n\t\t// eslint-disable-next-line no-await-in-loop -- Await is necessary in this case.\n\t\tawait executePluginInit(plugin.init);\n\n\t\tif (!plugin.hooks) continue;\n\n\t\taddPluginHooks(plugin.hooks);\n\t}\n\n\tif (mergedHooksExecutionOrder === \"mainHooksAfterPlugins\") {\n\t\taddMainHooks();\n\t}\n\n\tconst resolvedHooks: Hooks = {};\n\n\tfor (const [key, hookRegistry] of Object.entries(clonedHookRegistries)) {\n\t\tif (hookRegistry.size === 0) continue;\n\n\t\t// == Flatten the hook registry to remove any nested arrays or hooks incase an array of hooks is passed to any of the hooks\n\t\tconst flattenedHookArray = [...hookRegistry].flat();\n\n\t\tif (flattenedHookArray.length === 0) continue;\n\n\t\tconst mergedHooksExecutionMode =\n\t\t\toptions.mergedHooksExecutionMode ?? hookDefaults.mergedHooksExecutionMode;\n\n\t\tconst composedHook = composeAllHooks(flattenedHookArray, mergedHooksExecutionMode);\n\n\t\tresolvedHooks[key as keyof Hooks] = composedHook;\n\t}\n\n\treturn {\n\t\tresolvedHooks,\n\t\tresolvedInitURL,\n\t\tresolvedOptions,\n\t\tresolvedRequestOptions,\n\t};\n};\n","import { requestOptionDefaults, retryDefaults } from \"./constants/default-options\";\nimport type { ErrorContext, RequestContext } from \"./hooks\";\nimport type { MethodUnion } from \"./types\";\nimport type { Awaitable } from \"./types/type-helpers\";\nimport { isFunction } from \"./utils/guards\";\n\ntype RetryCondition<TErrorData> = (context: ErrorContext<TErrorData>) => Awaitable<boolean>;\n\ntype InnerRetryKeys<TErrorData> = Exclude<keyof RetryOptions<TErrorData>, \"~retryAttemptCount\" | \"retry\">;\n\ntype InnerRetryOptions<TErrorData> = {\n\t[Key in InnerRetryKeys<TErrorData> as Key extends `retry${infer TRest}` ?\n\t\tUncapitalize<TRest> extends \"attempts\" ?\n\t\t\tnever\n\t\t:\tUncapitalize<TRest>\n\t:\tKey]?: RetryOptions<TErrorData>[Key];\n} & {\n\tattempts: NonNullable<RetryOptions<TErrorData>[\"retryAttempts\"]>;\n};\n\nexport interface RetryOptions<TErrorData> {\n\t/**\n\t * Keeps track of the number of times the request has already been retried\n\t *\n\t * @deprecated **NOTE**: This property is used internally to track retries. Please abstain from modifying it.\n\t */\n\treadonly [\"~retryAttemptCount\"]?: number;\n\n\t/**\n\t * All retry options in a single object instead of separate properties\n\t */\n\tretry?: InnerRetryOptions<TErrorData>;\n\n\t/**\n\t * Number of allowed retry attempts on HTTP errors\n\t * @default 0\n\t */\n\tretryAttempts?: number;\n\n\t/**\n\t * Callback whose return value determines if a request should be retried or not\n\t */\n\tretryCondition?: RetryCondition<TErrorData>;\n\n\t/**\n\t * Delay between retries in milliseconds\n\t * @default 1000\n\t */\n\tretryDelay?: number | ((currentAttemptCount: number) => number);\n\n\t/**\n\t * Maximum delay in milliseconds. Only applies to exponential strategy\n\t * @default 10000\n\t */\n\tretryMaxDelay?: number;\n\n\t/**\n\t * HTTP methods that are allowed to retry\n\t * @default [\"GET\", \"POST\"]\n\t */\n\tretryMethods?: MethodUnion[];\n\n\t/**\n\t * HTTP status codes that trigger a retry\n\t */\n\tretryStatusCodes?: number[];\n\n\t/**\n\t * Strategy to use when retrying\n\t * @default \"linear\"\n\t */\n\tretryStrategy?: \"exponential\" | \"linear\";\n}\n\nconst getLinearDelay = (currentAttemptCount: number, options: RetryOptions<unknown>) => {\n\tconst retryDelay = options.retryDelay ?? options.retry?.delay;\n\n\tconst resolveRetryDelay =\n\t\t(isFunction(retryDelay) ? retryDelay(currentAttemptCount) : retryDelay) ?? retryDefaults.delay;\n\n\treturn resolveRetryDelay;\n};\n\nconst getExponentialDelay = (currentAttemptCount: number, options: RetryOptions<unknown>) => {\n\tconst retryDelay = options.retryDelay ?? options.retry?.delay ?? retryDefaults.delay;\n\n\tconst resolvedRetryDelay = isFunction(retryDelay) ? retryDelay(currentAttemptCount) : retryDelay;\n\n\tconst maxDelay = options.retryMaxDelay ?? options.retry?.maxDelay ?? retryDefaults.maxDelay;\n\n\tconst exponentialDelay = resolvedRetryDelay * 2 ** currentAttemptCount;\n\n\treturn Math.min(exponentialDelay, maxDelay);\n};\n\nexport const createRetryStrategy = (ctx: ErrorContext<unknown> & RequestContext) => {\n\tconst { options } = ctx;\n\n\t// eslint-disable-next-line ts-eslint/no-deprecated -- Allowed for internal use\n\tconst currentAttemptCount = options[\"~retryAttemptCount\"] ?? 1;\n\n\tconst retryStrategy = options.retryStrategy ?? options.retry?.strategy ?? retryDefaults.strategy;\n\n\tconst getDelay = () => {\n\t\tswitch (retryStrategy) {\n\t\t\tcase \"exponential\": {\n\t\t\t\treturn getExponentialDelay(currentAttemptCount, options);\n\t\t\t}\n\t\t\tcase \"linear\": {\n\t\t\t\treturn getLinearDelay(currentAttemptCount, options);\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tthrow new Error(`Invalid retry strategy: ${String(retryStrategy)}`);\n\t\t\t}\n\t\t}\n\t};\n\n\tconst shouldAttemptRetry = async () => {\n\t\tconst retryCondition = options.retryCondition ?? options.retry?.condition ?? retryDefaults.condition;\n\n\t\tconst maximumRetryAttempts =\n\t\t\toptions.retryAttempts ?? options.retry?.attempts ?? retryDefaults.attempts;\n\n\t\tconst customRetryCondition = await retryCondition(ctx);\n\n\t\tconst baseShouldRetry = maximumRetryAttempts >= currentAttemptCount && customRetryCondition;\n\n\t\tif (!baseShouldRetry) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst retryMethods = new Set(\n\t\t\toptions.retryMethods ?? options.retry?.methods ?? retryDefaults.methods\n\t\t);\n\n\t\tconst resolvedMethod = ctx.request.method ?? requestOptionDefaults.method;\n\n\t\tconst includesMethod = Boolean(resolvedMethod) && retryMethods.has(resolvedMethod);\n\n\t\tconst retryStatusCodes = new Set(options.retryStatusCodes ?? options.retry?.statusCodes ?? []);\n\n\t\tconst includesStatusCodes =\n\t\t\tBoolean(ctx.response?.status)\n\t\t\t&& (retryStatusCodes.size > 0 ? retryStatusCodes.has(ctx.response.status) : true);\n\n\t\tconst shouldRetry = includesMethod && includesStatusCodes;\n\n\t\treturn shouldRetry;\n\t};\n\n\treturn {\n\t\tcurrentAttemptCount,\n\t\tgetDelay,\n\t\tshouldAttemptRetry,\n\t};\n};\n","import { ValidationError } from \"./error\";\nimport type {\n\tBody,\n\tCallApiExtraOptions,\n\tCallApiRequestOptions,\n\tGlobalMeta,\n\tHeadersOption,\n\tMethodUnion,\n} from \"./types\";\nimport type { StandardSchemaV1 } from \"./types/standard-schema\";\nimport {\n\ttype AnyFunction,\n\ttype AnyString,\n\ttype Awaitable,\n\tdefineEnum,\n\ttype Prettify,\n\ttype UnionToIntersection,\n\ttype Writeable,\n} from \"./types/type-helpers\";\nimport type { Params, Query } from \"./url\";\nimport { isFunction } from \"./utils/guards\";\n\ntype InferSchemaInput<TSchema extends CallApiSchema[keyof CallApiSchema]> =\n\tTSchema extends StandardSchemaV1 ? StandardSchemaV1.InferInput<TSchema>\n\t: TSchema extends (value: infer TInput) => unknown ? TInput\n\t: never;\n\nexport type InferSchemaResult<TSchema, TFallbackResult = NonNullable<unknown>> =\n\tundefined extends TSchema ? TFallbackResult\n\t: TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema>\n\t: TSchema extends AnyFunction<infer TResult> ? Awaited<TResult>\n\t: TFallbackResult;\n\nconst handleValidatorFunction = async <TInput>(\n\tvalidator: Extract<CallApiSchema[keyof CallApiSchema], AnyFunction>,\n\tinputData: TInput\n): Promise<StandardSchemaV1.Result<TInput>> => {\n\ttry {\n\t\tconst result = await validator(inputData as never);\n\n\t\treturn {\n\t\t\tissues: undefined,\n\t\t\tvalue: result as never,\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tissues: error as never,\n\t\t\tvalue: undefined,\n\t\t};\n\t}\n};\n\nexport const standardSchemaParser = async <\n\tTSchema extends NonNullable<CallApiSchema[keyof CallApiSchema]>,\n>(\n\tschema: TSchema,\n\tinputData: InferSchemaInput<TSchema>,\n\tresponse?: Response | null\n): Promise<InferSchemaResult<TSchema>> => {\n\tconst result =\n\t\tisFunction(schema) ?\n\t\t\tawait handleValidatorFunction(schema, inputData)\n\t\t:\tawait schema[\"~standard\"].validate(inputData);\n\n\t// == If the `issues` field exists, it means the validation failed\n\tif (result.issues) {\n\t\tthrow new ValidationError(\n\t\t\t{ issues: result.issues, response: response ?? null },\n\t\t\t{ cause: result.issues }\n\t\t);\n\t}\n\n\treturn result.value as never;\n};\n\nexport interface CallApiSchemaConfig {\n\t/**\n\t * The base url of the schema. By default it's the baseURL of the fetch instance.\n\t */\n\tbaseURL?: string;\n\n\t/**\n\t * Disables runtime validation for the schema.\n\t */\n\tdisableRuntimeValidation?: boolean;\n\n\t/**\n\t * If `true`, the original input value will be used instead of the transformed/validated output.\n\t *\n\t * This is useful when you want to validate the input but don't want any transformations\n\t * applied by the validation schema (e.g., type coercion, default values, etc).\n\t */\n\tdisableValidationOutputApplication?: boolean;\n\n\t/**\n\t * Controls the inference of the method option based on the route modifiers (`@get/`, `@post/`, `@put/`, `@patch/`, `@delete/`).\n\t *\n\t * - When `true`, the method option is made required on the type level and is not automatically added to the request options.\n\t * - When `false` or `undefined` (default), the method option is not required on the type level, and is automatically added to the request options.\n\t *\n\t */\n\trequireHttpMethodProvision?: boolean;\n\n\t/**\n\t * Controls the strictness of API route validation.\n\t *\n\t * When true:\n\t * - Only routes explicitly defined in the schema will be considered valid to typescript\n\t * - Attempting to call undefined routes will result in type errors\n\t * - Useful for ensuring API calls conform exactly to your schema definition\n\t *\n\t * When false or undefined (default):\n\t * - All routes will be allowed, whether they are defined in the schema or not\n\t * - Provides more flexibility but less type safety\n\t *\n\t * @default false\n\t */\n\tstrict?: boolean;\n}\n\nexport interface CallApiSchema {\n\t/**\n\t * The schema to use for validating the request body.\n\t */\n\tbody?: StandardSchemaV1<Body> | ((body: Body) => Awaitable<Body>);\n\n\t/**\n\t * The schema to use for validating the response data.\n\t */\n\tdata?: StandardSchemaV1 | ((data: unknown) => unknown);\n\n\t/**\n\t * The schema to use for validating the response error data.\n\t */\n\terrorData?: StandardSchemaV1 | ((errorData: unknown) => unknown);\n\n\t/**\n\t * The schema to use for validating the request headers.\n\t */\n\theaders?:\n\t\t| StandardSchemaV1<HeadersOption | undefined>\n\t\t| ((headers: HeadersOption) => Awaitable<HeadersOption>);\n\n\t/**\n\t * The schema to use for validating the meta option.\n\t */\n\tmeta?: StandardSchemaV1<GlobalMeta | undefined> | ((meta: GlobalMeta) => Awaitable<GlobalMeta>);\n\n\t/**\n\t * The schema to use for validating the request method.\n\t */\n\tmethod?: StandardSchemaV1<MethodUnion | undefined> | ((method: MethodUnion) => Awaitable<MethodUnion>);\n\n\t/**\n\t * The schema to use for validating the request url parameters.\n\t */\n\tparams?: StandardSchemaV1<Params | undefined> | ((params: Params) => Awaitable<Params>);\n\n\t/**\n\t * The schema to use for validating the request url queries.\n\t */\n\tquery?: StandardSchemaV1<Query | undefined> | ((query: Query) => Awaitable<Query>);\n}\n\nexport const routeKeyMethods = defineEnum([\"delete\", \"get\", \"patch\", \"post\", \"put\"]);\n\nexport type RouteKeyMethods = (typeof routeKeyMethods)[number];\n\ntype PossibleRouteKey = `@${RouteKeyMethods}/` | AnyString;\n\nexport type BaseCallApiSchema = Partial<Record<PossibleRouteKey, CallApiSchema>>;\n\nexport const defineSchema = <const TBaseSchema extends BaseCallApiSchema>(baseSchema: TBaseSchema) => {\n\treturn baseSchema as Writeable<typeof baseSchema, \"deep\">;\n};\n\ntype ValidationOptions<\n\tTSchema extends CallApiSchema[keyof CallApiSchema] = CallApiSchema[keyof CallApiSchema],\n> = {\n\tinputValue: InferSchemaInput<TSchema>;\n\tresponse?: Response | null;\n\tschemaConfig: CallApiSchemaConfig | undefined;\n};\n\nexport const handleValidation = async <TSchema extends CallApiSchema[keyof CallApiSchema]>(\n\tschema: TSchema | undefined,\n\tvalidationOptions: ValidationOptions<TSchema>\n): Promise<InferSchemaResult<TSchema>> => {\n\tconst { inputValue, response, schemaConfig } = validationOptions;\n\n\tif (!schema || schemaConfig?.disableRuntimeValidation) {\n\t\treturn inputValue as never;\n\t}\n\n\tconst validResult = await standardSchemaParser(schema, inputValue, response);\n\n\treturn validResult as never;\n};\n\ntype LastOf<TValue> =\n\tUnionToIntersection<TValue extends unknown ? () => TValue : never> extends () => infer R ? R : never;\n\ntype Push<TArray extends unknown[], TArrayItem> = [...TArray, TArrayItem];\n\ntype UnionToTuple<\n\tTUnion,\n\tTComputedLastUnion = LastOf<TUnion>,\n\tTComputedIsUnionEqualToNever = [TUnion] extends [never] ? true : false,\n> =\n\ttrue extends TComputedIsUnionEqualToNever ? []\n\t:\tPush<UnionToTuple<Exclude<TUnion, TComputedLastUnion>>, TComputedLastUnion>;\n\nexport type Tuple<TTuple, TArray extends TTuple[] = []> =\n\tUnionToTuple<TTuple>[\"length\"] extends TArray[\"length\"] ? [...TArray]\n\t:\tTuple<TTuple, [TTuple, ...TArray]>;\n\nconst extraOptionsToBeValidated = [\"meta\", \"params\", \"query\"] satisfies Tuple<\n\tExtract<keyof CallApiSchema, keyof CallApiExtraOptions>\n>;\n\ntype ExtraOptionsValidationOptions = {\n\textraOptions: CallApiExtraOptions;\n\tschema: CallApiSchema | undefined;\n\tschemaConfig: CallApiSchemaConfig | undefined;\n};\n\nconst handleExtraOptionsValidation = async (validationOptions: ExtraOptionsValidationOptions) => {\n\tconst { extraOptions, schema, schemaConfig } = validationOptions;\n\n\tconst validationResultArray = await Promise.all(\n\t\textraOptionsToBeValidated.map((propertyKey) =>\n\t\t\thandleValidation(schema?.[propertyKey], {\n\t\t\t\tinputValue: extraOptions[propertyKey],\n\t\t\t\tschemaConfig,\n\t\t\t})\n\t\t)\n\t);\n\n\tconst validatedResultObject: Prettify<\n\t\tPick<CallApiExtraOptions, (typeof extraOptionsToBeValidated)[number]>\n\t> = {};\n\n\tfor (const [index, propertyKey] of extraOptionsToBeValidated.entries()) {\n\t\tconst validationResult = validationResultArray[index];\n\n\t\tif (validationResult === undefined) continue;\n\n\t\tvalidatedResultObject[propertyKey] = validationResult as never;\n\t}\n\n\treturn validatedResultObject;\n};\n\nconst requestOptionsToBeValidated = [\"body\", \"headers\", \"method\"] satisfies Tuple<\n\tExtract<keyof CallApiSchema, keyof CallApiRequestOptions>\n>;\n\ntype RequestOptionsValidationOptions = {\n\trequestOptions: CallApiRequestOptions;\n\tschema: CallApiSchema | undefined;\n\tschemaConfig: CallApiSchemaConfig | undefined;\n};\n\nconst handleRequestOptionsValidation = async (validationOptions: RequestOptionsValidationOptions) => {\n\tconst { requestOptions, schema, schemaConfig } = validationOptions;\n\n\tconst validationResultArray = await Promise.all(\n\t\trequestOptionsToBeValidated.map((propertyKey) =>\n\t\t\thandleValidation(schema?.[propertyKey], {\n\t\t\t\tinputValue: requestOptions[propertyKey],\n\t\t\t\tschemaConfig,\n\t\t\t})\n\t\t)\n\t);\n\n\tconst validatedResultObject: Prettify<\n\t\tPick<CallApiRequestOptions, (typeof requestOptionsToBeValidated)[number]>\n\t> = {};\n\n\tfor (const [index, propertyKey] of requestOptionsToBeValidated.entries()) {\n\t\tconst validationResult = validationResultArray[index];\n\n\t\tif (validationResult === undefined) continue;\n\n\t\tvalidatedResultObject[propertyKey] = validationResult as never;\n\t}\n\n\treturn validatedResultObject;\n};\n\nexport const handleOptionsValidation = async (\n\tvalidationOptions: ExtraOptionsValidationOptions & RequestOptionsValidationOptions\n) => {\n\tconst { extraOptions, requestOptions, schema, schemaConfig } = validationOptions;\n\n\tif (schemaConfig?.disableRuntimeValidation) {\n\t\treturn {\n\t\t\textraOptionsValidationResult: null,\n\t\t\trequestOptionsValidationResult: null,\n\t\t};\n\t}\n\n\tconst [extraOptionsValidationResult, requestOptionsValidationResult] = await Promise.all([\n\t\thandleExtraOptionsValidation({ extraOptions, schema, schemaConfig }),\n\t\thandleRequestOptionsValidation({ requestOptions, schema, schemaConfig }),\n\t]);\n\n\treturn { extraOptionsValidationResult, requestOptionsValidationResult };\n};\n","import { requestOptionDefaults } from \"./constants/default-options\";\nimport type { CallApiExtraOptions, CallApiRequestOptions } from \"./types/common\";\nimport type { UnmaskType } from \"./types/type-helpers\";\nimport { toQueryString } from \"./utils\";\nimport { isArray } from \"./utils/guards\";\nimport { type CallApiSchemaConfig, routeKeyMethods } from \"./validation\";\n\nconst slash = \"/\";\nconst column = \":\";\nconst mergeUrlWithParams = (url: string, params: CallApiExtraOptions[\"params\"]) => {\n\tif (!params) {\n\t\treturn url;\n\t}\n\n\tlet newUrl = url;\n\n\tif (isArray(params)) {\n\t\tconst matchedParamArray = newUrl.split(slash).filter((param) => param.startsWith(column));\n\n\t\tfor (const [index, matchedParam] of matchedParamArray.entries()) {\n\t\t\tconst realParam = params[index] as string;\n\t\t\tnewUrl = newUrl.replace(matchedParam, realParam);\n\t\t}\n\n\t\treturn newUrl;\n\t}\n\n\tfor (const [key, value] of Object.entries(params)) {\n\t\tnewUrl = newUrl.replace(`${column}${key}`, String(value));\n\t}\n\n\treturn newUrl;\n};\n\nconst questionMark = \"?\";\nconst ampersand = \"&\";\nconst mergeUrlWithQuery = (url: string, query: CallApiExtraOptions[\"query\"]): string => {\n\tif (!query) {\n\t\treturn url;\n\t}\n\n\tconst queryString = toQueryString(query);\n\n\tif (queryString?.length === 0) {\n\t\treturn url;\n\t}\n\n\tif (url.endsWith(questionMark)) {\n\t\treturn `${url}${queryString}`;\n\t}\n\n\tif (url.includes(questionMark)) {\n\t\treturn `${url}${ampersand}${queryString}`;\n\t}\n\n\treturn `${url}${questionMark}${queryString}`;\n};\n\nexport const getCurrentRouteKey = (url: string, schemaConfig: CallApiSchemaConfig | undefined) => {\n\tlet currentRouteKey = url;\n\n\tif (schemaConfig?.baseURL && currentRouteKey.startsWith(schemaConfig.baseURL)) {\n\t\tcurrentRouteKey = currentRouteKey.replace(schemaConfig.baseURL, \"\");\n\t}\n\n\treturn currentRouteKey;\n};\n\n/**\n * @description\n * Extracts the method from the URL if it is a schema modifier.\n *\n * @param initURL - The URL to extract the method from.\n * @returns The method if it is a schema modifier, otherwise undefined.\n */\nexport const extractMethodFromURL = (initURL: string | undefined) => {\n\tif (!initURL?.startsWith(\"@\")) return;\n\n\tconst method = initURL.split(\"@\")[1]?.split(\"/\")[0];\n\n\tif (!method || !routeKeyMethods.includes(method)) return;\n\n\treturn method;\n};\n\nexport type GetMethodOptions = {\n\tinitURL: string | undefined;\n\tmethod: CallApiRequestOptions[\"method\"];\n\tschemaConfig?: CallApiSchemaConfig;\n};\n\nexport const getMethod = (options: GetMethodOptions) => {\n\tconst { initURL, method, schemaConfig } = options;\n\n\tif (schemaConfig?.requireHttpMethodProvision === true) {\n\t\treturn method?.toUpperCase() ?? requestOptionDefaults.method;\n\t}\n\n\treturn (\n\t\tmethod?.toUpperCase() ?? extractMethodFromURL(initURL)?.toUpperCase() ?? requestOptionDefaults.method\n\t);\n};\n\nexport const normalizeURL = (initURL: string) => {\n\tconst methodFromURL = extractMethodFromURL(initURL);\n\n\tif (!methodFromURL) {\n\t\treturn initURL;\n\t}\n\n\tconst normalizedURL = initURL.replace(`@${methodFromURL}/`, \"/\");\n\n\treturn normalizedURL;\n};\n\ntype GetFullURLOptions = {\n\tbaseURL: string | undefined;\n\tinitURL: string;\n\tparams: CallApiExtraOptions[\"params\"];\n\tquery: CallApiExtraOptions[\"query\"];\n};\n\nexport const getFullURL = (options: GetFullURLOptions) => {\n\tconst { baseURL, initURL, params, query } = options;\n\n\tconst normalizedURL = normalizeURL(initURL);\n\n\tconst urlWithMergedParams = mergeUrlWithParams(normalizedURL, params);\n\n\tconst urlWithMergedQueryAndParams = mergeUrlWithQuery(urlWithMergedParams, query);\n\n\tif (urlWithMergedQueryAndParams.startsWith(\"http\") || !baseURL) {\n\t\treturn urlWithMergedQueryAndParams;\n\t}\n\n\treturn `${baseURL}${urlWithMergedQueryAndParams}`;\n};\n\nexport type AllowedQueryParamValues = UnmaskType<boolean | number | string>;\n\nexport type Params = UnmaskType<\n\t// eslint-disable-next-line perfectionist/sort-union-types -- I need the Record to be first\n\tRecord<string, AllowedQueryParamValues> | AllowedQueryParamValues[]\n>;\n\nexport type Query = UnmaskType<Record<string, AllowedQueryParamValues>>;\n\nexport type InitURLOrURLObject = string | URL;\n\nexport interface URLOptions {\n\t/**\n\t * Base URL to be prepended to all request URLs\n\t */\n\tbaseURL?: string;\n\n\t/**\n\t * Resolved request URL\n\t */\n\treadonly fullURL?: string;\n\n\t/**\n\t * The url string passed to the callApi instance\n\t */\n\treadonly initURL?: string;\n\n\t/**\n\t * The URL string passed to the callApi instance, but normalized (removed any method modifiers etc)\n\t */\n\treadonly initURLNormalized?: string;\n\n\t/**\n\t * Parameters to be appended to the URL (i.e: /:id)\n\t */\n\tparams?: Params;\n\n\t/**\n\t * Query parameters to append to the URL.\n\t */\n\tquery?: Query;\n}\n","import { createDedupeStrategy, getAbortErrorMessage, type RequestInfoCache } from \"./dedupe\";\nimport { HTTPError } from \"./error\";\nimport {\n\ttype ErrorContext,\n\ttype ExecuteHookInfo,\n\texecuteHooksInCatchBlock,\n\texecuteHooksInTryBlock,\n\ttype RetryContext,\n\ttype SuccessContext,\n} from \"./hooks\";\nimport { type CallApiPlugin, initializePlugins } from \"./plugins\";\nimport {\n\ttype ErrorInfo,\n\tgetCustomizedErrorResult,\n\ttype ResponseTypeUnion,\n\ttype ResultModeUnion,\n\tresolveErrorResult,\n\tresolveResponseData,\n\tresolveSuccessResult,\n} from \"./result\";\nimport { createRetryStrategy } from \"./retry\";\nimport type { GetCurrentRouteKey, InferHeadersOption, InferInitURL, ThrowOnErrorUnion } from \"./types\";\nimport type {\n\tBaseCallApiConfig,\n\tBaseCallApiExtraOptions,\n\tCallApiExtraOptions,\n\tCallApiExtraOptionsForHooks,\n\tCallApiParameters,\n\tCallApiRequestOptions,\n\tCallApiRequestOptionsForHooks,\n\tCallApiResult,\n} from \"./types/common\";\nimport type { DefaultDataType, DefaultPluginArray, DefaultThrowOnError } from \"./types/default-types\";\nimport type { AnyFunction } from \"./types/type-helpers\";\nimport { getCurrentRouteKey, getFullURL, getMethod, normalizeURL } from \"./url\";\nimport {\n\tcreateCombinedSignal,\n\tcreateTimeoutSignal,\n\tgetBody,\n\tgetHeaders,\n\tsplitBaseConfig,\n\tsplitConfig,\n\twaitFor,\n} from \"./utils/common\";\nimport { isFunction, isHTTPErrorInstance, isValidationErrorInstance } from \"./utils/guards\";\nimport {\n\ttype BaseCallApiSchema,\n\ttype CallApiSchema,\n\ttype CallApiSchemaConfig,\n\thandleOptionsValidation,\n\thandleValidation,\n\ttype InferSchemaResult,\n} from \"./validation\";\n\nconst $GlobalRequestInfoCache: RequestInfoCache = new Map();\n\nexport const createFetchClient = <\n\tTBaseData = DefaultDataType,\n\tTBaseErrorData = DefaultDataType,\n\tTBaseResultMode extends ResultModeUnion = ResultModeUnion,\n\tTBaseThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError,\n\tTBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tconst TBaseSchema extends BaseCallApiSchema = BaseCallApiSchema,\n\tconst TBaseSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig,\n\tTBasePluginArray extends CallApiPlugin[] = DefaultPluginArray,\n>(\n\tinitBaseConfig: BaseCallApiConfig<\n\t\tTBaseData,\n\t\tTBaseErrorData,\n\t\tTBaseResultMode,\n\t\tTBaseThrowOnError,\n\t\tTBaseResponseType,\n\t\tTBaseSchema,\n\t\tTBaseSchemaConfig,\n\t\tTBasePluginArray\n\t> = {} as never\n) => {\n\tconst $LocalRequestInfoCache: RequestInfoCache = new Map();\n\n\tconst callApi = async <\n\t\tTData = TBaseData,\n\t\tTErrorData = TBaseErrorData,\n\t\tTResultMode extends ResultModeUnion = TBaseResultMode,\n\t\tTThrowOnError extends ThrowOnErrorUnion = TBaseThrowOnError,\n\t\tTResponseType extends ResponseTypeUnion = TBaseResponseType,\n\t\tTSchemaConfig extends CallApiSchemaConfig = TBaseSchemaConfig,\n\t\tTInitURL extends InferInitURL<TBaseSchema, TSchemaConfig> = InferInitURL<TBaseSchema, TSchemaConfig>,\n\t\tTCurrentRouteKey extends GetCurrentRouteKey<TSchemaConfig, TInitURL> = GetCurrentRouteKey<\n\t\t\tTSchemaConfig,\n\t\t\tTInitURL\n\t\t>,\n\t\tTSchema extends CallApiSchema = NonNullable<TBaseSchema[TCurrentRouteKey]>,\n\t\tTPluginArray extends CallApiPlugin[] = TBasePluginArray,\n\t>(\n\t\t...parameters: CallApiParameters<\n\t\t\tInferSchemaResult<TSchema[\"data\"], TData>,\n\t\t\tInferSchemaResult<TSchema[\"errorData\"], TErrorData>,\n\t\t\tTResultMode,\n\t\t\tTThrowOnError,\n\t\t\tTResponseType,\n\t\t\tTBaseSchema,\n\t\t\tTSchema,\n\t\t\tTBaseSchemaConfig,\n\t\t\tTSchemaConfig,\n\t\t\tTInitURL,\n\t\t\tTCurrentRouteKey,\n\t\t\tTBasePluginArray,\n\t\t\tTPluginArray\n\t\t>\n\t): CallApiResult<\n\t\tInferSchemaResult<TSchema[\"data\"], TData>,\n\t\tInferSchemaResult<TSchema[\"errorData\"], TErrorData>,\n\t\tTResultMode,\n\t\tTThrowOnError,\n\t\tTResponseType\n\t> => {\n\t\tconst [initURLOrURLObject, initConfig = {}] = parameters;\n\n\t\tconst [fetchOptions, extraOptions] = splitConfig(initConfig);\n\n\t\tconst resolvedBaseConfig =\n\t\t\tisFunction(initBaseConfig) ?\n\t\t\t\tinitBaseConfig({\n\t\t\t\t\tinitURL: initURLOrURLObject.toString(),\n\t\t\t\t\toptions: extraOptions,\n\t\t\t\t\trequest: fetchOptions,\n\t\t\t\t})\n\t\t\t:\tinitBaseConfig;\n\n\t\tconst baseConfig = resolvedBaseConfig as BaseCallApiExtraOptions & CallApiRequestOptions;\n\t\tconst config = initConfig as CallApiExtraOptions & CallApiRequestOptions;\n\n\t\tconst [baseFetchOptions, baseExtraOptions] = splitBaseConfig(baseConfig);\n\n\t\t// == Merged Extra Options\n\t\tconst mergedExtraOptions = {\n\t\t\t...baseExtraOptions,\n\t\t\t...(baseExtraOptions.skipAutoMergeFor !== \"all\"\n\t\t\t\t&& baseExtraOptions.skipAutoMergeFor !== \"options\"\n\t\t\t\t&& extraOptions),\n\t\t};\n\n\t\t// == Merged Request Options\n\t\tconst mergedRequestOptions = {\n\t\t\t...baseFetchOptions,\n\t\t\t...(baseExtraOptions.skipAutoMergeFor !== \"all\"\n\t\t\t\t&& baseExtraOptions.skipAutoMergeFor !== \"request\"\n\t\t\t\t&& fetchOptions),\n\t\t} satisfies CallApiRequestOptions;\n\n\t\tconst { resolvedHooks, resolvedInitURL, resolvedOptions, resolvedRequestOptions } =\n\t\t\tawait initializePlugins({\n\t\t\t\tbaseConfig,\n\t\t\t\tconfig,\n\t\t\t\tinitURL: initURLOrURLObject.toString(),\n\t\t\t\toptions: mergedExtraOptions as CallApiExtraOptionsForHooks,\n\t\t\t\trequest: mergedRequestOptions as CallApiRequestOptionsForHooks,\n\t\t\t});\n\n\t\tconst fullURL = getFullURL({\n\t\t\tbaseURL: resolvedOptions.baseURL,\n\t\t\tinitURL: resolvedInitURL,\n\t\t\tparams: resolvedOptions.params,\n\t\t\tquery: resolvedOptions.query,\n\t\t});\n\n\t\tconst resolvedSchemaConfig =\n\t\t\tisFunction(extraOptions.schemaConfig) ?\n\t\t\t\textraOptions.schemaConfig({ baseSchemaConfig: baseExtraOptions.schemaConfig ?? {} })\n\t\t\t:\t(extraOptions.schemaConfig ?? baseExtraOptions.schemaConfig);\n\n\t\tconst currentRouteKey = getCurrentRouteKey(resolvedInitURL, resolvedSchemaConfig);\n\n\t\tconst routeSchema = baseExtraOptions.schema?.[currentRouteKey];\n\n\t\tconst resolvedSchema =\n\t\t\tisFunction(extraOptions.schema) ?\n\t\t\t\textraOptions.schema({\n\t\t\t\t\tbaseSchema: baseExtraOptions.schema ?? {},\n\t\t\t\t\tcurrentRouteSchema: routeSchema ?? {},\n\t\t\t\t})\n\t\t\t:\t(extraOptions.schema ?? routeSchema);\n\n\t\tlet options = {\n\t\t\t...resolvedOptions,\n\t\t\t...resolvedHooks,\n\n\t\t\tfullURL,\n\t\t\tinitURL: resolvedInitURL,\n\t\t\tinitURLNormalized: normalizeURL(resolvedInitURL),\n\t\t} satisfies CallApiExtraOptionsForHooks;\n\n\t\tconst newFetchController = new AbortController();\n\n\t\tconst timeoutSignal = options.timeout != null ? createTimeoutSignal(options.timeout) : null;\n\n\t\tconst combinedSignal = createCombinedSignal(\n\t\t\tresolvedRequestOptions.signal,\n\t\t\ttimeoutSignal,\n\t\t\tnewFetchController.signal\n\t\t);\n\n\t\tlet request = {\n\t\t\t...resolvedRequestOptions,\n\t\t\t// == Making sure headers is always an object\n\t\t\t// eslint-disable-next-line ts-eslint/no-unnecessary-condition -- False positive\n\t\t\theaders: resolvedRequestOptions.headers ?? {},\n\n\t\t\tsignal: combinedSignal,\n\t\t} satisfies CallApiRequestOptionsForHooks;\n\n\t\tconst {\n\t\t\tdedupeStrategy,\n\t\t\thandleRequestCancelStrategy,\n\t\t\thandleRequestDeferStrategy,\n\t\t\tremoveDedupeKeyFromCache,\n\t\t} = await createDedupeStrategy({\n\t\t\t$GlobalRequestInfoCache,\n\t\t\t$LocalRequestInfoCache,\n\t\t\tbaseConfig,\n\t\t\tconfig,\n\t\t\tnewFetchController,\n\t\t\toptions,\n\t\t\trequest,\n\t\t});\n\n\t\ttry {\n\t\t\tawait handleRequestCancelStrategy();\n\n\t\t\tawait executeHooksInTryBlock(options.onRequest?.({ baseConfig, config, options, request }));\n\n\t\t\tconst { extraOptionsValidationResult, requestOptionsValidationResult } =\n\t\t\t\tawait handleOptionsValidation({\n\t\t\t\t\textraOptions: options,\n\t\t\t\t\trequestOptions: request,\n\t\t\t\t\tschema: resolvedSchema,\n\t\t\t\t\tschemaConfig: resolvedSchemaConfig,\n\t\t\t\t});\n\n\t\t\tconst shouldApplySchemaOutput =\n\t\t\t\tBoolean(extraOptionsValidationResult)\n\t\t\t\t|| Boolean(requestOptionsValidationResult)\n\t\t\t\t|| !resolvedSchemaConfig?.disableValidationOutputApplication;\n\n\t\t\t// == Apply Schema Output for Extra Options\n\t\t\tif (shouldApplySchemaOutput) {\n\t\t\t\toptions = {\n\t\t\t\t\t...options,\n\t\t\t\t\t...extraOptionsValidationResult,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// == Apply Schema Output for Request Options\n\t\t\tconst rawBody = shouldApplySchemaOutput ? requestOptionsValidationResult?.body : request.body;\n\n\t\t\tconst validBody = getBody({\n\t\t\t\tbody: rawBody,\n\t\t\t\tbodySerializer: options.bodySerializer,\n\t\t\t});\n\n\t\t\ttype HeaderFn = Extract<InferHeadersOption<CallApiSchema>[\"headers\"], AnyFunction>;\n\n\t\t\tconst resolvedHeaders =\n\t\t\t\tisFunction<HeaderFn>(fetchOptions.headers) ?\n\t\t\t\t\tfetchOptions.headers({ baseHeaders: baseFetchOptions.headers ?? {} })\n\t\t\t\t:\t(fetchOptions.headers ?? baseFetchOptions.headers);\n\n\t\t\tconst validHeaders = await getHeaders({\n\t\t\t\tauth: options.auth,\n\t\t\t\tbody: rawBody,\n\t\t\t\theaders: shouldApplySchemaOutput ? requestOptionsValidationResult?.headers : resolvedHeaders,\n\t\t\t});\n\n\t\t\tconst validMethod = getMethod({\n\t\t\t\tinitURL: resolvedInitURL,\n\t\t\t\tmethod: shouldApplySchemaOutput ? requestOptionsValidationResult?.method : request.method,\n\t\t\t\tschemaConfig: resolvedSchemaConfig,\n\t\t\t});\n\n\t\t\trequest = {\n\t\t\t\t...request,\n\t\t\t\t...(Boolean(validBody) && { body: validBody }),\n\t\t\t\t...(Boolean(validHeaders) && { headers: validHeaders }),\n\t\t\t\t...(Boolean(validMethod) && { method: validMethod }),\n\t\t\t};\n\n\t\t\tconst response = await handleRequestDeferStrategy({ options, request });\n\n\t\t\t// == Also clone response when dedupeStrategy is set to \"defer\" to avoid error thrown from reading response.(whatever) more than once\n\t\t\tconst shouldCloneResponse = dedupeStrategy === \"defer\" || options.cloneResponse;\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst errorData = await resolveResponseData<TErrorData>(\n\t\t\t\t\tshouldCloneResponse ? response.clone() : response,\n\t\t\t\t\toptions.responseType,\n\t\t\t\t\toptions.responseParser\n\t\t\t\t);\n\n\t\t\t\tconst validErrorData = await handleValidation(resolvedSchema?.errorData, {\n\t\t\t\t\tinputValue: errorData,\n\t\t\t\t\tresponse,\n\t\t\t\t\tschemaConfig: resolvedSchemaConfig,\n\t\t\t\t});\n\n\t\t\t\t// == Push all error handling responsibilities to the catch block if not retrying\n\t\t\t\tthrow new HTTPError(\n\t\t\t\t\t{\n\t\t\t\t\t\tdefaultErrorMessage: options.defaultErrorMessage,\n\t\t\t\t\t\terrorData: validErrorData,\n\t\t\t\t\t\tresponse,\n\t\t\t\t\t},\n\t\t\t\t\t{ cause: validErrorData }\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst successData = await resolveResponseData<TData>(\n\t\t\t\tshouldCloneResponse ? response.clone() : response,\n\t\t\t\toptions.responseType,\n\t\t\t\toptions.responseParser\n\t\t\t);\n\n\t\t\tconst validSuccessData = await handleValidation(resolvedSchema?.data, {\n\t\t\t\tinputValue: successData,\n\t\t\t\tresponse,\n\t\t\t\tschemaConfig: resolvedSchemaConfig,\n\t\t\t});\n\n\t\t\tconst successContext = {\n\t\t\t\tbaseConfig,\n\t\t\t\tconfig,\n\t\t\t\tdata: validSuccessData,\n\t\t\t\toptions,\n\t\t\t\trequest,\n\t\t\t\tresponse,\n\t\t\t} satisfies SuccessContext<unknown>;\n\n\t\t\tawait executeHooksInTryBlock(\n\t\t\t\toptions.onSuccess?.(successContext),\n\n\t\t\t\toptions.onResponse?.({ ...successContext, error: null })\n\t\t\t);\n\n\t\t\tconst successResult = resolveSuccessResult(successContext.data, {\n\t\t\t\tresponse: successContext.response,\n\t\t\t\tresultMode: options.resultMode,\n\t\t\t});\n\n\t\t\treturn successResult as never;\n\n\t\t\t// == Exhaustive Error handling\n\t\t} catch (error) {\n\t\t\tconst errorInfo = {\n\t\t\t\tcloneResponse: options.cloneResponse,\n\t\t\t\tdefaultErrorMessage: options.defaultErrorMessage,\n\t\t\t\tresultMode: options.resultMode,\n\t\t\t} satisfies ErrorInfo;\n\n\t\t\tconst generalErrorResult = resolveErrorResult(error, errorInfo);\n\n\t\t\tconst errorContext = {\n\t\t\t\tbaseConfig,\n\t\t\t\tconfig,\n\t\t\t\terror: generalErrorResult?.error as never,\n\t\t\t\toptions,\n\t\t\t\trequest,\n\t\t\t\tresponse: generalErrorResult?.response as never,\n\t\t\t} satisfies ErrorContext<unknown>;\n\n\t\t\tconst shouldThrowOnError = (\n\t\t\t\tisFunction(options.throwOnError) ?\n\t\t\t\t\toptions.throwOnError(errorContext)\n\t\t\t\t:\toptions.throwOnError) as boolean;\n\n\t\t\tconst hookInfo = {\n\t\t\t\terrorInfo,\n\t\t\t\tshouldThrowOnError,\n\t\t\t} satisfies ExecuteHookInfo;\n\n\t\t\tconst handleRetryOrGetErrorResult = async () => {\n\t\t\t\tconst { currentAttemptCount, getDelay, shouldAttemptRetry } =\n\t\t\t\t\tcreateRetryStrategy(errorContext);\n\n\t\t\t\tconst shouldRetry = !combinedSignal.aborted && (await shouldAttemptRetry());\n\n\t\t\t\tif (shouldRetry) {\n\t\t\t\t\tconst retryContext = {\n\t\t\t\t\t\t...errorContext,\n\t\t\t\t\t\tretryAttemptCount: currentAttemptCount,\n\t\t\t\t\t} satisfies RetryContext<unknown>;\n\n\t\t\t\t\tconst hookError = await executeHooksInCatchBlock(\n\t\t\t\t\t\t[options.onRetry?.(retryContext)],\n\t\t\t\t\t\thookInfo\n\t\t\t\t\t);\n\n\t\t\t\t\tif (hookError) {\n\t\t\t\t\t\treturn hookError;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst delay = getDelay();\n\n\t\t\t\t\tawait waitFor(delay);\n\n\t\t\t\t\tconst updatedOptions = {\n\t\t\t\t\t\t...config,\n\t\t\t\t\t\t\"~retryAttemptCount\": currentAttemptCount + 1,\n\t\t\t\t\t} satisfies typeof config;\n\n\t\t\t\t\treturn callApi(initURLOrURLObject as never, updatedOptions as never) as never;\n\t\t\t\t}\n\n\t\t\t\tif (shouldThrowOnError) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\n\t\t\t\treturn generalErrorResult;\n\t\t\t};\n\n\t\t\tif (isHTTPErrorInstance<TErrorData>(error)) {\n\t\t\t\tconst hookError = await executeHooksInCatchBlock(\n\t\t\t\t\t[\n\t\t\t\t\t\toptions.onResponseError?.(errorContext),\n\t\t\t\t\t\toptions.onError?.(errorContext),\n\t\t\t\t\t\toptions.onResponse?.({ ...errorContext, data: null }),\n\t\t\t\t\t],\n\t\t\t\t\thookInfo\n\t\t\t\t);\n\n\t\t\t\treturn (hookError ?? (await handleRetryOrGetErrorResult())) as never;\n\t\t\t}\n\n\t\t\tif (isValidationErrorInstance(error)) {\n\t\t\t\tconst hookError = await executeHooksInCatchBlock(\n\t\t\t\t\t[\n\t\t\t\t\t\toptions.onValidationError?.(errorContext),\n\t\t\t\t\t\toptions.onRequestError?.(errorContext),\n\t\t\t\t\t\toptions.onError?.(errorContext),\n\t\t\t\t\t],\n\t\t\t\t\thookInfo\n\t\t\t\t);\n\n\t\t\t\treturn (hookError ?? (await handleRetryOrGetErrorResult())) as never;\n\t\t\t}\n\n\t\t\tlet message: string | undefined = (error as Error | undefined)?.message;\n\n\t\t\tif (error instanceof DOMException && error.name === \"AbortError\") {\n\t\t\t\tmessage = getAbortErrorMessage(options.dedupeKey, options.fullURL);\n\n\t\t\t\t!shouldThrowOnError && console.error(`${error.name}:`, message);\n\t\t\t}\n\n\t\t\tif (error instanceof DOMException && error.name === \"TimeoutError\") {\n\t\t\t\tmessage = `Request timed out after ${options.timeout}ms`;\n\n\t\t\t\t!shouldThrowOnError && console.error(`${error.name}:`, message);\n\t\t\t}\n\n\t\t\tconst hookError = await executeHooksInCatchBlock(\n\t\t\t\t[options.onRequestError?.(errorContext), options.onError?.(errorContext)],\n\t\t\t\thookInfo\n\t\t\t);\n\n\t\t\treturn (hookError\n\t\t\t\t?? getCustomizedErrorResult(await handleRetryOrGetErrorResult(), { message })) as never;\n\n\t\t\t// == Removing the now unneeded AbortController from store\n\t\t} finally {\n\t\t\tremoveDedupeKeyFromCache();\n\t\t}\n\t};\n\n\treturn callApi;\n};\n\nexport const callApi = createFetchClient();\n","import type { CallApiPlugin } from \"./plugins\";\nimport type { ResponseTypeUnion, ResultModeUnion } from \"./result\";\nimport type { CallApiParameters, InferInitURL, ThrowOnErrorUnion } from \"./types\";\nimport type { DefaultDataType, DefaultPluginArray, DefaultThrowOnError } from \"./types/default-types\";\nimport type { BaseCallApiSchema, CallApiSchema, CallApiSchemaConfig } from \"./validation\";\n\nconst defineParameters = <\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTBaseSchema extends BaseCallApiSchema = BaseCallApiSchema,\n\tTSchema extends CallApiSchema = CallApiSchema,\n\tTBaseSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig,\n\tTSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig,\n\tTInitURL extends InferInitURL<BaseCallApiSchema, TSchemaConfig> = InferInitURL<\n\t\tBaseCallApiSchema,\n\t\tTSchemaConfig\n\t>,\n\tTCurrentRouteKey extends string = string,\n\tTBasePluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTPluginArray extends CallApiPlugin[] = DefaultPluginArray,\n>(\n\t...parameters: CallApiParameters<\n\t\tTData,\n\t\tTErrorData,\n\t\tTResultMode,\n\t\tTThrowOnError,\n\t\tTResponseType,\n\t\tTBaseSchema,\n\t\tTSchema,\n\t\tTBaseSchemaConfig,\n\t\tTSchemaConfig,\n\t\tTInitURL,\n\t\tTCurrentRouteKey,\n\t\tTBasePluginArray,\n\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"version":3,"file":"index.js","names":["response: Response","parser: Parser","responseType?: ResponseTypeUnion","parser?: Parser","details: CallApiResultErrorVariant<unknown> | CallApiResultSuccessVariant<unknown>","data: unknown","info: SuccessInfo","error: unknown","info: ErrorInfo","errorResult: ErrorResult","customErrorInfo: { message: string | undefined }","hooksArray: Array<AnyFunction | undefined>","mergedHooksExecutionMode: CallApiExtraOptionsForHooks[\"mergedHooksExecutionMode\"]","ctx: unknown","hookResultsOrPromise: Array<Awaitable<unknown>>","hookInfo: ExecuteHookInfo","options: {\n\tchunk: Uint8Array;\n\ttotalBytes: number;\n\ttransferredBytes: number;\n}","requestBody: Request[\"body\"] | null","existingTotalBytes: number","context: ToStreamableRequestContext","context: StreamableResponseContext","dedupeKey: DedupeOptions[\"dedupeKey\"]","fullURL: DedupeContext[\"options\"][\"fullURL\"]","context: DedupeContext","$GlobalRequestInfoCache","deferContext: {\n\t\toptions: DedupeContext[\"options\"];\n\t\trequest: DedupeContext[\"request\"];\n\t}","plugin: TPlugin","context: PluginInitContext","pluginHooks: Required<CallApiPlugin>[\"hooks\"]","pluginInit: CallApiPlugin[\"init\"]","resolvedHooks: Hooks","currentAttemptCount: number","options: RetryOptions<unknown>","ctx: ErrorContext<unknown> & RequestContext","validator: Extract<CallApiSchema[keyof CallApiSchema], AnyFunction>","inputData: TInput","schema: TSchema","inputData: InferSchemaInput<TSchema>","response?: Response | null","baseSchema: TBaseSchema","schema: TSchema | undefined","validationOptions: ValidationOptions<TSchema>","validationOptions: ExtraOptionsValidationOptions","validatedResultObject: Prettify<\n\t\tPick<CallApiExtraOptions, (typeof extraOptionsToBeValidated)[number]>\n\t>","validationOptions: RequestOptionsValidationOptions","validatedResultObject: Prettify<\n\t\tPick<CallApiRequestOptions, (typeof requestOptionsToBeValidated)[number]>\n\t>","validationOptions: ExtraOptionsValidationOptions & RequestOptionsValidationOptions","url: string","params: CallApiExtraOptions[\"params\"]","query: CallApiExtraOptions[\"query\"]","schemaConfig: CallApiSchemaConfig | undefined","initURL: string | undefined","options: GetMethodOptions","initURL: string","options: GetFullURLOptions","$GlobalRequestInfoCache: RequestInfoCache","initBaseConfig: BaseCallApiConfig<\n\t\tTBaseData,\n\t\tTBaseErrorData,\n\t\tTBaseResultMode,\n\t\tTBaseThrowOnError,\n\t\tTBaseResponseType,\n\t\tTBaseSchema,\n\t\tTBaseSchemaConfig,\n\t\tTBasePluginArray\n\t>","$LocalRequestInfoCache: RequestInfoCache","callApi","hookError","message: string | undefined"],"sources":["../../src/result.ts","../../src/hooks.ts","../../src/stream.ts","../../src/dedupe.ts","../../src/plugins.ts","../../src/retry.ts","../../src/validation.ts","../../src/url.ts","../../src/createFetchClient.ts","../../src/defineParameters.ts"],"sourcesContent":["import { responseDefaults } from \"./constants/default-options\";\nimport type { HTTPError, ValidationError } from \"./error\";\nimport type { CallApiExtraOptions, ThrowOnErrorUnion } from \"./types\";\nimport type { DefaultDataType } from \"./types/default-types\";\nimport type { AnyString, Awaitable, UnmaskType } from \"./types/type-helpers\";\nimport { isHTTPErrorInstance, isValidationErrorInstance } from \"./utils/guards\";\n\ntype Parser = (responseString: string) => Awaitable<Record<string, unknown>>;\n\nexport const getResponseType = <TResponse>(response: Response, parser: Parser) => ({\n\tarrayBuffer: () => response.arrayBuffer(),\n\tblob: () => response.blob(),\n\tformData: () => response.formData(),\n\tjson: async () => {\n\t\tconst text = await response.text();\n\t\treturn parser(text) as TResponse;\n\t},\n\tstream: () => response.body,\n\ttext: () => response.text(),\n});\n\ntype InitResponseTypeMap<TResponse = unknown> = ReturnType<typeof getResponseType<TResponse>>;\n\nexport type ResponseTypeUnion = keyof InitResponseTypeMap | null;\n\nexport type ResponseTypeMap<TResponse> = {\n\t[Key in keyof InitResponseTypeMap<TResponse>]: Awaited<ReturnType<InitResponseTypeMap<TResponse>[Key]>>;\n};\n\nexport type GetResponseType<\n\tTResponse,\n\tTResponseType extends ResponseTypeUnion,\n\tTComputedResponseTypeMap extends ResponseTypeMap<TResponse> = ResponseTypeMap<TResponse>,\n> =\n\tnull extends TResponseType ? TComputedResponseTypeMap[\"json\"]\n\t: TResponseType extends NonNullable<ResponseTypeUnion> ? TComputedResponseTypeMap[TResponseType]\n\t: never;\n\nexport const resolveResponseData = <TResponse>(\n\tresponse: Response,\n\tresponseType?: ResponseTypeUnion,\n\tparser?: Parser\n) => {\n\tconst selectedParser = parser ?? responseDefaults.responseParser;\n\tconst selectedResponseType = responseType ?? responseDefaults.responseType;\n\n\tconst RESPONSE_TYPE_LOOKUP = getResponseType<TResponse>(response, selectedParser);\n\n\tif (!Object.hasOwn(RESPONSE_TYPE_LOOKUP, selectedResponseType)) {\n\t\tthrow new Error(`Invalid response type: ${responseType}`);\n\t}\n\n\treturn RESPONSE_TYPE_LOOKUP[selectedResponseType]();\n};\n\nexport type CallApiResultSuccessVariant<TData> = {\n\tdata: NoInfer<TData>;\n\terror: null;\n\tresponse: Response;\n};\n\nexport type PossibleJavaScriptError = UnmaskType<{\n\terrorData: false;\n\tmessage: string;\n\tname: \"AbortError\" | \"Error\" | \"SyntaxError\" | \"TimeoutError\" | \"TypeError\" | AnyString;\n\toriginalError: DOMException | Error | SyntaxError | TypeError;\n}>;\n\nexport type PossibleHTTPError<TErrorData> = UnmaskType<{\n\terrorData: NoInfer<TErrorData>;\n\tmessage: string;\n\tname: \"HTTPError\";\n\toriginalError: HTTPError;\n}>;\n\nexport type PossibleValidationError = UnmaskType<{\n\terrorData: ValidationError[\"errorData\"];\n\tmessage: string;\n\tname: \"ValidationError\";\n\toriginalError: ValidationError;\n}>;\n\nexport type PossibleJavaScriptOrValidationError = UnmaskType<\n\tPossibleJavaScriptError | PossibleValidationError\n>;\n\nexport type CallApiResultErrorVariant<TErrorData> =\n\t| {\n\t\t\tdata: null;\n\t\t\terror: PossibleHTTPError<TErrorData>;\n\t\t\tresponse: Response;\n\t }\n\t| {\n\t\t\tdata: null;\n\t\t\terror: PossibleJavaScriptOrValidationError;\n\t\t\tresponse: Response | null;\n\t };\n\nexport type ResultModeMap<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTComputedData = GetResponseType<TData, TResponseType>,\n\tTComputedErrorData = GetResponseType<TErrorData, TResponseType>,\n> = UnmaskType<{\n\t/* eslint-disable perfectionist/sort-union-types -- I need the first one to be first */\n\tall: CallApiResultSuccessVariant<TComputedData> | CallApiResultErrorVariant<TComputedErrorData>;\n\n\tallWithException: CallApiResultSuccessVariant<TComputedData>;\n\n\tonlySuccess:\n\t\t| CallApiResultErrorVariant<TComputedErrorData>[\"data\"]\n\t\t| CallApiResultSuccessVariant<TComputedData>[\"data\"];\n\n\tonlySuccessWithException: CallApiResultSuccessVariant<TComputedData>[\"data\"];\n\t/* eslint-enable perfectionist/sort-union-types -- I need the first one to be first */\n}>;\n\nexport type ResultModeUnion = keyof ResultModeMap | null;\n\nexport type GetCallApiResult<\n\tTData,\n\tTErrorData,\n\tTResultMode extends ResultModeUnion,\n\tTThrowOnError extends ThrowOnErrorUnion,\n\tTResponseType extends ResponseTypeUnion,\n> =\n\tTErrorData extends false ? ResultModeMap<TData, TErrorData, TResponseType>[\"onlySuccessWithException\"]\n\t: TErrorData extends false | undefined ?\n\t\tResultModeMap<TData, TErrorData, TResponseType>[\"onlySuccessWithException\"]\n\t: TErrorData extends false | null ? ResultModeMap<TData, TErrorData, TResponseType>[\"onlySuccess\"]\n\t: null extends TResultMode ?\n\t\tTThrowOnError extends true ?\n\t\t\tResultModeMap<TData, TErrorData, TResponseType>[\"allWithException\"]\n\t\t:\tResultModeMap<TData, TErrorData, TResponseType>[\"all\"]\n\t: TResultMode extends NonNullable<ResultModeUnion> ?\n\t\tResultModeMap<TData, TErrorData, TResponseType>[TResultMode]\n\t:\tnever;\n\ntype SuccessInfo = {\n\tresponse: Response;\n\tresultMode: CallApiExtraOptions[\"resultMode\"];\n};\n\ntype LazyResultModeMap = {\n\t[key in keyof ResultModeMap]: () => ResultModeMap[key];\n};\n\nconst getResultModeMap = (\n\tdetails: CallApiResultErrorVariant<unknown> | CallApiResultSuccessVariant<unknown>\n) => {\n\tconst resultModeMap = {\n\t\tall: () => details,\n\t\tallWithException: () => resultModeMap.all() as never,\n\t\tonlySuccess: () => details.data,\n\t\tonlySuccessWithException: () => resultModeMap.onlySuccess(),\n\t} satisfies LazyResultModeMap as LazyResultModeMap;\n\n\treturn resultModeMap;\n};\n\ntype SuccessResult = CallApiResultSuccessVariant<unknown> | null;\n\n// == The CallApiResult type is used to cast all return statements due to a design limitation in ts.\n// LINK - See https://www.zhenghao.io/posts/type-functions for more info\nexport const resolveSuccessResult = (data: unknown, info: SuccessInfo): SuccessResult => {\n\tconst { response, resultMode } = info;\n\n\tconst details = {\n\t\tdata,\n\t\terror: null,\n\t\tresponse,\n\t} satisfies CallApiResultSuccessVariant<unknown>;\n\n\tconst resultModeMap = getResultModeMap(details);\n\n\tconst successResult = resultModeMap[resultMode ?? \"all\"]();\n\n\treturn successResult as SuccessResult;\n};\n\nexport type ErrorInfo = {\n\tcloneResponse: CallApiExtraOptions[\"cloneResponse\"];\n\tmessage?: string;\n\tresultMode: CallApiExtraOptions[\"resultMode\"];\n};\n\ntype ErrorResult = CallApiResultErrorVariant<unknown> | null;\n\nexport const resolveErrorResult = (error: unknown, info: ErrorInfo): ErrorResult => {\n\tconst { cloneResponse, message: customErrorMessage, resultMode } = info;\n\n\tlet details = {\n\t\tdata: null,\n\t\terror: {\n\t\t\terrorData: false,\n\t\t\tmessage: customErrorMessage ?? (error as Error).message,\n\t\t\tname: (error as Error).name,\n\t\t\toriginalError: error as Error,\n\t\t},\n\t\tresponse: null,\n\t} satisfies CallApiResultErrorVariant<unknown> as CallApiResultErrorVariant<unknown>;\n\n\tif (isValidationErrorInstance(error)) {\n\t\tconst { errorData, message, response } = error;\n\n\t\tdetails = {\n\t\t\tdata: null,\n\t\t\terror: { errorData, message, name: \"ValidationError\", originalError: error },\n\t\t\tresponse,\n\t\t};\n\t}\n\n\tif (isHTTPErrorInstance<never>(error)) {\n\t\tconst { errorData, message, name, response } = error;\n\n\t\tdetails = {\n\t\t\tdata: null,\n\t\t\terror: { errorData, message, name, originalError: error },\n\t\t\tresponse: cloneResponse ? response.clone() : response,\n\t\t};\n\t}\n\n\tconst resultModeMap = getResultModeMap(details);\n\n\tconst errorResult = resultModeMap[resultMode ?? \"all\"]();\n\n\treturn errorResult as ErrorResult;\n};\n\nexport const getCustomizedErrorResult = (\n\terrorResult: ErrorResult,\n\tcustomErrorInfo: { message: string | undefined }\n): ErrorResult => {\n\tif (!errorResult) {\n\t\treturn null;\n\t}\n\n\tconst { message = errorResult.error.message } = customErrorInfo;\n\n\treturn {\n\t\t...errorResult,\n\t\terror: {\n\t\t\t...errorResult.error,\n\t\t\tmessage,\n\t\t} satisfies NonNullable<ErrorResult>[\"error\"] as never,\n\t};\n};\n","import type { ValidationError } from \"./error\";\nimport {\n\ttype CallApiResultErrorVariant,\n\ttype CallApiResultSuccessVariant,\n\ttype ErrorInfo,\n\ttype PossibleHTTPError,\n\ttype PossibleJavaScriptOrValidationError,\n\tresolveErrorResult,\n} from \"./result\";\nimport type { StreamProgressEvent } from \"./stream\";\nimport type {\n\tBaseCallApiExtraOptions,\n\tCallApiExtraOptions,\n\tCallApiExtraOptionsForHooks,\n\tCallApiRequestOptions,\n\tCallApiRequestOptionsForHooks,\n} from \"./types/common\";\nimport type { DefaultDataType } from \"./types/default-types\";\nimport type { AnyFunction, Awaitable, Prettify, UnmaskType } from \"./types/type-helpers\";\n\nexport type PluginExtraOptions<TPluginOptions = unknown> = {\n\toptions: Partial<TPluginOptions>;\n};\n\n/* eslint-disable perfectionist/sort-intersection-types -- Plugin options should come last */\nexport interface Hooks<TData = DefaultDataType, TErrorData = DefaultDataType, TPluginOptions = unknown> {\n\t/**\n\t * Hook that will be called when any error occurs within the request/response lifecycle, regardless of whether the error is from the api or not.\n\t * It is basically a combination of `onRequestError` and `onResponseError` hooks\n\t */\n\tonError?: (\n\t\tcontext: ErrorContext<TErrorData> & PluginExtraOptions<TPluginOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called just before the request is being made.\n\t */\n\tonRequest?: (context: RequestContext & PluginExtraOptions<TPluginOptions>) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when an error occurs during the fetch request.\n\t */\n\tonRequestError?: (\n\t\tcontext: RequestErrorContext & PluginExtraOptions<TPluginOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when upload stream progress is tracked\n\t */\n\tonRequestStream?: (\n\t\tcontext: RequestStreamContext & PluginExtraOptions<TPluginOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when any response is received from the api, whether successful or not\n\t */\n\tonResponse?: (\n\t\tcontext: ResponseContext<TData, TErrorData> & PluginExtraOptions<TPluginOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when an error response is received from the api.\n\t */\n\tonResponseError?: (\n\t\tcontext: ResponseErrorContext<TErrorData> & PluginExtraOptions<TPluginOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when download stream progress is tracked\n\t */\n\tonResponseStream?: (\n\t\tcontext: ResponseStreamContext & PluginExtraOptions<TPluginOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when a request is retried.\n\t */\n\tonRetry?: (\n\t\tresponse: RetryContext<TErrorData> & PluginExtraOptions<TPluginOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when a successful response is received from the api.\n\t */\n\tonSuccess?: (context: SuccessContext<TData> & PluginExtraOptions<TPluginOptions>) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when a validation error occurs.\n\t */\n\tonValidationError?: (\n\t\tcontext: ValidationErrorContext & PluginExtraOptions<TPluginOptions>\n\t) => Awaitable<unknown>;\n}\n/* eslint-enable perfectionist/sort-intersection-types -- Plugin options should come last */\n\nexport type HooksOrHooksArray<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTMoreOptions = unknown,\n> = {\n\t[Key in keyof Hooks<TData, TErrorData, TMoreOptions>]:\n\t\t| Hooks<TData, TErrorData, TMoreOptions>[Key]\n\t\t// eslint-disable-next-line perfectionist/sort-union-types -- I need arrays to be last\n\t\t| Array<Hooks<TData, TErrorData, TMoreOptions>[Key]>;\n};\n\nexport type RequestContext = {\n\t/**\n\t * Config object passed to createFetchClient\n\t */\n\tbaseConfig: BaseCallApiExtraOptions & CallApiRequestOptions;\n\t/**\n\t * Config object passed to the callApi instance\n\t */\n\tconfig: CallApiExtraOptions & CallApiRequestOptions;\n\t/**\n\t * Merged options consisting of extra options from createFetchClient, the callApi instance and default options.\n\t *\n\t */\n\toptions: CallApiExtraOptionsForHooks;\n\t/**\n\t * Merged request consisting of request options from createFetchClient, the callApi instance and default request options.\n\t */\n\trequest: CallApiRequestOptionsForHooks;\n};\n\nexport type ValidationErrorContext = UnmaskType<\n\tRequestContext & {\n\t\terror: ValidationError;\n\t\tresponse: Response | null;\n\t}\n>;\n\nexport type SuccessContext<TData> = UnmaskType<\n\tRequestContext & {\n\t\tdata: TData;\n\t\tresponse: Response;\n\t}\n>;\n\nexport type ResponseContext<TData, TErrorData> = UnmaskType<\n\tRequestContext\n\t\t& (\n\t\t\t| Prettify<CallApiResultSuccessVariant<TData>>\n\t\t\t| Prettify<\n\t\t\t\t\tExtract<CallApiResultErrorVariant<TErrorData>, { error: PossibleHTTPError<TErrorData> }>\n\t\t\t >\n\t\t)\n>;\n\nexport type RequestErrorContext = RequestContext & {\n\terror: PossibleJavaScriptOrValidationError;\n\tresponse: null;\n};\n\nexport type ErrorContext<TErrorData> = UnmaskType<\n\tRequestContext\n\t\t& (\n\t\t\t| {\n\t\t\t\t\terror: PossibleHTTPError<TErrorData>;\n\t\t\t\t\tresponse: Response;\n\t\t\t }\n\t\t\t| {\n\t\t\t\t\terror: PossibleJavaScriptOrValidationError;\n\t\t\t\t\tresponse: Response | null;\n\t\t\t }\n\t\t)\n>;\n\nexport type ResponseErrorContext<TErrorData> = UnmaskType<\n\tExtract<ErrorContext<TErrorData>, { error: PossibleHTTPError<TErrorData> }> & RequestContext\n>;\n\nexport type RetryContext<TErrorData> = UnmaskType<\n\tErrorContext<TErrorData> & { retryAttemptCount: number }\n>;\n\nexport type RequestStreamContext = UnmaskType<\n\tRequestContext & {\n\t\tevent: StreamProgressEvent;\n\t\trequestInstance: Request;\n\t}\n>;\n\nexport type ResponseStreamContext = UnmaskType<\n\tRequestContext & {\n\t\tevent: StreamProgressEvent;\n\t\tresponse: Response;\n\t}\n>;\n\ntype HookRegistries = Required<{\n\t[Key in keyof Hooks]: Set<Hooks[Key]>;\n}>;\n\nexport const hookRegistries = {\n\tonError: new Set(),\n\tonRequest: new Set(),\n\tonRequestError: new Set(),\n\tonRequestStream: new Set(),\n\tonResponse: new Set(),\n\tonResponseError: new Set(),\n\tonResponseStream: new Set(),\n\tonRetry: new Set(),\n\tonSuccess: new Set(),\n\tonValidationError: new Set(),\n} satisfies HookRegistries;\n\nexport const composeAllHooks = (\n\thooksArray: Array<AnyFunction | undefined>,\n\tmergedHooksExecutionMode: CallApiExtraOptionsForHooks[\"mergedHooksExecutionMode\"]\n) => {\n\tconst mergedHook = async (ctx: unknown) => {\n\t\tif (mergedHooksExecutionMode === \"sequential\") {\n\t\t\tfor (const hook of hooksArray) {\n\t\t\t\t// eslint-disable-next-line no-await-in-loop -- This is necessary in this case\n\t\t\t\tawait hook?.(ctx);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif (mergedHooksExecutionMode === \"parallel\") {\n\t\t\tawait Promise.all(hooksArray.map((uniqueHook) => uniqueHook?.(ctx)));\n\t\t}\n\t};\n\n\treturn mergedHook;\n};\n\nexport const executeHooksInTryBlock = async (...hookResultsOrPromise: Array<Awaitable<unknown>>) => {\n\tawait Promise.all(hookResultsOrPromise);\n};\n\nexport type ExecuteHookInfo = {\n\terrorInfo: ErrorInfo;\n\tshouldThrowOnError: boolean | undefined;\n};\n\nexport const executeHooksInCatchBlock = async (\n\thookResultsOrPromise: Array<Awaitable<unknown>>,\n\thookInfo: ExecuteHookInfo\n) => {\n\tconst { errorInfo, shouldThrowOnError } = hookInfo;\n\n\ttry {\n\t\tawait Promise.all(hookResultsOrPromise);\n\n\t\treturn null;\n\t} catch (hookError) {\n\t\tconst hookErrorResult = resolveErrorResult(hookError, errorInfo);\n\n\t\tif (shouldThrowOnError) {\n\t\t\tthrow hookError;\n\t\t}\n\n\t\treturn hookErrorResult;\n\t}\n};\n","import {\n\texecuteHooksInTryBlock,\n\ttype RequestContext,\n\ttype RequestStreamContext,\n\ttype ResponseStreamContext,\n} from \"./hooks\";\nimport { isObject, isReadableStream } from \"./utils/guards\";\n\nexport type StreamProgressEvent = {\n\t/**\n\t * Current chunk of data being streamed\n\t */\n\tchunk: Uint8Array;\n\t/**\n\t * Progress in percentage\n\t */\n\tprogress: number;\n\t/**\n\t * Total size of data in bytes\n\t */\n\ttotalBytes: number;\n\t/**\n\t * Amount of data transferred so far\n\t */\n\ttransferredBytes: number;\n};\n\ndeclare global {\n\tinterface ReadableStream<R> {\n\t\t[Symbol.asyncIterator]: () => AsyncIterableIterator<R>;\n\t}\n}\n\nconst createProgressEvent = (options: {\n\tchunk: Uint8Array;\n\ttotalBytes: number;\n\ttransferredBytes: number;\n}): StreamProgressEvent => {\n\tconst { chunk, totalBytes, transferredBytes } = options;\n\n\treturn {\n\t\tchunk,\n\t\tprogress: Math.round((transferredBytes / totalBytes) * 100) || 0,\n\t\ttotalBytes,\n\t\ttransferredBytes,\n\t};\n};\n\nconst calculateTotalBytesFromBody = async (\n\trequestBody: Request[\"body\"] | null,\n\texistingTotalBytes: number\n) => {\n\tlet totalBytes = existingTotalBytes;\n\n\tif (!requestBody) {\n\t\treturn totalBytes;\n\t}\n\n\tfor await (const chunk of requestBody) {\n\t\ttotalBytes += chunk.byteLength;\n\t}\n\n\treturn totalBytes;\n};\n\ntype ToStreamableRequestContext = RequestContext;\n\nexport const toStreamableRequest = async (\n\tcontext: ToStreamableRequestContext\n): Promise<Request | RequestInit> => {\n\tconst { baseConfig, config, options, request } = context;\n\n\tif (!options.onRequestStream || !isReadableStream(request.body)) {\n\t\treturn request as RequestInit;\n\t}\n\n\tconst requestInstance = new Request(\n\t\toptions.fullURL as NonNullable<typeof options.fullURL>,\n\t\t{ ...request, duplex: \"half\" } as RequestInit\n\t);\n\n\tconst contentLength = requestInstance.headers.get(\"content-length\");\n\n\tlet totalBytes = Number(contentLength ?? 0);\n\n\tconst shouldForcefullyCalcStreamSize =\n\t\tisObject(options.forcefullyCalculateStreamSize) ?\n\t\t\toptions.forcefullyCalculateStreamSize.request\n\t\t:\toptions.forcefullyCalculateStreamSize;\n\n\t// == If no content length is present, we read the total bytes from the body\n\tif (!contentLength && shouldForcefullyCalcStreamSize) {\n\t\ttotalBytes = await calculateTotalBytesFromBody(requestInstance.clone().body, totalBytes);\n\t}\n\n\tlet transferredBytes = 0;\n\n\tconst stream = new ReadableStream({\n\t\tstart: async (controller) => {\n\t\t\tconst body = requestInstance.body;\n\n\t\t\tif (!body) return;\n\n\t\t\tconst requestStreamContext = {\n\t\t\t\tbaseConfig,\n\t\t\t\tconfig,\n\t\t\t\tevent: createProgressEvent({ chunk: new Uint8Array(), totalBytes, transferredBytes }),\n\t\t\t\toptions,\n\t\t\t\trequest,\n\t\t\t\trequestInstance,\n\t\t\t} satisfies RequestStreamContext;\n\n\t\t\tawait executeHooksInTryBlock(options.onRequestStream?.(requestStreamContext));\n\n\t\t\tfor await (const chunk of body) {\n\t\t\t\ttransferredBytes += chunk.byteLength;\n\n\t\t\t\ttotalBytes = Math.max(totalBytes, transferredBytes);\n\n\t\t\t\tawait executeHooksInTryBlock(\n\t\t\t\t\toptions.onRequestStream?.({\n\t\t\t\t\t\t...requestStreamContext,\n\t\t\t\t\t\tevent: createProgressEvent({ chunk, totalBytes, transferredBytes }),\n\t\t\t\t\t})\n\t\t\t\t);\n\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\n\t\t\tcontroller.close();\n\t\t},\n\t});\n\n\treturn new Request(requestInstance, { body: stream, duplex: \"half\" } as RequestInit);\n};\n\ntype StreamableResponseContext = RequestContext & { response: Response };\n\nexport const toStreamableResponse = async (context: StreamableResponseContext): Promise<Response> => {\n\tconst { baseConfig, config, options, request, response } = context;\n\n\tif (!options.onResponseStream || !response.body) {\n\t\treturn response;\n\t}\n\n\tconst contentLength = response.headers.get(\"content-length\");\n\n\tlet totalBytes = Number(contentLength ?? 0);\n\n\tconst shouldForceContentLengthCalc =\n\t\tisObject(options.forcefullyCalculateStreamSize) ?\n\t\t\toptions.forcefullyCalculateStreamSize.response\n\t\t:\toptions.forcefullyCalculateStreamSize;\n\n\t// == If no content length is present and `forceContentLengthCalculation` is enabled, we read the total bytes from the body\n\tif (!contentLength && shouldForceContentLengthCalc) {\n\t\ttotalBytes = await calculateTotalBytesFromBody(response.clone().body, totalBytes);\n\t}\n\n\tlet transferredBytes = 0;\n\n\tconst stream = new ReadableStream({\n\t\tstart: async (controller) => {\n\t\t\tconst body = response.body;\n\n\t\t\tif (!body) return;\n\n\t\t\tconst responseStreamContext = {\n\t\t\t\tbaseConfig,\n\t\t\t\tconfig,\n\t\t\t\tevent: createProgressEvent({ chunk: new Uint8Array(), totalBytes, transferredBytes }),\n\t\t\t\toptions,\n\t\t\t\trequest,\n\t\t\t\tresponse,\n\t\t\t} satisfies ResponseStreamContext;\n\n\t\t\tawait executeHooksInTryBlock(options.onResponseStream?.(responseStreamContext));\n\n\t\t\tfor await (const chunk of body) {\n\t\t\t\ttransferredBytes += chunk.byteLength;\n\n\t\t\t\ttotalBytes = Math.max(totalBytes, transferredBytes);\n\n\t\t\t\tawait executeHooksInTryBlock(\n\t\t\t\t\toptions.onResponseStream?.({\n\t\t\t\t\t\t...responseStreamContext,\n\t\t\t\t\t\tevent: createProgressEvent({ chunk, totalBytes, transferredBytes }),\n\t\t\t\t\t})\n\t\t\t\t);\n\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\n\t\t\tcontroller.close();\n\t\t},\n\t});\n\n\treturn new Response(stream, response);\n};\n","import { dedupeDefaults } from \"./constants/default-options\";\nimport type { RequestContext } from \"./hooks\";\nimport { toStreamableRequest, toStreamableResponse } from \"./stream\";\nimport { deterministicHashFn, getFetchImpl, waitFor } from \"./utils/common\";\n\ntype RequestInfo = {\n\tcontroller: AbortController;\n\tresponsePromise: Promise<Response>;\n};\n\nexport type RequestInfoCache = Map<string | null, RequestInfo>;\n\ntype DedupeContext = RequestContext & {\n\t$GlobalRequestInfoCache: RequestInfoCache;\n\t$LocalRequestInfoCache: RequestInfoCache;\n\tnewFetchController: AbortController;\n};\n\nexport const getAbortErrorMessage = (\n\tdedupeKey: DedupeOptions[\"dedupeKey\"],\n\tfullURL: DedupeContext[\"options\"][\"fullURL\"]\n) => {\n\treturn dedupeKey ?\n\t\t\t`Duplicate request detected - Aborting previous request with key '${dedupeKey}' as a new request was initiated`\n\t\t:\t`Duplicate request detected - Aborting previous request to '${fullURL}' as a new request with identical options was initiated`;\n};\n\nexport const createDedupeStrategy = async (context: DedupeContext) => {\n\tconst {\n\t\t$GlobalRequestInfoCache,\n\t\t$LocalRequestInfoCache,\n\t\tbaseConfig,\n\t\tconfig,\n\t\tnewFetchController,\n\t\toptions: globalOptions,\n\t\trequest: globalRequest,\n\t} = context;\n\n\tconst dedupeStrategy = globalOptions.dedupeStrategy ?? dedupeDefaults.dedupeStrategy;\n\n\tconst generateDedupeKey = () => {\n\t\tconst shouldHaveDedupeKey = dedupeStrategy === \"cancel\" || dedupeStrategy === \"defer\";\n\n\t\tif (!shouldHaveDedupeKey) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn `${globalOptions.fullURL}-${deterministicHashFn({ options: globalOptions, request: globalRequest })}`;\n\t};\n\n\tconst dedupeKey = globalOptions.dedupeKey ?? generateDedupeKey();\n\n\tconst dedupeCacheScope = globalOptions.dedupeCacheScope ?? dedupeDefaults.dedupeCacheScope;\n\n\tconst $RequestInfoCache = (\n\t\t{\n\t\t\tglobal: $GlobalRequestInfoCache,\n\t\t\tlocal: $LocalRequestInfoCache,\n\t\t} satisfies Record<NonNullable<DedupeOptions[\"dedupeCacheScope\"]>, RequestInfoCache>\n\t)[dedupeCacheScope];\n\n\t// == This is to ensure cache operations only occur when key is available\n\tconst $RequestInfoCacheOrNull = dedupeKey !== null ? $RequestInfoCache : null;\n\n\t/******\n\t * == Add a small delay to the execution to ensure proper request deduplication when multiple requests with the same key start simultaneously.\n\t * == This gives time for the cache to be updated with the previous request info before the next request checks it.\n\t ******/\n\tif (dedupeKey !== null) {\n\t\tawait waitFor(0.1);\n\t}\n\n\tconst prevRequestInfo = $RequestInfoCacheOrNull?.get(dedupeKey);\n\n\tconst handleRequestCancelStrategy = () => {\n\t\tconst shouldCancelRequest = prevRequestInfo && dedupeStrategy === \"cancel\";\n\n\t\tif (!shouldCancelRequest) return;\n\n\t\tconst message = getAbortErrorMessage(globalOptions.dedupeKey, globalOptions.fullURL);\n\n\t\tconst reason = new DOMException(message, \"AbortError\");\n\n\t\tprevRequestInfo.controller.abort(reason);\n\n\t\t// == Adding this just so that eslint forces me put await when calling the function (it looks better that way tbh)\n\t\treturn Promise.resolve();\n\t};\n\n\tconst handleRequestDeferStrategy = async (deferContext: {\n\t\toptions: DedupeContext[\"options\"];\n\t\trequest: DedupeContext[\"request\"];\n\t}) => {\n\t\t// == Local options and request are needed so that transformations are applied can be applied to both from call site\n\t\tconst { options: localOptions, request: localRequest } = deferContext;\n\n\t\tconst fetchApi = getFetchImpl(localOptions.customFetchImpl);\n\n\t\tconst shouldUsePromiseFromCache = prevRequestInfo && dedupeStrategy === \"defer\";\n\n\t\tconst streamableContext = {\n\t\t\tbaseConfig,\n\t\t\tconfig,\n\t\t\toptions: localOptions,\n\t\t\trequest: localRequest,\n\t\t} satisfies RequestContext;\n\n\t\tconst streamableRequest = await toStreamableRequest(streamableContext);\n\n\t\tconst responsePromise =\n\t\t\tshouldUsePromiseFromCache ?\n\t\t\t\tprevRequestInfo.responsePromise\n\t\t\t:\tfetchApi(localOptions.fullURL as NonNullable<typeof localOptions.fullURL>, streamableRequest);\n\n\t\t$RequestInfoCacheOrNull?.set(dedupeKey, { controller: newFetchController, responsePromise });\n\n\t\tconst streamableResponse = toStreamableResponse({\n\t\t\t...streamableContext,\n\t\t\tresponse: await responsePromise,\n\t\t});\n\n\t\treturn streamableResponse;\n\t};\n\n\tconst removeDedupeKeyFromCache = () => {\n\t\t$RequestInfoCacheOrNull?.delete(dedupeKey);\n\t};\n\n\treturn {\n\t\tdedupeStrategy,\n\t\thandleRequestCancelStrategy,\n\t\thandleRequestDeferStrategy,\n\t\tremoveDedupeKeyFromCache,\n\t};\n};\n\nexport type DedupeOptions = {\n\t/**\n\t * Defines the scope of the deduplication cache, can be set to \"global\" | \"local\".\n\t * - If set to \"global\", the deduplication cache will be shared across all requests, regardless of whether they shared the same `createFetchClient` or not.\n\t * - If set to \"local\", the deduplication cache will be scoped to the current request.\n\t * @default \"local\"\n\t */\n\tdedupeCacheScope?: \"global\" | \"local\";\n\n\t/**\n\t * Custom request key to be used to identify a request in the fetch deduplication strategy.\n\t * @default the full request url + string formed from the request options\n\t */\n\tdedupeKey?: string;\n\n\t/**\n\t * Defines the deduplication strategy for the request, can be set to \"none\" | \"defer\" | \"cancel\".\n\t * - If set to \"cancel\", the previous pending request with the same request key will be cancelled and lets the new request through.\n\t * - If set to \"defer\", all new request with the same request key will be share the same response, until the previous one is completed.\n\t * - If set to \"none\", deduplication is disabled.\n\t * @default \"cancel\"\n\t */\n\tdedupeStrategy?: \"cancel\" | \"defer\" | \"none\";\n};\n","import { hookDefaults } from \"./constants/default-options\";\nimport {\n\tcomposeAllHooks,\n\ttype Hooks,\n\ttype HooksOrHooksArray,\n\thookRegistries,\n\ttype PluginExtraOptions,\n\ttype RequestContext,\n} from \"./hooks\";\nimport type { CallApiRequestOptions, CallApiRequestOptionsForHooks } from \"./types/common\";\nimport type { AnyFunction, Awaitable } from \"./types/type-helpers\";\nimport type { InitURLOrURLObject } from \"./url\";\nimport { isArray, isFunction, isPlainObject, isString } from \"./utils/guards\";\n\nexport type PluginInitContext<TPluginExtraOptions = unknown> = RequestContext // eslint-disable-next-line perfectionist/sort-intersection-types -- Allow\n\t& PluginExtraOptions<TPluginExtraOptions> & { initURL: string };\n\nexport type PluginInitResult = Partial<\n\tOmit<PluginInitContext, \"initURL\" | \"request\"> & {\n\t\tinitURL: InitURLOrURLObject;\n\t\trequest: CallApiRequestOptions;\n\t}\n>;\n\nexport type PluginHooksWithMoreOptions<TMoreOptions = unknown> = HooksOrHooksArray<\n\tnever,\n\tnever,\n\tTMoreOptions\n>;\n\nexport type PluginHooks<TData = never, TErrorData = never, TMoreOptions = unknown> = HooksOrHooksArray<\n\tTData,\n\tTErrorData,\n\tTMoreOptions\n>;\n\nexport interface CallApiPlugin {\n\t/**\n\t * Defines additional options that can be passed to callApi\n\t */\n\tdefineExtraOptions?: (...params: never[]) => unknown;\n\n\t/**\n\t * A description for the plugin\n\t */\n\tdescription?: string;\n\n\t/**\n\t * Hooks / Interceptors for the plugin\n\t */\n\thooks?: PluginHooks;\n\n\t/**\n\t * A unique id for the plugin\n\t */\n\tid: string;\n\n\t/**\n\t * A function that will be called when the plugin is initialized. This will be called before the any of the other internal functions.\n\t */\n\tinit?: (context: PluginInitContext) => Awaitable<PluginInitResult> | Awaitable<void>;\n\n\t/**\n\t * A name for the plugin\n\t */\n\tname: string;\n\n\t/**\n\t * A version for the plugin\n\t */\n\tversion?: string;\n}\n\nexport const definePlugin = <\n\t// eslint-disable-next-line perfectionist/sort-union-types -- Let the first one be first\n\tTPlugin extends CallApiPlugin | AnyFunction<CallApiPlugin>,\n>(\n\tplugin: TPlugin\n) => {\n\treturn plugin;\n};\n\nexport const initializePlugins = async (context: PluginInitContext) => {\n\tconst { baseConfig, config, initURL, options, request } = context;\n\n\tconst clonedHookRegistries = structuredClone(hookRegistries);\n\n\tconst addMainHooks = () => {\n\t\tfor (const key of Object.keys(clonedHookRegistries) as Array<keyof Hooks>) {\n\t\t\tconst overriddenHook = options[key];\n\t\t\tconst baseHook = baseConfig[key];\n\t\t\tconst instanceHook = config[key];\n\n\t\t\t// == If the base hook is an array and instance hook is defined, we need to compose the base hook with the instance hook\n\t\t\tconst mainHook =\n\t\t\t\tisArray(baseHook) && Boolean(instanceHook) ? [baseHook, instanceHook].flat() : overriddenHook;\n\n\t\t\tif (!mainHook) continue;\n\n\t\t\tclonedHookRegistries[key].add(mainHook as never);\n\t\t}\n\t};\n\n\tconst addPluginHooks = (pluginHooks: Required<CallApiPlugin>[\"hooks\"]) => {\n\t\tfor (const key of Object.keys(clonedHookRegistries) as Array<keyof Hooks>) {\n\t\t\tconst pluginHook = pluginHooks[key];\n\n\t\t\tif (!pluginHook) continue;\n\n\t\t\tclonedHookRegistries[key].add(pluginHook as never);\n\t\t}\n\t};\n\n\tconst mergedHooksExecutionOrder =\n\t\toptions.mergedHooksExecutionOrder ?? hookDefaults.mergedHooksExecutionOrder;\n\n\tif (mergedHooksExecutionOrder === \"mainHooksBeforePlugins\") {\n\t\taddMainHooks();\n\t}\n\n\tconst resolvedPlugins =\n\t\tisFunction(options.plugins) ?\n\t\t\toptions.plugins({ basePlugins: baseConfig.plugins ?? [] })\n\t\t:\t(options.plugins ?? []);\n\n\tlet resolvedInitURL = initURL;\n\tlet resolvedOptions = options;\n\tlet resolvedRequestOptions = request;\n\n\tconst executePluginInit = async (pluginInit: CallApiPlugin[\"init\"]) => {\n\t\tif (!pluginInit) return;\n\n\t\tconst initResult = await pluginInit({\n\t\t\tbaseConfig,\n\t\t\tconfig,\n\t\t\tinitURL,\n\t\t\toptions,\n\t\t\trequest,\n\t\t});\n\n\t\tif (!isPlainObject(initResult)) return;\n\n\t\tconst urlString = initResult.initURL?.toString();\n\n\t\tif (isString(urlString)) {\n\t\t\tresolvedInitURL = urlString;\n\t\t}\n\n\t\tif (isPlainObject(initResult.request)) {\n\t\t\tresolvedRequestOptions = initResult.request as CallApiRequestOptionsForHooks;\n\t\t}\n\n\t\tif (isPlainObject(initResult.options)) {\n\t\t\tresolvedOptions = initResult.options;\n\t\t}\n\t};\n\n\tfor (const plugin of resolvedPlugins) {\n\t\t// eslint-disable-next-line no-await-in-loop -- Await is necessary in this case.\n\t\tawait executePluginInit(plugin.init);\n\n\t\tif (!plugin.hooks) continue;\n\n\t\taddPluginHooks(plugin.hooks);\n\t}\n\n\tif (mergedHooksExecutionOrder === \"mainHooksAfterPlugins\") {\n\t\taddMainHooks();\n\t}\n\n\tconst resolvedHooks: Hooks = {};\n\n\tfor (const [key, hookRegistry] of Object.entries(clonedHookRegistries)) {\n\t\tif (hookRegistry.size === 0) continue;\n\n\t\t// == Flatten the hook registry to remove any nested arrays, incase an array of hooks is passed to any of the hooks\n\t\tconst flattenedHookArray = [...hookRegistry].flat();\n\n\t\tif (flattenedHookArray.length === 0) continue;\n\n\t\tconst mergedHooksExecutionMode =\n\t\t\toptions.mergedHooksExecutionMode ?? hookDefaults.mergedHooksExecutionMode;\n\n\t\tconst composedHook = composeAllHooks(flattenedHookArray, mergedHooksExecutionMode);\n\n\t\tresolvedHooks[key as keyof Hooks] = composedHook;\n\t}\n\n\treturn {\n\t\tresolvedHooks,\n\t\tresolvedInitURL,\n\t\tresolvedOptions,\n\t\tresolvedRequestOptions,\n\t};\n};\n","import { requestOptionDefaults, retryDefaults } from \"./constants/default-options\";\nimport type { ErrorContext, RequestContext } from \"./hooks\";\nimport type { MethodUnion } from \"./types\";\nimport type { Awaitable } from \"./types/type-helpers\";\nimport { isFunction } from \"./utils/guards\";\n\ntype RetryCondition<TErrorData> = (context: ErrorContext<TErrorData>) => Awaitable<boolean>;\n\ntype InnerRetryKeys<TErrorData> = Exclude<keyof RetryOptions<TErrorData>, \"~retryAttemptCount\" | \"retry\">;\n\ntype InnerRetryOptions<TErrorData> = {\n\t[Key in InnerRetryKeys<TErrorData> as Key extends `retry${infer TRest}` ?\n\t\tUncapitalize<TRest> extends \"attempts\" ?\n\t\t\tnever\n\t\t:\tUncapitalize<TRest>\n\t:\tKey]?: RetryOptions<TErrorData>[Key];\n} & {\n\tattempts: NonNullable<RetryOptions<TErrorData>[\"retryAttempts\"]>;\n};\n\nexport interface RetryOptions<TErrorData> {\n\t/**\n\t * Keeps track of the number of times the request has already been retried\n\t *\n\t * @deprecated **NOTE**: This property is used internally to track retries. Please abstain from modifying it.\n\t */\n\treadonly [\"~retryAttemptCount\"]?: number;\n\n\t/**\n\t * All retry options in a single object instead of separate properties\n\t */\n\tretry?: InnerRetryOptions<TErrorData>;\n\n\t/**\n\t * Number of allowed retry attempts on HTTP errors\n\t * @default 0\n\t */\n\tretryAttempts?: number;\n\n\t/**\n\t * Callback whose return value determines if a request should be retried or not\n\t */\n\tretryCondition?: RetryCondition<TErrorData>;\n\n\t/**\n\t * Delay between retries in milliseconds\n\t * @default 1000\n\t */\n\tretryDelay?: number | ((currentAttemptCount: number) => number);\n\n\t/**\n\t * Maximum delay in milliseconds. Only applies to exponential strategy\n\t * @default 10000\n\t */\n\tretryMaxDelay?: number;\n\n\t/**\n\t * HTTP methods that are allowed to retry\n\t * @default [\"GET\", \"POST\"]\n\t */\n\tretryMethods?: MethodUnion[];\n\n\t/**\n\t * HTTP status codes that trigger a retry\n\t */\n\tretryStatusCodes?: number[];\n\n\t/**\n\t * Strategy to use when retrying\n\t * @default \"linear\"\n\t */\n\tretryStrategy?: \"exponential\" | \"linear\";\n}\n\nconst getLinearDelay = (currentAttemptCount: number, options: RetryOptions<unknown>) => {\n\tconst retryDelay = options.retryDelay ?? options.retry?.delay;\n\n\tconst resolveRetryDelay =\n\t\t(isFunction(retryDelay) ? retryDelay(currentAttemptCount) : retryDelay) ?? retryDefaults.delay;\n\n\treturn resolveRetryDelay;\n};\n\nconst getExponentialDelay = (currentAttemptCount: number, options: RetryOptions<unknown>) => {\n\tconst retryDelay = options.retryDelay ?? options.retry?.delay ?? retryDefaults.delay;\n\n\tconst resolvedRetryDelay = isFunction(retryDelay) ? retryDelay(currentAttemptCount) : retryDelay;\n\n\tconst maxDelay = options.retryMaxDelay ?? options.retry?.maxDelay ?? retryDefaults.maxDelay;\n\n\tconst exponentialDelay = resolvedRetryDelay * 2 ** currentAttemptCount;\n\n\treturn Math.min(exponentialDelay, maxDelay);\n};\n\nexport const createRetryStrategy = (ctx: ErrorContext<unknown> & RequestContext) => {\n\tconst { options } = ctx;\n\n\t// eslint-disable-next-line ts-eslint/no-deprecated -- Allowed for internal use\n\tconst currentAttemptCount = options[\"~retryAttemptCount\"] ?? 1;\n\n\tconst retryStrategy = options.retryStrategy ?? options.retry?.strategy ?? retryDefaults.strategy;\n\n\tconst getDelay = () => {\n\t\tswitch (retryStrategy) {\n\t\t\tcase \"exponential\": {\n\t\t\t\treturn getExponentialDelay(currentAttemptCount, options);\n\t\t\t}\n\t\t\tcase \"linear\": {\n\t\t\t\treturn getLinearDelay(currentAttemptCount, options);\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tthrow new Error(`Invalid retry strategy: ${String(retryStrategy)}`);\n\t\t\t}\n\t\t}\n\t};\n\n\tconst shouldAttemptRetry = async () => {\n\t\tconst retryCondition = options.retryCondition ?? options.retry?.condition ?? retryDefaults.condition;\n\n\t\tconst maximumRetryAttempts =\n\t\t\toptions.retryAttempts ?? options.retry?.attempts ?? retryDefaults.attempts;\n\n\t\tconst customRetryCondition = await retryCondition(ctx);\n\n\t\tconst baseShouldRetry = maximumRetryAttempts >= currentAttemptCount && customRetryCondition;\n\n\t\tif (!baseShouldRetry) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst retryMethods = new Set(\n\t\t\toptions.retryMethods ?? options.retry?.methods ?? retryDefaults.methods\n\t\t);\n\n\t\tconst resolvedMethod = ctx.request.method ?? requestOptionDefaults.method;\n\n\t\tconst includesMethod = retryMethods.has(resolvedMethod);\n\n\t\tconst retryStatusCodes = new Set(options.retryStatusCodes ?? options.retry?.statusCodes ?? []);\n\n\t\tconst includesStatusCodes =\n\t\t\tBoolean(ctx.response?.status)\n\t\t\t&& (retryStatusCodes.size > 0 ? retryStatusCodes.has(ctx.response.status) : true);\n\n\t\tconst shouldRetry = includesMethod && includesStatusCodes;\n\n\t\treturn shouldRetry;\n\t};\n\n\treturn {\n\t\tcurrentAttemptCount,\n\t\tgetDelay,\n\t\tshouldAttemptRetry,\n\t};\n};\n","import { ValidationError } from \"./error\";\nimport type {\n\tBody,\n\tCallApiExtraOptions,\n\tCallApiRequestOptions,\n\tGlobalMeta,\n\tHeadersOption,\n\tMethodUnion,\n} from \"./types\";\nimport type { StandardSchemaV1 } from \"./types/standard-schema\";\nimport {\n\ttype AnyFunction,\n\ttype AnyString,\n\ttype Awaitable,\n\tdefineEnum,\n\ttype Prettify,\n\ttype UnionToIntersection,\n\ttype Writeable,\n} from \"./types/type-helpers\";\nimport type { Params, Query } from \"./url\";\nimport { isFunction } from \"./utils/guards\";\n\ntype InferSchemaInput<TSchema extends CallApiSchema[keyof CallApiSchema]> =\n\tTSchema extends StandardSchemaV1 ? StandardSchemaV1.InferInput<TSchema>\n\t: TSchema extends (value: infer TInput) => unknown ? TInput\n\t: never;\n\nexport type InferSchemaResult<TSchema, TFallbackResult = unknown> =\n\t// == Checking for undefined first and returning fallback to avoid type errors when passing the config around (weird tbh)\n\tundefined extends TSchema ? TFallbackResult\n\t: TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema>\n\t: TSchema extends AnyFunction<infer TResult> ? Awaited<TResult>\n\t: TFallbackResult;\n\nconst handleValidatorFunction = async <TInput>(\n\tvalidator: Extract<CallApiSchema[keyof CallApiSchema], AnyFunction>,\n\tinputData: TInput\n): Promise<StandardSchemaV1.Result<TInput>> => {\n\ttry {\n\t\tconst result = await validator(inputData as never);\n\n\t\treturn {\n\t\t\tissues: undefined,\n\t\t\tvalue: result as never,\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tissues: error as never,\n\t\t\tvalue: undefined,\n\t\t};\n\t}\n};\n\nexport const standardSchemaParser = async <\n\tTSchema extends NonNullable<CallApiSchema[keyof CallApiSchema]>,\n>(\n\tschema: TSchema,\n\tinputData: InferSchemaInput<TSchema>,\n\tresponse?: Response | null\n): Promise<InferSchemaResult<TSchema>> => {\n\tconst result =\n\t\tisFunction(schema) ?\n\t\t\tawait handleValidatorFunction(schema, inputData)\n\t\t:\tawait schema[\"~standard\"].validate(inputData);\n\n\t// == If the `issues` field exists, it means the validation failed\n\tif (result.issues) {\n\t\tthrow new ValidationError(\n\t\t\t{ issues: result.issues, response: response ?? null },\n\t\t\t{ cause: result.issues }\n\t\t);\n\t}\n\n\treturn result.value as never;\n};\n\nexport interface CallApiSchemaConfig {\n\t/**\n\t * The base url of the schema. By default it's the baseURL of the fetch instance.\n\t */\n\tbaseURL?: string;\n\n\t/**\n\t * Disables runtime validation for the schema.\n\t */\n\tdisableRuntimeValidation?: boolean;\n\n\t/**\n\t * If `true`, the original input value will be used instead of the transformed/validated output.\n\t *\n\t * This is useful when you want to validate the input but don't want any transformations\n\t * applied by the validation schema (e.g., type coercion, default values, etc).\n\t */\n\tdisableValidationOutputApplication?: boolean;\n\n\t/**\n\t *Determines the inference or requirement of the method option based on the route modifiers (`@get/`, `@post/`, `@put/`, `@patch/`, `@delete/`).\n\t *\n\t * - When `true`, the method option is made required on the type level and is not automatically added to the request options.\n\t * - When `false` or `undefined` (default), the method option is not required on the type level, and is automatically added to the request options.\n\t *\n\t */\n\trequireMethodProvision?: boolean;\n\n\t/**\n\t * Controls the strictness of API route validation.\n\t *\n\t * When true:\n\t * - Only routes explicitly defined in the schema will be considered valid to typescript\n\t * - Attempting to call undefined routes will result in type errors\n\t * - Useful for ensuring API calls conform exactly to your schema definition\n\t *\n\t * When false or undefined (default):\n\t * - All routes will be allowed, whether they are defined in the schema or not\n\t * - Provides more flexibility but less type safety\n\t *\n\t */\n\tstrict?: boolean;\n}\n\nexport interface CallApiSchema {\n\t/**\n\t * The schema to use for validating the request body.\n\t */\n\tbody?: StandardSchemaV1<Body> | ((body: Body) => Awaitable<Body>);\n\n\t/**\n\t * The schema to use for validating the response data.\n\t */\n\tdata?: StandardSchemaV1 | ((data: unknown) => unknown);\n\n\t/**\n\t * The schema to use for validating the response error data.\n\t */\n\terrorData?: StandardSchemaV1 | ((errorData: unknown) => unknown);\n\n\t/**\n\t * The schema to use for validating the request headers.\n\t */\n\theaders?:\n\t\t| StandardSchemaV1<HeadersOption | undefined>\n\t\t| ((headers: HeadersOption) => Awaitable<HeadersOption>);\n\n\t/**\n\t * The schema to use for validating the meta option.\n\t */\n\tmeta?: StandardSchemaV1<GlobalMeta | undefined> | ((meta: GlobalMeta) => Awaitable<GlobalMeta>);\n\n\t/**\n\t * The schema to use for validating the request method.\n\t */\n\tmethod?: StandardSchemaV1<MethodUnion | undefined> | ((method: MethodUnion) => Awaitable<MethodUnion>);\n\n\t/**\n\t * The schema to use for validating the request url parameters.\n\t */\n\tparams?: StandardSchemaV1<Params | undefined> | ((params: Params) => Awaitable<Params>);\n\n\t/**\n\t * The schema to use for validating the request url queries.\n\t */\n\tquery?: StandardSchemaV1<Query | undefined> | ((query: Query) => Awaitable<Query>);\n}\n\nexport const routeKeyMethods = defineEnum([\"delete\", \"get\", \"patch\", \"post\", \"put\"]);\n\nexport type RouteKeyMethods = (typeof routeKeyMethods)[number];\n\ntype PossibleRouteKey = `@${RouteKeyMethods}/` | AnyString;\n\nexport type BaseCallApiSchema = Partial<Record<PossibleRouteKey, CallApiSchema>>;\n\nexport const defineSchema = <const TBaseSchema extends BaseCallApiSchema>(baseSchema: TBaseSchema) => {\n\treturn baseSchema as Writeable<typeof baseSchema, \"deep\">;\n};\n\ntype ValidationOptions<\n\tTSchema extends CallApiSchema[keyof CallApiSchema] = CallApiSchema[keyof CallApiSchema],\n> = {\n\tinputValue: InferSchemaInput<TSchema>;\n\tresponse?: Response | null;\n\tschemaConfig: CallApiSchemaConfig | undefined;\n};\n\nexport const handleValidation = async <TSchema extends CallApiSchema[keyof CallApiSchema]>(\n\tschema: TSchema | undefined,\n\tvalidationOptions: ValidationOptions<TSchema>\n): Promise<InferSchemaResult<TSchema>> => {\n\tconst { inputValue, response, schemaConfig } = validationOptions;\n\n\tif (!schema || schemaConfig?.disableRuntimeValidation) {\n\t\treturn inputValue as never;\n\t}\n\n\tconst validResult = await standardSchemaParser(schema, inputValue, response);\n\n\treturn validResult as never;\n};\n\ntype LastOf<TValue> =\n\tUnionToIntersection<TValue extends unknown ? () => TValue : never> extends () => infer R ? R : never;\n\ntype Push<TArray extends unknown[], TArrayItem> = [...TArray, TArrayItem];\n\ntype UnionToTuple<\n\tTUnion,\n\tTComputedLastUnion = LastOf<TUnion>,\n\tTComputedIsUnionEqualToNever = [TUnion] extends [never] ? true : false,\n> =\n\ttrue extends TComputedIsUnionEqualToNever ? []\n\t:\tPush<UnionToTuple<Exclude<TUnion, TComputedLastUnion>>, TComputedLastUnion>;\n\nexport type Tuple<TTuple, TArray extends TTuple[] = []> =\n\tUnionToTuple<TTuple>[\"length\"] extends TArray[\"length\"] ? [...TArray]\n\t:\tTuple<TTuple, [TTuple, ...TArray]>;\n\nconst extraOptionsToBeValidated = [\"meta\", \"params\", \"query\"] satisfies Tuple<\n\tExtract<keyof CallApiSchema, keyof CallApiExtraOptions>\n>;\n\ntype ExtraOptionsValidationOptions = {\n\textraOptions: CallApiExtraOptions;\n\tschema: CallApiSchema | undefined;\n\tschemaConfig: CallApiSchemaConfig | undefined;\n};\n\nconst handleExtraOptionsValidation = async (validationOptions: ExtraOptionsValidationOptions) => {\n\tconst { extraOptions, schema, schemaConfig } = validationOptions;\n\n\tconst validationResultArray = await Promise.all(\n\t\textraOptionsToBeValidated.map((propertyKey) =>\n\t\t\thandleValidation(schema?.[propertyKey], {\n\t\t\t\tinputValue: extraOptions[propertyKey],\n\t\t\t\tschemaConfig,\n\t\t\t})\n\t\t)\n\t);\n\n\tconst validatedResultObject: Prettify<\n\t\tPick<CallApiExtraOptions, (typeof extraOptionsToBeValidated)[number]>\n\t> = {};\n\n\tfor (const [index, propertyKey] of extraOptionsToBeValidated.entries()) {\n\t\tconst validationResult = validationResultArray[index];\n\n\t\tif (validationResult === undefined) continue;\n\n\t\tvalidatedResultObject[propertyKey] = validationResult as never;\n\t}\n\n\treturn validatedResultObject;\n};\n\nconst requestOptionsToBeValidated = [\"body\", \"headers\", \"method\"] satisfies Tuple<\n\tExtract<keyof CallApiSchema, keyof CallApiRequestOptions>\n>;\n\ntype RequestOptionsValidationOptions = {\n\trequestOptions: CallApiRequestOptions;\n\tschema: CallApiSchema | undefined;\n\tschemaConfig: CallApiSchemaConfig | undefined;\n};\n\nconst handleRequestOptionsValidation = async (validationOptions: RequestOptionsValidationOptions) => {\n\tconst { requestOptions, schema, schemaConfig } = validationOptions;\n\n\tconst validationResultArray = await Promise.all(\n\t\trequestOptionsToBeValidated.map((propertyKey) =>\n\t\t\thandleValidation(schema?.[propertyKey], {\n\t\t\t\tinputValue: requestOptions[propertyKey],\n\t\t\t\tschemaConfig,\n\t\t\t})\n\t\t)\n\t);\n\n\tconst validatedResultObject: Prettify<\n\t\tPick<CallApiRequestOptions, (typeof requestOptionsToBeValidated)[number]>\n\t> = {};\n\n\tfor (const [index, propertyKey] of requestOptionsToBeValidated.entries()) {\n\t\tconst validationResult = validationResultArray[index];\n\n\t\tif (validationResult === undefined) continue;\n\n\t\tvalidatedResultObject[propertyKey] = validationResult as never;\n\t}\n\n\treturn validatedResultObject;\n};\n\nexport const handleOptionsValidation = async (\n\tvalidationOptions: ExtraOptionsValidationOptions & RequestOptionsValidationOptions\n) => {\n\tconst { extraOptions, requestOptions, schema, schemaConfig } = validationOptions;\n\n\tif (schemaConfig?.disableRuntimeValidation) {\n\t\treturn {\n\t\t\textraOptionsValidationResult: null,\n\t\t\trequestOptionsValidationResult: null,\n\t\t};\n\t}\n\n\tconst [extraOptionsValidationResult, requestOptionsValidationResult] = await Promise.all([\n\t\thandleExtraOptionsValidation({ extraOptions, schema, schemaConfig }),\n\t\thandleRequestOptionsValidation({ requestOptions, schema, schemaConfig }),\n\t]);\n\n\treturn { extraOptionsValidationResult, requestOptionsValidationResult };\n};\n","import { requestOptionDefaults } from \"./constants/default-options\";\nimport type { CallApiExtraOptions, CallApiRequestOptions } from \"./types/common\";\nimport type { UnmaskType } from \"./types/type-helpers\";\nimport { toQueryString } from \"./utils\";\nimport { isArray } from \"./utils/guards\";\nimport { type CallApiSchemaConfig, routeKeyMethods } from \"./validation\";\n\nconst slash = \"/\";\nconst column = \":\";\nconst mergeUrlWithParams = (url: string, params: CallApiExtraOptions[\"params\"]) => {\n\tif (!params) {\n\t\treturn url;\n\t}\n\n\tlet newUrl = url;\n\n\tif (isArray(params)) {\n\t\tconst matchedParamArray = newUrl.split(slash).filter((param) => param.startsWith(column));\n\n\t\tfor (const [index, matchedParam] of matchedParamArray.entries()) {\n\t\t\tconst realParam = params[index] as string;\n\t\t\tnewUrl = newUrl.replace(matchedParam, realParam);\n\t\t}\n\n\t\treturn newUrl;\n\t}\n\n\tfor (const [key, value] of Object.entries(params)) {\n\t\tnewUrl = newUrl.replace(`${column}${key}`, String(value));\n\t}\n\n\treturn newUrl;\n};\n\nconst questionMark = \"?\";\nconst ampersand = \"&\";\nconst mergeUrlWithQuery = (url: string, query: CallApiExtraOptions[\"query\"]): string => {\n\tif (!query) {\n\t\treturn url;\n\t}\n\n\tconst queryString = toQueryString(query);\n\n\tif (queryString?.length === 0) {\n\t\treturn url;\n\t}\n\n\tif (url.endsWith(questionMark)) {\n\t\treturn `${url}${queryString}`;\n\t}\n\n\tif (url.includes(questionMark)) {\n\t\treturn `${url}${ampersand}${queryString}`;\n\t}\n\n\treturn `${url}${questionMark}${queryString}`;\n};\n\nexport const getCurrentRouteKey = (url: string, schemaConfig: CallApiSchemaConfig | undefined) => {\n\tlet currentRouteKey = url;\n\n\tif (schemaConfig?.baseURL && currentRouteKey.startsWith(schemaConfig.baseURL)) {\n\t\tcurrentRouteKey = currentRouteKey.replace(schemaConfig.baseURL, \"\");\n\t}\n\n\treturn currentRouteKey;\n};\n\n/**\n * @description\n * Extracts the method from the URL if it is a schema modifier.\n *\n * @param initURL - The URL to extract the method from.\n * @returns The method if it is a schema modifier, otherwise undefined.\n */\nexport const extractMethodFromURL = (initURL: string | undefined) => {\n\tif (!initURL?.startsWith(\"@\")) return;\n\n\tconst method = initURL.split(\"@\")[1]?.split(\"/\")[0];\n\n\tif (!method || !routeKeyMethods.includes(method)) return;\n\n\treturn method;\n};\n\nexport type GetMethodOptions = {\n\tinitURL: string | undefined;\n\tmethod: CallApiRequestOptions[\"method\"];\n\tschemaConfig?: CallApiSchemaConfig;\n};\n\nexport const getMethod = (options: GetMethodOptions) => {\n\tconst { initURL, method, schemaConfig } = options;\n\n\tif (schemaConfig?.requireMethodProvision === true) {\n\t\treturn method?.toUpperCase() ?? requestOptionDefaults.method;\n\t}\n\n\treturn (\n\t\tmethod?.toUpperCase() ?? extractMethodFromURL(initURL)?.toUpperCase() ?? requestOptionDefaults.method\n\t);\n};\n\nexport const normalizeURL = (initURL: string) => {\n\tconst methodFromURL = extractMethodFromURL(initURL);\n\n\tif (!methodFromURL) {\n\t\treturn initURL;\n\t}\n\n\tconst normalizedURL = initURL.replace(`@${methodFromURL}/`, \"/\");\n\n\treturn normalizedURL;\n};\n\ntype GetFullURLOptions = {\n\tbaseURL: string | undefined;\n\tinitURL: string;\n\tparams: CallApiExtraOptions[\"params\"];\n\tquery: CallApiExtraOptions[\"query\"];\n};\n\nexport const getFullURL = (options: GetFullURLOptions) => {\n\tconst { baseURL, initURL, params, query } = options;\n\n\tconst normalizedURL = normalizeURL(initURL);\n\n\tconst urlWithMergedParams = mergeUrlWithParams(normalizedURL, params);\n\n\tconst urlWithMergedQueryAndParams = mergeUrlWithQuery(urlWithMergedParams, query);\n\n\tif (urlWithMergedQueryAndParams.startsWith(\"http\") || !baseURL) {\n\t\treturn urlWithMergedQueryAndParams;\n\t}\n\n\treturn `${baseURL}${urlWithMergedQueryAndParams}`;\n};\n\nexport type AllowedQueryParamValues = UnmaskType<boolean | number | string>;\n\nexport type Params = UnmaskType<\n\t// eslint-disable-next-line perfectionist/sort-union-types -- I need the Record to be first\n\tRecord<string, AllowedQueryParamValues> | AllowedQueryParamValues[]\n>;\n\nexport type Query = UnmaskType<Record<string, AllowedQueryParamValues>>;\n\nexport type InitURLOrURLObject = string | URL;\n\nexport interface URLOptions {\n\t/**\n\t * Base URL to be prepended to all request URLs\n\t */\n\tbaseURL?: string;\n\n\t/**\n\t * Resolved request URL\n\t */\n\treadonly fullURL?: string;\n\n\t/**\n\t * The url string passed to the callApi instance\n\t */\n\treadonly initURL?: string;\n\n\t/**\n\t * The URL string passed to the callApi instance, but normalized (removed any method modifiers etc)\n\t */\n\treadonly initURLNormalized?: string;\n\n\t/**\n\t * Parameters to be appended to the URL (i.e: /:id)\n\t *\n\t * If url is defined as `/path/:id`, params will be `{ id: string }`\n\t */\n\tparams?: Params;\n\n\t/**\n\t * Query parameters to append to the URL.\n\t */\n\tquery?: Query;\n}\n","import { createDedupeStrategy, getAbortErrorMessage, type RequestInfoCache } from \"./dedupe\";\nimport { HTTPError } from \"./error\";\nimport {\n\ttype ErrorContext,\n\ttype ExecuteHookInfo,\n\texecuteHooksInCatchBlock,\n\texecuteHooksInTryBlock,\n\ttype RetryContext,\n\ttype SuccessContext,\n} from \"./hooks\";\nimport { type CallApiPlugin, initializePlugins } from \"./plugins\";\nimport {\n\ttype ErrorInfo,\n\tgetCustomizedErrorResult,\n\ttype ResponseTypeUnion,\n\ttype ResultModeUnion,\n\tresolveErrorResult,\n\tresolveResponseData,\n\tresolveSuccessResult,\n} from \"./result\";\nimport { createRetryStrategy } from \"./retry\";\nimport type {\n\tGetCurrentRouteKey,\n\tGetCurrentRouteSchema,\n\tInferHeadersOption,\n\tInferInitURL,\n\tThrowOnErrorUnion,\n} from \"./types\";\nimport type {\n\tBaseCallApiConfig,\n\tBaseCallApiExtraOptions,\n\tCallApiExtraOptions,\n\tCallApiExtraOptionsForHooks,\n\tCallApiParameters,\n\tCallApiRequestOptions,\n\tCallApiRequestOptionsForHooks,\n\tCallApiResult,\n} from \"./types/common\";\nimport type { DefaultDataType, DefaultPluginArray, DefaultThrowOnError } from \"./types/default-types\";\nimport type { AnyFunction } from \"./types/type-helpers\";\nimport { getCurrentRouteKey, getFullURL, getMethod, normalizeURL } from \"./url\";\nimport {\n\tcreateCombinedSignal,\n\tcreateTimeoutSignal,\n\tgetBody,\n\tgetHeaders,\n\tsplitBaseConfig,\n\tsplitConfig,\n\twaitFor,\n} from \"./utils/common\";\nimport { isFunction, isHTTPErrorInstance, isValidationErrorInstance } from \"./utils/guards\";\nimport {\n\ttype BaseCallApiSchema,\n\ttype CallApiSchema,\n\ttype CallApiSchemaConfig,\n\thandleOptionsValidation,\n\thandleValidation,\n\ttype InferSchemaResult,\n} from \"./validation\";\n\nconst $GlobalRequestInfoCache: RequestInfoCache = new Map();\n\nexport const createFetchClient = <\n\tTBaseData = DefaultDataType,\n\tTBaseErrorData = DefaultDataType,\n\tTBaseResultMode extends ResultModeUnion = ResultModeUnion,\n\tTBaseThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError,\n\tTBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tconst TBaseSchema extends BaseCallApiSchema = BaseCallApiSchema,\n\tconst TBaseSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig,\n\tTBasePluginArray extends CallApiPlugin[] = DefaultPluginArray,\n>(\n\tinitBaseConfig: BaseCallApiConfig<\n\t\tTBaseData,\n\t\tTBaseErrorData,\n\t\tTBaseResultMode,\n\t\tTBaseThrowOnError,\n\t\tTBaseResponseType,\n\t\tTBaseSchema,\n\t\tTBaseSchemaConfig,\n\t\tTBasePluginArray\n\t> = {} as never\n) => {\n\tconst $LocalRequestInfoCache: RequestInfoCache = new Map();\n\n\tconst callApi = async <\n\t\tTData = TBaseData,\n\t\tTErrorData = TBaseErrorData,\n\t\tTResultMode extends ResultModeUnion = TBaseResultMode,\n\t\tTThrowOnError extends ThrowOnErrorUnion = TBaseThrowOnError,\n\t\tTResponseType extends ResponseTypeUnion = TBaseResponseType,\n\t\tTSchemaConfig extends CallApiSchemaConfig = TBaseSchemaConfig,\n\t\tTInitURL extends InferInitURL<TBaseSchema, TSchemaConfig> = InferInitURL<TBaseSchema, TSchemaConfig>,\n\t\tTCurrentRouteKey extends GetCurrentRouteKey<TSchemaConfig, TInitURL> = GetCurrentRouteKey<\n\t\t\tTSchemaConfig,\n\t\t\tTInitURL\n\t\t>,\n\t\tTSchema extends CallApiSchema = GetCurrentRouteSchema<TBaseSchema, TCurrentRouteKey>,\n\t\tTPluginArray extends CallApiPlugin[] = TBasePluginArray,\n\t>(\n\t\t...parameters: CallApiParameters<\n\t\t\tInferSchemaResult<TSchema[\"data\"], TData>,\n\t\t\tInferSchemaResult<TSchema[\"errorData\"], TErrorData>,\n\t\t\tTResultMode,\n\t\t\tTThrowOnError,\n\t\t\tTResponseType,\n\t\t\tTBaseSchema,\n\t\t\tTSchema,\n\t\t\tTBaseSchemaConfig,\n\t\t\tTSchemaConfig,\n\t\t\tTInitURL,\n\t\t\tTCurrentRouteKey,\n\t\t\tTBasePluginArray,\n\t\t\tTPluginArray\n\t\t>\n\t): CallApiResult<\n\t\tInferSchemaResult<TSchema[\"data\"], TData>,\n\t\tInferSchemaResult<TSchema[\"errorData\"], TErrorData>,\n\t\tTResultMode,\n\t\tTThrowOnError,\n\t\tTResponseType\n\t> => {\n\t\tconst [initURLOrURLObject, initConfig = {}] = parameters;\n\n\t\tconst [fetchOptions, extraOptions] = splitConfig(initConfig);\n\n\t\tconst resolvedBaseConfig =\n\t\t\tisFunction(initBaseConfig) ?\n\t\t\t\tinitBaseConfig({\n\t\t\t\t\tinitURL: initURLOrURLObject.toString(),\n\t\t\t\t\toptions: extraOptions,\n\t\t\t\t\trequest: fetchOptions,\n\t\t\t\t})\n\t\t\t:\tinitBaseConfig;\n\n\t\tconst baseConfig = resolvedBaseConfig as BaseCallApiExtraOptions & CallApiRequestOptions;\n\t\tconst config = initConfig as CallApiExtraOptions & CallApiRequestOptions;\n\n\t\tconst [baseFetchOptions, baseExtraOptions] = splitBaseConfig(baseConfig);\n\n\t\tconst shouldSkipAutoMergeForOptions =\n\t\t\tbaseExtraOptions.skipAutoMergeFor === \"all\" || baseExtraOptions.skipAutoMergeFor === \"options\";\n\n\t\tconst shouldSkipAutoMergeForRequest =\n\t\t\tbaseExtraOptions.skipAutoMergeFor === \"all\" || baseExtraOptions.skipAutoMergeFor === \"request\";\n\n\t\t// == Merged Extra Options\n\t\tconst mergedExtraOptions = {\n\t\t\t...baseExtraOptions,\n\t\t\t...(!shouldSkipAutoMergeForOptions && extraOptions),\n\t\t};\n\n\t\t// == Merged Request Options\n\t\tconst mergedRequestOptions = {\n\t\t\t// == Making sure headers is always an object\n\t\t\theaders: {},\n\t\t\t...baseFetchOptions,\n\t\t\t...(!shouldSkipAutoMergeForRequest && fetchOptions),\n\t\t} satisfies CallApiRequestOptions;\n\n\t\tconst { resolvedHooks, resolvedInitURL, resolvedOptions, resolvedRequestOptions } =\n\t\t\tawait initializePlugins({\n\t\t\t\tbaseConfig,\n\t\t\t\tconfig,\n\t\t\t\tinitURL: initURLOrURLObject.toString(),\n\t\t\t\toptions: mergedExtraOptions as CallApiExtraOptionsForHooks,\n\t\t\t\trequest: mergedRequestOptions as CallApiRequestOptionsForHooks,\n\t\t\t});\n\n\t\tconst fullURL = getFullURL({\n\t\t\tbaseURL: resolvedOptions.baseURL,\n\t\t\tinitURL: resolvedInitURL,\n\t\t\tparams: resolvedOptions.params,\n\t\t\tquery: resolvedOptions.query,\n\t\t});\n\n\t\tconst resolvedSchemaConfig =\n\t\t\tisFunction(extraOptions.schemaConfig) ?\n\t\t\t\textraOptions.schemaConfig({ baseSchemaConfig: baseExtraOptions.schemaConfig ?? {} })\n\t\t\t:\t(extraOptions.schemaConfig ?? baseExtraOptions.schemaConfig);\n\n\t\tconst currentRouteKey = getCurrentRouteKey(resolvedInitURL, resolvedSchemaConfig);\n\n\t\tconst routeSchema = baseExtraOptions.schema?.[currentRouteKey];\n\n\t\tconst resolvedSchema =\n\t\t\tisFunction(extraOptions.schema) ?\n\t\t\t\textraOptions.schema({\n\t\t\t\t\tbaseSchema: baseExtraOptions.schema ?? {},\n\t\t\t\t\tcurrentRouteSchema: routeSchema ?? {},\n\t\t\t\t})\n\t\t\t:\t(extraOptions.schema ?? routeSchema);\n\n\t\tlet options = {\n\t\t\t...resolvedOptions,\n\t\t\t...resolvedHooks,\n\n\t\t\tfullURL,\n\t\t\tinitURL: resolvedInitURL,\n\t\t\tinitURLNormalized: normalizeURL(resolvedInitURL),\n\t\t} satisfies CallApiExtraOptionsForHooks;\n\n\t\tconst newFetchController = new AbortController();\n\n\t\tconst timeoutSignal = options.timeout != null ? createTimeoutSignal(options.timeout) : null;\n\n\t\tconst combinedSignal = createCombinedSignal(\n\t\t\tresolvedRequestOptions.signal,\n\t\t\ttimeoutSignal,\n\t\t\tnewFetchController.signal\n\t\t);\n\n\t\tlet request = {\n\t\t\t...resolvedRequestOptions,\n\n\t\t\tsignal: combinedSignal,\n\t\t} satisfies CallApiRequestOptionsForHooks;\n\n\t\tconst {\n\t\t\tdedupeStrategy,\n\t\t\thandleRequestCancelStrategy,\n\t\t\thandleRequestDeferStrategy,\n\t\t\tremoveDedupeKeyFromCache,\n\t\t} = await createDedupeStrategy({\n\t\t\t$GlobalRequestInfoCache,\n\t\t\t$LocalRequestInfoCache,\n\t\t\tbaseConfig,\n\t\t\tconfig,\n\t\t\tnewFetchController,\n\t\t\toptions,\n\t\t\trequest,\n\t\t});\n\n\t\ttry {\n\t\t\tawait handleRequestCancelStrategy();\n\n\t\t\tawait executeHooksInTryBlock(options.onRequest?.({ baseConfig, config, options, request }));\n\n\t\t\tconst { extraOptionsValidationResult, requestOptionsValidationResult } =\n\t\t\t\tawait handleOptionsValidation({\n\t\t\t\t\textraOptions: options,\n\t\t\t\t\trequestOptions: request,\n\t\t\t\t\tschema: resolvedSchema,\n\t\t\t\t\tschemaConfig: resolvedSchemaConfig,\n\t\t\t\t});\n\n\t\t\tconst shouldApplySchemaOutput =\n\t\t\t\tBoolean(extraOptionsValidationResult)\n\t\t\t\t|| Boolean(requestOptionsValidationResult)\n\t\t\t\t|| !resolvedSchemaConfig?.disableValidationOutputApplication;\n\n\t\t\t// == Apply Schema Output for Extra Options\n\t\t\tif (shouldApplySchemaOutput) {\n\t\t\t\toptions = { ...options, ...extraOptionsValidationResult };\n\t\t\t}\n\n\t\t\t// == Apply Schema Output for Request Options\n\t\t\tconst rawBody = shouldApplySchemaOutput ? requestOptionsValidationResult?.body : request.body;\n\n\t\t\tconst validBody = getBody({\n\t\t\t\tbody: rawBody,\n\t\t\t\tbodySerializer: options.bodySerializer,\n\t\t\t});\n\n\t\t\ttype HeaderFn = Extract<InferHeadersOption<CallApiSchema>[\"headers\"], AnyFunction>;\n\n\t\t\tconst resolvedHeaders =\n\t\t\t\tisFunction<HeaderFn>(fetchOptions.headers) ?\n\t\t\t\t\tfetchOptions.headers({ baseHeaders: baseFetchOptions.headers ?? {} })\n\t\t\t\t:\t(fetchOptions.headers ?? baseFetchOptions.headers);\n\n\t\t\tconst validHeaders = await getHeaders({\n\t\t\t\tauth: options.auth,\n\t\t\t\tbody: rawBody,\n\t\t\t\theaders: shouldApplySchemaOutput ? requestOptionsValidationResult?.headers : resolvedHeaders,\n\t\t\t});\n\n\t\t\tconst validMethod = getMethod({\n\t\t\t\tinitURL: resolvedInitURL,\n\t\t\t\tmethod: shouldApplySchemaOutput ? requestOptionsValidationResult?.method : request.method,\n\t\t\t\tschemaConfig: resolvedSchemaConfig,\n\t\t\t});\n\n\t\t\trequest = {\n\t\t\t\t...request,\n\t\t\t\t...(Boolean(validBody) && { body: validBody }),\n\t\t\t\t...(Boolean(validHeaders) && { headers: validHeaders }),\n\t\t\t\t...(Boolean(validMethod) && { method: validMethod }),\n\t\t\t};\n\n\t\t\tconst response = await handleRequestDeferStrategy({ options, request });\n\n\t\t\t// == Also clone response when dedupeStrategy is set to \"defer\" to avoid error thrown from reading response.(whatever) more than once\n\t\t\tconst shouldCloneResponse = dedupeStrategy === \"defer\" || options.cloneResponse;\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst errorData = await resolveResponseData<TErrorData>(\n\t\t\t\t\tshouldCloneResponse ? response.clone() : response,\n\t\t\t\t\toptions.responseType,\n\t\t\t\t\toptions.responseParser\n\t\t\t\t);\n\n\t\t\t\tconst validErrorData = await handleValidation(resolvedSchema?.errorData, {\n\t\t\t\t\tinputValue: errorData,\n\t\t\t\t\tresponse,\n\t\t\t\t\tschemaConfig: resolvedSchemaConfig,\n\t\t\t\t});\n\n\t\t\t\t// == Push all error handling responsibilities to the catch block if not retrying\n\t\t\t\tthrow new HTTPError(\n\t\t\t\t\t{\n\t\t\t\t\t\tdefaultHTTPErrorMessage: options.defaultHTTPErrorMessage,\n\t\t\t\t\t\terrorData: validErrorData,\n\t\t\t\t\t\tresponse,\n\t\t\t\t\t},\n\t\t\t\t\t{ cause: validErrorData }\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst successData = await resolveResponseData<TData>(\n\t\t\t\tshouldCloneResponse ? response.clone() : response,\n\t\t\t\toptions.responseType,\n\t\t\t\toptions.responseParser\n\t\t\t);\n\n\t\t\tconst validSuccessData = await handleValidation(resolvedSchema?.data, {\n\t\t\t\tinputValue: successData,\n\t\t\t\tresponse,\n\t\t\t\tschemaConfig: resolvedSchemaConfig,\n\t\t\t});\n\n\t\t\tconst successContext = {\n\t\t\t\tbaseConfig,\n\t\t\t\tconfig,\n\t\t\t\tdata: validSuccessData,\n\t\t\t\toptions,\n\t\t\t\trequest,\n\t\t\t\tresponse,\n\t\t\t} satisfies SuccessContext<unknown>;\n\n\t\t\tawait executeHooksInTryBlock(\n\t\t\t\toptions.onSuccess?.(successContext),\n\n\t\t\t\toptions.onResponse?.({ ...successContext, error: null })\n\t\t\t);\n\n\t\t\tconst successResult = resolveSuccessResult(successContext.data, {\n\t\t\t\tresponse: successContext.response,\n\t\t\t\tresultMode: options.resultMode,\n\t\t\t});\n\n\t\t\treturn successResult as never;\n\n\t\t\t// == Exhaustive Error handling\n\t\t} catch (error) {\n\t\t\tconst errorInfo = {\n\t\t\t\tcloneResponse: options.cloneResponse,\n\t\t\t\tresultMode: options.resultMode,\n\t\t\t} satisfies ErrorInfo;\n\n\t\t\tconst generalErrorResult = resolveErrorResult(error, errorInfo);\n\n\t\t\tconst errorContext = {\n\t\t\t\tbaseConfig,\n\t\t\t\tconfig,\n\t\t\t\terror: generalErrorResult?.error as never,\n\t\t\t\toptions,\n\t\t\t\trequest,\n\t\t\t\tresponse: generalErrorResult?.response as never,\n\t\t\t} satisfies ErrorContext<unknown>;\n\n\t\t\tconst shouldThrowOnError = (\n\t\t\t\tisFunction(options.throwOnError) ?\n\t\t\t\t\toptions.throwOnError(errorContext)\n\t\t\t\t:\toptions.throwOnError) as boolean;\n\n\t\t\tconst hookInfo = {\n\t\t\t\terrorInfo,\n\t\t\t\tshouldThrowOnError,\n\t\t\t} satisfies ExecuteHookInfo;\n\n\t\t\tconst handleRetryOrGetErrorResult = async () => {\n\t\t\t\tconst { currentAttemptCount, getDelay, shouldAttemptRetry } =\n\t\t\t\t\tcreateRetryStrategy(errorContext);\n\n\t\t\t\tconst shouldRetry = !combinedSignal.aborted && (await shouldAttemptRetry());\n\n\t\t\t\tif (shouldRetry) {\n\t\t\t\t\tconst retryContext = {\n\t\t\t\t\t\t...errorContext,\n\t\t\t\t\t\tretryAttemptCount: currentAttemptCount,\n\t\t\t\t\t} satisfies RetryContext<unknown>;\n\n\t\t\t\t\tconst hookError = await executeHooksInCatchBlock(\n\t\t\t\t\t\t[options.onRetry?.(retryContext)],\n\t\t\t\t\t\thookInfo\n\t\t\t\t\t);\n\n\t\t\t\t\tif (hookError) {\n\t\t\t\t\t\treturn hookError;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst delay = getDelay();\n\n\t\t\t\t\tawait waitFor(delay);\n\n\t\t\t\t\tconst updatedOptions = {\n\t\t\t\t\t\t...config,\n\t\t\t\t\t\t\"~retryAttemptCount\": currentAttemptCount + 1,\n\t\t\t\t\t} satisfies typeof config;\n\n\t\t\t\t\treturn callApi(initURLOrURLObject as never, updatedOptions as never) as never;\n\t\t\t\t}\n\n\t\t\t\tif (shouldThrowOnError) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\n\t\t\t\treturn generalErrorResult;\n\t\t\t};\n\n\t\t\tif (isHTTPErrorInstance<TErrorData>(error)) {\n\t\t\t\tconst hookError = await executeHooksInCatchBlock(\n\t\t\t\t\t[\n\t\t\t\t\t\toptions.onResponseError?.(errorContext),\n\t\t\t\t\t\toptions.onError?.(errorContext),\n\t\t\t\t\t\toptions.onResponse?.({ ...errorContext, data: null }),\n\t\t\t\t\t],\n\t\t\t\t\thookInfo\n\t\t\t\t);\n\n\t\t\t\treturn (hookError ?? (await handleRetryOrGetErrorResult())) as never;\n\t\t\t}\n\n\t\t\tif (isValidationErrorInstance(error)) {\n\t\t\t\tconst hookError = await executeHooksInCatchBlock(\n\t\t\t\t\t[\n\t\t\t\t\t\toptions.onValidationError?.(errorContext),\n\t\t\t\t\t\toptions.onRequestError?.(errorContext),\n\t\t\t\t\t\toptions.onError?.(errorContext),\n\t\t\t\t\t],\n\t\t\t\t\thookInfo\n\t\t\t\t);\n\n\t\t\t\treturn (hookError ?? (await handleRetryOrGetErrorResult())) as never;\n\t\t\t}\n\n\t\t\tlet message: string | undefined = (error as Error | undefined)?.message;\n\n\t\t\tif (error instanceof DOMException && error.name === \"AbortError\") {\n\t\t\t\tmessage = getAbortErrorMessage(options.dedupeKey, options.fullURL);\n\n\t\t\t\t!shouldThrowOnError && console.error(`${error.name}:`, message);\n\t\t\t}\n\n\t\t\tif (error instanceof DOMException && error.name === \"TimeoutError\") {\n\t\t\t\tmessage = `Request timed out after ${options.timeout}ms`;\n\n\t\t\t\t!shouldThrowOnError && console.error(`${error.name}:`, message);\n\t\t\t}\n\n\t\t\tconst hookError = await executeHooksInCatchBlock(\n\t\t\t\t[options.onRequestError?.(errorContext), options.onError?.(errorContext)],\n\t\t\t\thookInfo\n\t\t\t);\n\n\t\t\treturn (hookError\n\t\t\t\t?? getCustomizedErrorResult(await handleRetryOrGetErrorResult(), { message })) as never;\n\n\t\t\t// == Removing the now unneeded AbortController from store\n\t\t} finally {\n\t\t\tremoveDedupeKeyFromCache();\n\t\t}\n\t};\n\n\treturn callApi;\n};\n\nexport const callApi = createFetchClient();\n","import type { CallApiPlugin } from \"./plugins\";\nimport type { ResponseTypeUnion, ResultModeUnion } from \"./result\";\nimport type { CallApiParameters, InferInitURL, ThrowOnErrorUnion } from \"./types\";\nimport type { DefaultDataType, DefaultPluginArray, DefaultThrowOnError } from \"./types/default-types\";\nimport type { BaseCallApiSchema, CallApiSchema, CallApiSchemaConfig } from \"./validation\";\n\nconst defineParameters = <\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTBaseSchema extends BaseCallApiSchema = BaseCallApiSchema,\n\tTSchema extends CallApiSchema = CallApiSchema,\n\tTBaseSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig,\n\tTSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig,\n\tTInitURL extends InferInitURL<BaseCallApiSchema, TSchemaConfig> = InferInitURL<\n\t\tBaseCallApiSchema,\n\t\tTSchemaConfig\n\t>,\n\tTCurrentRouteKey extends string = string,\n\tTBasePluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTPluginArray extends CallApiPlugin[] = DefaultPluginArray,\n>(\n\t...parameters: CallApiParameters<\n\t\tTData,\n\t\tTErrorData,\n\t\tTResultMode,\n\t\tTThrowOnError,\n\t\tTResponseType,\n\t\tTBaseSchema,\n\t\tTSchema,\n\t\tTBaseSchemaConfig,\n\t\tTSchemaConfig,\n\t\tTInitURL,\n\t\tTCurrentRouteKey,\n\t\tTBasePluginArray,\n\t\tTPluginArray\n\t>\n) => {\n\treturn parameters;\n};\n\nexport { defineParameters };\n"],"mappings":";;;AASA,MAAa,kBAAkB,CAAYA,UAAoBC,YAAoB;CAClF,aAAa,MAAM,SAAS,aAAa;CACzC,MAAM,MAAM,SAAS,MAAM;CAC3B,UAAU,MAAM,SAAS,UAAU;CACnC,MAAM,YAAY;EACjB,MAAM,OAAO,MAAM,SAAS,MAAM;AAClC,SAAO,OAAO,KAAK;CACnB;CACD,QAAQ,MAAM,SAAS;CACvB,MAAM,MAAM,SAAS,MAAM;AAC3B;AAmBD,MAAa,sBAAsB,CAClCD,UACAE,cACAC,WACI;CACJ,MAAM,iBAAiB,UAAU,iBAAiB;CAClD,MAAM,uBAAuB,gBAAgB,iBAAiB;CAE9D,MAAM,uBAAuB,gBAA2B,UAAU,eAAe;AAEjF,MAAK,OAAO,OAAO,sBAAsB,qBAAqB,CAC7D,OAAM,IAAI,OAAO,yBAAyB;AAG3C,QAAO,qBAAqB,uBAAuB;AACnD;AA+FD,MAAM,mBAAmB,CACxBC,YACI;CACJ,MAAM,gBAAgB;EACrB,KAAK,MAAM;EACX,kBAAkB,MAAM,cAAc,KAAK;EAC3C,aAAa,MAAM,QAAQ;EAC3B,0BAA0B,MAAM,cAAc,aAAa;CAC3D;AAED,QAAO;AACP;AAMD,MAAa,uBAAuB,CAACC,MAAeC,SAAqC;CACxF,MAAM,EAAE,UAAU,YAAY,GAAG;CAEjC,MAAM,UAAU;EACf;EACA,OAAO;EACP;CACA;CAED,MAAM,gBAAgB,iBAAiB,QAAQ;CAE/C,MAAM,gBAAgB,cAAc,cAAc,QAAQ;AAE1D,QAAO;AACP;AAUD,MAAa,qBAAqB,CAACC,OAAgBC,SAAiC;CACnF,MAAM,EAAE,eAAe,SAAS,oBAAoB,YAAY,GAAG;CAEnE,IAAI,UAAU;EACb,MAAM;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AAM,6BAA6B;GACzD;AAED,OAAI,0BAA0B,MAAM,EAAE;IACrC,MAAMA,cAAY,MAAM,yBACvB;KACC,QAAQ,oBAAoB,aAAa;KACzC,QAAQ,iBAAiB,aAAa;KACtC,QAAQ,UAAU,aAAa;IAC/B,GACD,SACA;AAED,WAAQA,eAAc,MAAM,6BAA6B;GACzD;GAED,IAAIC,UAA+B,OAA6B;AAEhE,OAAI,iBAAiB,gBAAgB,MAAM,SAAS,cAAc;AACjE,cAAU,qBAAqB,QAAQ,WAAW,QAAQ,QAAQ;AAElE,KAAC,sBAAsB,QAAQ,SAAS,MAAM,KAAK,IAAI,QAAQ;GAC/D;AAED,OAAI,iBAAiB,gBAAgB,MAAM,SAAS,gBAAgB;AACnE,eAAW,0BAA0B,QAAQ,QAAQ;AAErD,KAAC,sBAAsB,QAAQ,SAAS,MAAM,KAAK,IAAI,QAAQ;GAC/D;GAED,MAAM,YAAY,MAAM,yBACvB,CAAC,QAAQ,iBAAiB,aAAa,EAAE,QAAQ,UAAU,aAAa,AAAC,GACzE,SACA;AAED,UAAQ,aACJ,yBAAyB,MAAM,6BAA6B,EAAE,EAAE,QAAS,EAAC;EAG9E,UAAS;AACT,6BAA0B;EAC1B;CACD;AAED,QAAOF;AACP;AAED,MAAa,UAAU,mBAAmB;;;;ACxd1C,MAAM,mBAAmB,CAkBxB,GAAG,eAeC;AACJ,QAAO;AACP"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import { CallApiExtraOptions, CallApiResultErrorVariant, HTTPError, PossibleHTTPError, PossibleJavaScriptError, PossibleValidationError, ValidationError } from "../common-
|
1
|
+
import { CallApiExtraOptions, CallApiResultErrorVariant, HTTPError, PossibleHTTPError, PossibleJavaScriptError, PossibleValidationError, ValidationError } from "../common-CmLbOQH8.js";
|
2
2
|
|
3
3
|
//#region src/utils/common.d.ts
|
4
4
|
|
package/dist/esm/utils/index.js
CHANGED
@@ -1,3 +1,3 @@
|
|
1
|
-
import { isHTTPError, isHTTPErrorInstance, isJavascriptError, isValidationError, isValidationErrorInstance, toQueryString } from "../utils-
|
1
|
+
import { isHTTPError, isHTTPErrorInstance, isJavascriptError, isValidationError, isValidationErrorInstance, toQueryString } from "../utils-BMQYfuNI.js";
|
2
2
|
|
3
3
|
export { isHTTPError, isHTTPErrorInstance, isJavascriptError, isValidationError, isValidationErrorInstance, toQueryString };
|
@@ -51,8 +51,12 @@ var HTTPError = class HTTPError extends Error {
|
|
51
51
|
name = "HTTPError";
|
52
52
|
response;
|
53
53
|
constructor(errorDetails, errorOptions) {
|
54
|
-
const {
|
55
|
-
const
|
54
|
+
const { defaultHTTPErrorMessage, errorData, response } = errorDetails;
|
55
|
+
const resolvedDefaultHTTPErrorMessage = isString(defaultHTTPErrorMessage) ? defaultHTTPErrorMessage : defaultHTTPErrorMessage?.({
|
56
|
+
errorData,
|
57
|
+
response
|
58
|
+
});
|
59
|
+
const selectedDefaultErrorMessage = resolvedDefaultHTTPErrorMessage ?? (response.statusText || commonDefaults.defaultErrorMessage);
|
56
60
|
const message = errorData?.message ?? selectedDefaultErrorMessage;
|
57
61
|
super(message, errorOptions);
|
58
62
|
this.errorData = errorData;
|
@@ -296,7 +300,16 @@ const createCombinedSignal = (...signals) => {
|
|
296
300
|
return combinedSignal;
|
297
301
|
};
|
298
302
|
const createTimeoutSignal = (milliseconds) => AbortSignal.timeout(milliseconds);
|
303
|
+
const deterministicHashFn = (value) => {
|
304
|
+
return JSON.stringify(value, (_, val) => {
|
305
|
+
if (!isPlainObject(val)) return val;
|
306
|
+
const sortedKeys = Object.keys(val).sort();
|
307
|
+
const result = {};
|
308
|
+
for (const key of sortedKeys) result[key] = val[key];
|
309
|
+
return result;
|
310
|
+
});
|
311
|
+
};
|
299
312
|
|
300
313
|
//#endregion
|
301
|
-
export { HTTPError, ValidationError,
|
302
|
-
//# sourceMappingURL=utils-
|
314
|
+
export { HTTPError, ValidationError, createCombinedSignal, createTimeoutSignal, dedupeDefaults, defineEnum, deterministicHashFn, getBody, getFetchImpl, getHeaders, hookDefaults, isArray, isFunction, isHTTPError, isHTTPErrorInstance, isJavascriptError, isObject, isPlainObject, isReadableStream, isString, isValidationError, isValidationErrorInstance, requestOptionDefaults, responseDefaults, retryDefaults, splitBaseConfig, splitConfig, toQueryString, waitFor };
|
315
|
+
//# sourceMappingURL=utils-BMQYfuNI.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"utils-BMQYfuNI.js","names":["value: TValue","errorDetails: HTTPErrorDetails<TErrorData>","errorOptions?: ErrorOptions","error: unknown","path: ValidationError[\"errorData\"][number][\"path\"]","issues: ValidationError[\"errorData\"]","details: ValidationErrorDetails","error: CallApiResultErrorVariant<TErrorData>[\"error\"] | null","error: unknown","error: CallApiResultErrorVariant<unknown>[\"error\"] | null","value: unknown","value: ValidAuthValue","auth: CallApiExtraOptions[\"auth\"]","initialObject: TObject","keysToOmit: TOmitArray","keysToPick: TPickArray","baseConfig: Record<string, any>","config: Record<string, any>","toQueryString: ToQueryStringFn","headers: CallApiRequestOptions[\"headers\"]","options: GetHeadersOptions","headersObject: Record<string, string | undefined>","options: GetBodyOptions","customFetchImpl: CallApiExtraOptions[\"customFetchImpl\"]","reject!: (reason?: unknown) => void","resolve!: (value: unknown) => void","delay: number","milliseconds: number","value: unknown","val: unknown","result: Record<string, unknown>"],"sources":["../../src/types/type-helpers.ts","../../src/constants/default-options.ts","../../src/error.ts","../../src/utils/guards.ts","../../src/auth.ts","../../src/constants/common.ts","../../src/utils/common.ts"],"sourcesContent":["// == These two types allows for adding arbitrary literal types, while still provided autocomplete for defaults.\n// == Usually intersection with \"{}\" or \"NonNullable<unknown>\" would make it work fine, but the placeholder with never type is added to make the AnyWhatever type appear last in a given union.\nexport type AnyString = string & NonNullable<unknown>;\nexport type AnyNumber = number & NonNullable<unknown>;\n\n// eslint-disable-next-line ts-eslint/no-explicit-any -- Any is fine here\nexport type AnyObject = Record<keyof any, any>;\n\n// eslint-disable-next-line ts-eslint/no-explicit-any -- Any is required here so that one can pass custom function type without type errors\nexport type AnyFunction<TResult = unknown> = (...args: any[]) => TResult;\n\nexport type CallbackFn<in TParams, out TResult = void> = (...params: TParams[]) => TResult;\n\nexport type Prettify<TObject> = NonNullable<unknown> & { [Key in keyof TObject]: TObject[Key] };\n\nexport type WriteableLevel = \"deep\" | \"shallow\";\n\n/**\n * Makes all properties in an object type writeable (removes readonly modifiers).\n * Supports both shallow and deep modes, and handles special cases like arrays, tuples, and unions.\n * @template TObject - The object type to make writeable\n * @template TVariant - The level of writeable transformation (\"shallow\" | \"deep\")\n */\n\ntype ArrayOrObject = Record<number | string | symbol, unknown> | unknown[];\n\nexport type Writeable<TObject, TLevel extends WriteableLevel = \"shallow\"> =\n\tTObject extends readonly [...infer TTupleItems] ?\n\t\t[\n\t\t\t...{\n\t\t\t\t[Index in keyof TTupleItems]: TLevel extends \"deep\" ? Writeable<TTupleItems[Index], \"deep\">\n\t\t\t\t:\tTTupleItems[Index];\n\t\t\t},\n\t\t]\n\t: TObject extends ArrayOrObject ?\n\t\t{\n\t\t\t-readonly [Key in keyof TObject]: TLevel extends \"deep\" ? Writeable<TObject[Key], \"deep\">\n\t\t\t:\tTObject[Key];\n\t\t}\n\t:\tTObject;\n\nexport const defineEnum = <const TValue extends object>(value: TValue) => value as Writeable<TValue>;\n\nexport type UnionToIntersection<TUnion> =\n\t(TUnion extends unknown ? (param: TUnion) => void : never) extends (param: infer TParam) => void ?\n\t\tTParam\n\t:\tnever;\n\n// == Using this Immediately Indexed Mapped type helper to help show computed type of anything passed to it instead of just the type name\nexport type UnmaskType<TValue> = { _: TValue }[\"_\"];\n\nexport type Awaitable<TValue> = Promise<TValue> | TValue;\n\nexport type CommonRequestHeaders =\n\t| \"Access-Control-Allow-Credentials\"\n\t| \"Access-Control-Allow-Headers\"\n\t| \"Access-Control-Allow-Methods\"\n\t| \"Access-Control-Allow-Origin\"\n\t| \"Access-Control-Expose-Headers\"\n\t| \"Access-Control-Max-Age\"\n\t| \"Age\"\n\t| \"Allow\"\n\t| \"Cache-Control\"\n\t| \"Clear-Site-Data\"\n\t| \"Content-Disposition\"\n\t| \"Content-Encoding\"\n\t| \"Content-Language\"\n\t| \"Content-Length\"\n\t| \"Content-Location\"\n\t| \"Content-Range\"\n\t| \"Content-Security-Policy-Report-Only\"\n\t| \"Content-Security-Policy\"\n\t| \"Cookie\"\n\t| \"Cross-Origin-Embedder-Policy\"\n\t| \"Cross-Origin-Opener-Policy\"\n\t| \"Cross-Origin-Resource-Policy\"\n\t| \"Date\"\n\t| \"ETag\"\n\t| \"Expires\"\n\t| \"Last-Modified\"\n\t| \"Location\"\n\t| \"Permissions-Policy\"\n\t| \"Pragma\"\n\t| \"Retry-After\"\n\t| \"Save-Data\"\n\t| \"Sec-CH-Prefers-Color-Scheme\"\n\t| \"Sec-CH-Prefers-Reduced-Motion\"\n\t| \"Sec-CH-UA-Arch\"\n\t| \"Sec-CH-UA-Bitness\"\n\t| \"Sec-CH-UA-Form-Factor\"\n\t| \"Sec-CH-UA-Full-Version-List\"\n\t| \"Sec-CH-UA-Full-Version\"\n\t| \"Sec-CH-UA-Mobile\"\n\t| \"Sec-CH-UA-Model\"\n\t| \"Sec-CH-UA-Platform-Version\"\n\t| \"Sec-CH-UA-Platform\"\n\t| \"Sec-CH-UA-WoW64\"\n\t| \"Sec-CH-UA\"\n\t| \"Sec-Fetch-Dest\"\n\t| \"Sec-Fetch-Mode\"\n\t| \"Sec-Fetch-Site\"\n\t| \"Sec-Fetch-User\"\n\t| \"Sec-GPC\"\n\t| \"Server-Timing\"\n\t| \"Server\"\n\t| \"Service-Worker-Navigation-Preload\"\n\t| \"Set-Cookie\"\n\t| \"Strict-Transport-Security\"\n\t| \"Timing-Allow-Origin\"\n\t| \"Trailer\"\n\t| \"Transfer-Encoding\"\n\t| \"Upgrade\"\n\t| \"Vary\"\n\t| \"Warning\"\n\t| \"WWW-Authenticate\"\n\t| \"X-Content-Type-Options\"\n\t| \"X-DNS-Prefetch-Control\"\n\t| \"X-Frame-Options\"\n\t| \"X-Permitted-Cross-Domain-Policies\"\n\t| \"X-Powered-By\"\n\t| \"X-Robots-Tag\"\n\t| \"X-XSS-Protection\"\n\t| AnyString;\n\nexport type CommonAuthorizationHeaders = `${\"Basic\" | \"Bearer\" | \"Token\"} ${string}`;\n\nexport type CommonContentTypes =\n\t| \"application/epub+zip\"\n\t| \"application/gzip\"\n\t| \"application/json\"\n\t| \"application/ld+json\"\n\t| \"application/octet-stream\"\n\t| \"application/ogg\"\n\t| \"application/pdf\"\n\t| \"application/rtf\"\n\t| \"application/vnd.ms-fontobject\"\n\t| \"application/wasm\"\n\t| \"application/xhtml+xml\"\n\t| \"application/xml\"\n\t| \"application/zip\"\n\t| \"audio/aac\"\n\t| \"audio/mpeg\"\n\t| \"audio/ogg\"\n\t| \"audio/opus\"\n\t| \"audio/webm\"\n\t| \"audio/x-midi\"\n\t| \"font/otf\"\n\t| \"font/ttf\"\n\t| \"font/woff\"\n\t| \"font/woff2\"\n\t| \"image/avif\"\n\t| \"image/bmp\"\n\t| \"image/gif\"\n\t| \"image/jpeg\"\n\t| \"image/png\"\n\t| \"image/svg+xml\"\n\t| \"image/tiff\"\n\t| \"image/webp\"\n\t| \"image/x-icon\"\n\t| \"model/gltf-binary\"\n\t| \"model/gltf+json\"\n\t| \"text/calendar\"\n\t| \"text/css\"\n\t| \"text/csv\"\n\t| \"text/html\"\n\t| \"text/javascript\"\n\t| \"text/plain\"\n\t| \"video/3gpp\"\n\t| \"video/3gpp2\"\n\t| \"video/av1\"\n\t| \"video/mp2t\"\n\t| \"video/mp4\"\n\t| \"video/mpeg\"\n\t| \"video/ogg\"\n\t| \"video/webm\"\n\t| \"video/x-msvideo\"\n\t| AnyString;\n","import type { CallApiExtraOptions } from \"../types/common\";\nimport { defineEnum } from \"../types/type-helpers\";\n\nexport const retryDefaults = defineEnum({\n\tattempts: 0,\n\tcondition: () => true,\n\tdelay: 1000,\n\tmaxDelay: 10000,\n\tmethods: [\"GET\", \"POST\"] satisfies CallApiExtraOptions[\"retryMethods\"],\n\tstatusCodes: [] satisfies CallApiExtraOptions[\"retryStatusCodes\"],\n\tstrategy: \"linear\",\n});\n\nexport const defaultRetryStatusCodesLookup = defineEnum({\n\t408: \"Request Timeout\",\n\t409: \"Conflict\",\n\t425: \"Too Early\",\n\t429: \"Too Many Requests\",\n\t500: \"Internal Server Error\",\n\t502: \"Bad Gateway\",\n\t503: \"Service Unavailable\",\n\t504: \"Gateway Timeout\",\n});\n\nexport const commonDefaults = defineEnum({\n\tbodySerializer: JSON.stringify,\n\tdefaultErrorMessage: \"An unexpected error occurred during the HTTP request.\",\n});\n\nexport const responseDefaults = defineEnum({\n\tresponseParser: JSON.parse,\n\tresponseType: \"json\",\n\tresultMode: \"all\",\n});\n\nexport const hookDefaults = defineEnum({\n\tmergedHooksExecutionMode: \"parallel\",\n\tmergedHooksExecutionOrder: \"mainHooksAfterPlugins\",\n});\n\nexport const dedupeDefaults = defineEnum({\n\tdedupeCacheScope: \"local\",\n\tdedupeStrategy: \"cancel\",\n});\n\nexport const requestOptionDefaults = defineEnum({\n\tmethod: \"GET\",\n});\n","import { commonDefaults } from \"./constants/default-options\";\nimport type { CallApiExtraOptions } from \"./types\";\nimport type { StandardSchemaV1 } from \"./types/standard-schema\";\nimport { isObject, isString } from \"./utils/guards\";\n\ntype HTTPErrorDetails<TErrorData> = Pick<CallApiExtraOptions, \"defaultHTTPErrorMessage\"> & {\n\terrorData: TErrorData;\n\tresponse: Response;\n};\n\nconst httpErrorSymbol = Symbol(\"HTTPError\");\n\nexport class HTTPError<TErrorData = Record<string, unknown>> extends Error {\n\terrorData: HTTPErrorDetails<TErrorData>[\"errorData\"];\n\n\thttpErrorSymbol = httpErrorSymbol;\n\n\tisHTTPError = true;\n\n\toverride name = \"HTTPError\" as const;\n\n\tresponse: HTTPErrorDetails<TErrorData>[\"response\"];\n\n\tconstructor(errorDetails: HTTPErrorDetails<TErrorData>, errorOptions?: ErrorOptions) {\n\t\tconst { defaultHTTPErrorMessage, errorData, response } = errorDetails;\n\n\t\tconst resolvedDefaultHTTPErrorMessage =\n\t\t\tisString(defaultHTTPErrorMessage) ? defaultHTTPErrorMessage : (\n\t\t\t\tdefaultHTTPErrorMessage?.({ errorData, response })\n\t\t\t);\n\n\t\tconst selectedDefaultErrorMessage =\n\t\t\tresolvedDefaultHTTPErrorMessage ?? (response.statusText || commonDefaults.defaultErrorMessage);\n\n\t\tconst message =\n\t\t\t(errorData as { message?: string } | undefined)?.message ?? selectedDefaultErrorMessage;\n\n\t\tsuper(message, errorOptions);\n\n\t\tthis.errorData = errorData;\n\t\tthis.response = response;\n\t\tError.captureStackTrace(this, this.constructor);\n\t}\n\n\t/**\n\t * @description Checks if the given error is an instance of HTTPError\n\t * @param error - The error to check\n\t * @returns true if the error is an instance of HTTPError, false otherwise\n\t */\n\tstatic isError<TErrorData>(error: unknown): error is HTTPError<TErrorData> {\n\t\tif (!isObject<Record<string, unknown>>(error)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (error instanceof HTTPError) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn error.httpErrorSymbol === httpErrorSymbol && error.isHTTPError === true;\n\t}\n}\n\nconst prettifyPath = (path: ValidationError[\"errorData\"][number][\"path\"]) => {\n\tif (!path || path.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst pathString = path.map((segment) => (isObject(segment) ? segment.key : segment)).join(\".\");\n\n\treturn ` → at ${pathString}`;\n};\n\nconst prettifyValidationIssues = (issues: ValidationError[\"errorData\"]) => {\n\tconst issuesString = issues\n\t\t.map((issue) => `✖ ${issue.message}${prettifyPath(issue.path)}`)\n\t\t.join(\" | \");\n\n\treturn issuesString;\n};\n\ntype ValidationErrorDetails = {\n\tissues: readonly StandardSchemaV1.Issue[];\n\tresponse: Response | null;\n};\n\nconst validationErrorSymbol = Symbol(\"validationErrorSymbol\");\n\nexport class ValidationError extends Error {\n\terrorData: ValidationErrorDetails[\"issues\"];\n\n\toverride name = \"ValidationError\";\n\n\tresponse: ValidationErrorDetails[\"response\"];\n\n\tvalidationErrorSymbol = validationErrorSymbol;\n\n\tconstructor(details: ValidationErrorDetails, errorOptions?: ErrorOptions) {\n\t\tconst { issues, response } = details;\n\n\t\tconst message = prettifyValidationIssues(issues);\n\n\t\tsuper(message, errorOptions);\n\n\t\tthis.errorData = issues;\n\t\tthis.response = response;\n\n\t\tError.captureStackTrace(this, this.constructor);\n\t}\n\n\t/**\n\t * @description Checks if the given error is an instance of HTTPError\n\t * @param error - The error to check\n\t * @returns true if the error is an instance of HTTPError, false otherwise\n\t */\n\tstatic isError(error: unknown): error is ValidationError {\n\t\tif (!isObject<Record<string, unknown>>(error)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (error instanceof ValidationError) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn error.validationErrorSymbol === validationErrorSymbol && error.name === \"ValidationError\";\n\t}\n}\n","import { HTTPError, ValidationError } from \"../error\";\nimport type {\n\tCallApiResultErrorVariant,\n\tPossibleHTTPError,\n\tPossibleJavaScriptError,\n\tPossibleValidationError,\n} from \"../result\";\nimport type { AnyFunction } from \"../types/type-helpers\";\n\nexport const isHTTPError = <TErrorData>(\n\terror: CallApiResultErrorVariant<TErrorData>[\"error\"] | null\n): error is PossibleHTTPError<TErrorData> => {\n\treturn isObject(error) && error.name === \"HTTPError\";\n};\n\nexport const isHTTPErrorInstance = <TErrorData>(error: unknown) => {\n\treturn HTTPError.isError<TErrorData>(error);\n};\n\nexport const isValidationError = (\n\terror: CallApiResultErrorVariant<unknown>[\"error\"] | null\n): error is PossibleValidationError => {\n\treturn isObject(error) && error.name === \"ValidationError\";\n};\n\nexport const isValidationErrorInstance = (error: unknown): error is ValidationError => {\n\treturn ValidationError.isError(error);\n};\n\nexport const isJavascriptError = (\n\terror: CallApiResultErrorVariant<unknown>[\"error\"] | null\n): error is PossibleJavaScriptError => {\n\treturn isObject(error) && !isHTTPError(error) && !isValidationError(error);\n};\n\nexport const isArray = <TArrayItem>(value: unknown): value is TArrayItem[] => Array.isArray(value);\n\nexport const isObject = <TObject extends object>(value: unknown): value is TObject => {\n\treturn typeof value === \"object\" && value !== null;\n};\n\nconst hasObjectPrototype = (value: unknown) => {\n\treturn Object.prototype.toString.call(value) === \"[object Object]\";\n};\n\n/**\n * @description Copied from TanStack Query's isPlainObject\n * @see https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L321\n */\nexport const isPlainObject = <TPlainObject extends Record<string, unknown>>(\n\tvalue: unknown\n): value is TPlainObject => {\n\tif (!hasObjectPrototype(value)) {\n\t\treturn false;\n\t}\n\n\t// If has no constructor\n\tconst constructor = (value as object | undefined)?.constructor;\n\tif (constructor === undefined) {\n\t\treturn true;\n\t}\n\n\t// If has modified prototype\n\tconst prototype = constructor.prototype as object;\n\tif (!hasObjectPrototype(prototype)) {\n\t\treturn false;\n\t}\n\n\t// If constructor does not have an Object-specific method\n\tif (!Object.hasOwn(prototype, \"isPrototypeOf\")) {\n\t\treturn false;\n\t}\n\n\t// Handles Objects created by Object.create(<arbitrary prototype>)\n\tif (Object.getPrototypeOf(value) !== Object.prototype) {\n\t\treturn false;\n\t}\n\n\t// It's probably a plain object at this point\n\treturn true;\n};\n\nexport const isJsonString = (value: unknown): value is string => {\n\tif (!isString(value)) {\n\t\treturn false;\n\t}\n\n\ttry {\n\t\tJSON.parse(value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\nexport const isSerializable = (value: unknown) => {\n\treturn (\n\t\tisPlainObject(value)\n\t\t|| isArray(value)\n\t\t|| typeof (value as { toJSON: unknown } | undefined)?.toJSON === \"function\"\n\t);\n};\n\nexport const isFunction = <TFunction extends AnyFunction>(value: unknown): value is TFunction =>\n\ttypeof value === \"function\";\n\nexport const isQueryString = (value: unknown): value is string => isString(value) && value.includes(\"=\");\n\nexport const isString = (value: unknown) => typeof value === \"string\";\n\nexport const isReadableStream = (value: unknown): value is ReadableStream<unknown> => {\n\treturn value instanceof ReadableStream;\n};\n\n// https://github.com/unjs/ofetch/blob/main/src/utils.ts\nexport const isJSONSerializable = (value: unknown) => {\n\tif (value === undefined) {\n\t\treturn false;\n\t}\n\tconst t = typeof value;\n\t// eslint-disable-next-line ts-eslint/no-unnecessary-condition -- No time to make this more type-safe\n\tif (t === \"string\" || t === \"number\" || t === \"boolean\" || t === null) {\n\t\treturn true;\n\t}\n\tif (t !== \"object\") {\n\t\treturn false;\n\t}\n\tif (isArray(value)) {\n\t\treturn true;\n\t}\n\tif ((value as Buffer | null)?.buffer) {\n\t\treturn false;\n\t}\n\n\treturn (\n\t\t(value?.constructor && value.constructor.name === \"Object\")\n\t\t// eslint-disable-next-line ts-eslint/prefer-nullish-coalescing -- Nullish coalescing makes no sense in this boolean context\n\t\t|| typeof (value as { toJSON: () => unknown } | null)?.toJSON === \"function\"\n\t);\n};\n","/* eslint-disable perfectionist/sort-object-types -- Avoid Sorting for now */\n\nimport type { CallApiExtraOptions } from \"./types/common\";\nimport type { Awaitable } from \"./types/type-helpers\";\nimport { isFunction, isString } from \"./utils/guards\";\n\ntype ValueOrFunctionResult<TValue> = TValue | (() => TValue);\n\ntype ValidAuthValue = ValueOrFunctionResult<Awaitable<string | null | undefined>>;\n\n/**\n * Bearer Or Token authentication\n *\n * The value of `bearer` will be added to a header as\n * `auth: Bearer some-auth-token`,\n *\n * The value of `token` will be added to a header as\n * `auth: Token some-auth-token`,\n */\nexport type BearerOrTokenAuth =\n\t| {\n\t\t\ttype?: \"Bearer\";\n\t\t\tbearer?: ValidAuthValue;\n\t\t\ttoken?: never;\n\t }\n\t| {\n\t\t\ttype?: \"Token\";\n\t\t\tbearer?: never;\n\t\t\ttoken?: ValidAuthValue;\n\t };\n\n/**\n * Basic auth\n */\nexport type BasicAuth = {\n\ttype: \"Basic\";\n\tusername: ValidAuthValue;\n\tpassword: ValidAuthValue;\n};\n\n/**\n * Custom auth\n *\n * @param prefix - prefix of the header\n * @param authValue - value of the header\n *\n * @example\n * ```ts\n * {\n * type: \"Custom\",\n * prefix: \"Token\",\n * authValue: \"token\"\n * }\n * ```\n */\nexport type CustomAuth = {\n\ttype: \"Custom\";\n\tprefix: ValidAuthValue;\n\tvalue: ValidAuthValue;\n};\n\n// eslint-disable-next-line perfectionist/sort-union-types -- Let the first one be first\nexport type Auth = BearerOrTokenAuth | BasicAuth | CustomAuth;\n\nconst getValue = (value: ValidAuthValue) => {\n\treturn isFunction(value) ? value() : value;\n};\n\ntype AuthorizationHeader = {\n\tAuthorization: string;\n};\n\nexport const getAuthHeader = async (\n\tauth: CallApiExtraOptions[\"auth\"]\n): Promise<AuthorizationHeader | undefined> => {\n\tif (auth === undefined) return;\n\n\tif (isString(auth) || auth === null) {\n\t\treturn { Authorization: `Bearer ${auth}` };\n\t}\n\n\tswitch (auth.type) {\n\t\tcase \"Basic\": {\n\t\t\tconst username = await getValue(auth.username);\n\t\t\tconst password = await getValue(auth.password);\n\n\t\t\tif (username === undefined || password === undefined) return;\n\n\t\t\treturn {\n\t\t\t\tAuthorization: `Basic ${globalThis.btoa(`${username}:${password}`)}`,\n\t\t\t};\n\t\t}\n\n\t\tcase \"Custom\": {\n\t\t\tconst value = await getValue(auth.value);\n\n\t\t\tif (value === undefined) return;\n\n\t\t\tconst prefix = await getValue(auth.prefix);\n\n\t\t\treturn {\n\t\t\t\tAuthorization: `${prefix} ${value}`,\n\t\t\t};\n\t\t}\n\n\t\tdefault: {\n\t\t\tconst bearer = await getValue(auth.bearer);\n\t\t\tconst token = await getValue(auth.token);\n\n\t\t\tif (\"token\" in auth && token !== undefined) {\n\t\t\t\treturn { Authorization: `Token ${token}` };\n\t\t\t}\n\n\t\t\tif (bearer === undefined) return;\n\n\t\t\treturn { Authorization: `Bearer ${bearer}` };\n\t\t}\n\t}\n};\n","import type { ModifiedRequestInit } from \"../types\";\nimport { defineEnum } from \"../types/type-helpers\";\n\nexport const fetchSpecificKeys = defineEnum([\n\t\"body\",\n\t\"integrity\",\n\t\"duplex\",\n\t\"method\",\n\t\"headers\",\n\t\"signal\",\n\t\"cache\",\n\t\"redirect\",\n\t\"window\",\n\t\"credentials\",\n\t\"keepalive\",\n\t\"referrer\",\n\t\"priority\",\n\t\"mode\",\n\t\"referrerPolicy\",\n] satisfies Array<keyof ModifiedRequestInit> as Array<keyof ModifiedRequestInit>);\n","import { getAuthHeader } from \"../auth\";\nimport { fetchSpecificKeys } from \"../constants/common\";\nimport { commonDefaults } from \"../constants/default-options\";\nimport type { BaseCallApiExtraOptions, CallApiExtraOptions, CallApiRequestOptions } from \"../types/common\";\nimport { isFunction, isJsonString, isPlainObject, isQueryString, isSerializable } from \"./guards\";\n\nexport const omitKeys = <\n\tTObject extends Record<string, unknown>,\n\tconst TOmitArray extends Array<keyof TObject>,\n>(\n\tinitialObject: TObject,\n\tkeysToOmit: TOmitArray\n) => {\n\tconst updatedObject = {} as Record<string, unknown>;\n\n\tconst keysToOmitSet = new Set(keysToOmit);\n\n\tfor (const [key, value] of Object.entries(initialObject)) {\n\t\tif (!keysToOmitSet.has(key)) {\n\t\t\tupdatedObject[key] = value;\n\t\t}\n\t}\n\n\treturn updatedObject as Omit<TObject, TOmitArray[number]>;\n};\n\nexport const pickKeys = <\n\tTObject extends Record<string, unknown>,\n\tconst TPickArray extends Array<keyof TObject>,\n>(\n\tinitialObject: TObject,\n\tkeysToPick: TPickArray\n) => {\n\tconst updatedObject = {} as Record<string, unknown>;\n\n\tconst keysToPickSet = new Set(keysToPick);\n\n\tfor (const [key, value] of Object.entries(initialObject)) {\n\t\tif (keysToPickSet.has(key)) {\n\t\t\tupdatedObject[key] = value;\n\t\t}\n\t}\n\n\treturn updatedObject as Pick<TObject, TPickArray[number]>;\n};\n\n// eslint-disable-next-line ts-eslint/no-explicit-any -- Any is required here so that one can pass custom function type without type errors\nexport const splitBaseConfig = (baseConfig: Record<string, any>) =>\n\t[\n\t\tpickKeys(baseConfig, fetchSpecificKeys) as CallApiRequestOptions,\n\t\tomitKeys(baseConfig, fetchSpecificKeys) as BaseCallApiExtraOptions,\n\t] as const;\n\n// eslint-disable-next-line ts-eslint/no-explicit-any -- Any is required here so that one can pass custom function type without type errors\nexport const splitConfig = (config: Record<string, any>) =>\n\t[\n\t\tpickKeys(config, fetchSpecificKeys) as CallApiRequestOptions,\n\t\tomitKeys(config, fetchSpecificKeys) as CallApiExtraOptions,\n\t] as const;\n\ntype ToQueryStringFn = {\n\t(params: CallApiExtraOptions[\"query\"]): string | null;\n\t(params: Required<CallApiExtraOptions>[\"query\"]): string;\n};\n\nexport const toQueryString: ToQueryStringFn = (params) => {\n\tif (!params) {\n\t\tconsole.error(\"toQueryString:\", \"No query params provided!\");\n\n\t\treturn null as never;\n\t}\n\n\treturn new URLSearchParams(params as Record<string, string>).toString();\n};\n\nexport const objectifyHeaders = (headers: CallApiRequestOptions[\"headers\"]) => {\n\tif (!headers || isPlainObject(headers)) {\n\t\treturn headers;\n\t}\n\n\treturn Object.fromEntries(headers);\n};\n\nexport type GetHeadersOptions = {\n\tauth: CallApiExtraOptions[\"auth\"];\n\tbody: CallApiRequestOptions[\"body\"];\n\theaders: CallApiRequestOptions[\"headers\"];\n};\n\nexport const getHeaders = async (options: GetHeadersOptions) => {\n\tconst { auth, body, headers } = options;\n\n\t// == Return early if any of the following conditions are not met (so that native fetch would auto set the correct headers):\n\tconst shouldResolveHeaders = Boolean(headers) || Boolean(body) || Boolean(auth);\n\n\tif (!shouldResolveHeaders) return;\n\n\tconst headersObject: Record<string, string | undefined> = {\n\t\t...(await getAuthHeader(auth)),\n\t\t...objectifyHeaders(headers),\n\t};\n\n\tif (isQueryString(body)) {\n\t\theadersObject[\"Content-Type\"] = \"application/x-www-form-urlencoded\";\n\n\t\treturn headersObject;\n\t}\n\n\tif (isSerializable(body) || isJsonString(body)) {\n\t\theadersObject[\"Content-Type\"] = \"application/json\";\n\t\theadersObject.Accept = \"application/json\";\n\t}\n\n\treturn headersObject;\n};\n\nexport type GetBodyOptions = {\n\tbody: CallApiRequestOptions[\"body\"];\n\tbodySerializer: CallApiExtraOptions[\"bodySerializer\"];\n};\n\nexport const getBody = (options: GetBodyOptions) => {\n\tconst { body, bodySerializer } = options;\n\n\tif (isSerializable(body)) {\n\t\tconst selectedBodySerializer = bodySerializer ?? commonDefaults.bodySerializer;\n\n\t\treturn selectedBodySerializer(body);\n\t}\n\n\treturn body;\n};\n\nexport const getFetchImpl = (customFetchImpl: CallApiExtraOptions[\"customFetchImpl\"]) => {\n\tif (customFetchImpl) {\n\t\treturn customFetchImpl;\n\t}\n\n\tif (typeof globalThis !== \"undefined\" && isFunction(globalThis.fetch)) {\n\t\treturn globalThis.fetch;\n\t}\n\n\tthrow new Error(\"No fetch implementation found\");\n};\n\nconst PromiseWithResolvers = () => {\n\tlet reject!: (reason?: unknown) => void;\n\tlet resolve!: (value: unknown) => void;\n\n\tconst promise = new Promise((res, rej) => {\n\t\tresolve = res;\n\t\treject = rej;\n\t});\n\n\treturn { promise, reject, resolve };\n};\n\nexport const waitFor = (delay: number) => {\n\tif (delay === 0) return;\n\n\tconst { promise, resolve } = PromiseWithResolvers();\n\n\tsetTimeout(resolve, delay);\n\n\treturn promise;\n};\n\nexport const createCombinedSignal = (...signals: Array<AbortSignal | null | undefined>) => {\n\tconst cleanedSignals = signals.filter(Boolean);\n\n\tconst combinedSignal = AbortSignal.any(cleanedSignals);\n\n\treturn combinedSignal;\n};\n\nexport const createTimeoutSignal = (milliseconds: number) => AbortSignal.timeout(milliseconds);\n\nexport const deterministicHashFn = (value: unknown): string => {\n\treturn JSON.stringify(value, (_, val: unknown) => {\n\t\tif (!isPlainObject(val)) {\n\t\t\treturn val;\n\t\t}\n\n\t\tconst sortedKeys = Object.keys(val).sort();\n\n\t\tconst result: Record<string, unknown> = {};\n\n\t\tfor (const key of sortedKeys) {\n\t\t\tresult[key] = val[key];\n\t\t}\n\n\t\treturn result;\n\t});\n};\n"],"mappings":";AAyCA,MAAa,aAAa,CAA8BA,UAAkB;;;;ACtC1E,MAAa,gBAAgB,WAAW;CACvC,UAAU;CACV,WA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