@zayne-labs/callapi 1.6.12 → 1.6.14
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/dist/cjs/{common-BriivbRX.d.cts → common-B_9jiZXC.d.cts} +25 -18
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +9 -23
- package/dist/cjs/options/index.cjs +1 -1
- package/dist/cjs/options/index.cjs.map +1 -1
- package/dist/cjs/options/index.d.cts +10 -24
- package/dist/cjs/utils/index.cjs +1 -1
- package/dist/cjs/utils/index.cjs.map +1 -1
- package/dist/cjs/utils/index.d.cts +2 -2
- package/dist/esm/chunk-DQY5GNZB.js +1 -0
- package/dist/esm/chunk-DQY5GNZB.js.map +1 -0
- package/dist/esm/chunk-MOMG57MZ.js +1 -0
- package/dist/esm/chunk-MOMG57MZ.js.map +1 -0
- package/dist/esm/{common-BriivbRX.d.ts → common-B_9jiZXC.d.ts} +25 -18
- package/dist/esm/index.d.ts +9 -23
- package/dist/esm/index.js +1 -1
- package/dist/esm/options/index.d.ts +10 -24
- package/dist/esm/options/index.js +1 -1
- package/dist/esm/options/index.js.map +1 -1
- package/dist/esm/utils/index.d.ts +2 -2
- package/dist/esm/utils/index.js +1 -1
- package/package.json +15 -13
- package/dist/esm/chunk-NQNGYTDF.js +0 -1
- package/dist/esm/chunk-NQNGYTDF.js.map +0 -1
- package/dist/esm/chunk-VV4JMNGC.js +0 -1
- package/dist/esm/chunk-VV4JMNGC.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/index.ts","../../../src/error.ts","../../../src/utils/type-guards.ts","../../../src/utils/type-helpers.ts","../../../src/utils/constants.ts","../../../src/utils/common.ts"],"sourcesContent":["export { toQueryString } from \"./common\";\nexport { isHTTPError, isHTTPErrorInstance } from \"./type-guards\";\nexport { defaultRetryMethods, defaultRetryStatusCodes } from \"./constants\";\n","import type {\n\tCallApiExtraOptions,\n\tCallApiResultErrorVariant,\n\tPossibleJavascriptErrorNames,\n\tResultModeMap,\n} from \"./types/common\";\nimport { isHTTPErrorInstance, isObject } from \"./utils/type-guards\";\n\ntype ErrorInfo = {\n\tcloneResponse: CallApiExtraOptions[\"cloneResponse\"];\n\tdefaultErrorMessage: Required<CallApiExtraOptions>[\"defaultErrorMessage\"];\n\terror?: unknown;\n\tmessage?: string;\n\tresultMode: CallApiExtraOptions[\"resultMode\"];\n};\n\nexport const resolveErrorResult = <TCallApiResult = never>(info: ErrorInfo) => {\n\tconst { cloneResponse, defaultErrorMessage, error, message: customErrorMessage, resultMode } = info;\n\n\tlet errorVariantDetails: CallApiResultErrorVariant<unknown> = {\n\t\tdata: null,\n\t\terror: {\n\t\t\terrorData: error as Error,\n\t\t\tmessage: customErrorMessage ?? (error as Error).message,\n\t\t\tname: (error as Error).name as PossibleJavascriptErrorNames,\n\t\t},\n\t\tresponse: null,\n\t};\n\n\tif (isHTTPErrorInstance(error)) {\n\t\tconst { errorData, message = defaultErrorMessage, name, response } = error;\n\n\t\terrorVariantDetails = {\n\t\t\tdata: null,\n\t\t\terror: {\n\t\t\t\terrorData,\n\t\t\t\tmessage,\n\t\t\t\tname,\n\t\t\t},\n\t\t\tresponse: cloneResponse ? response.clone() : response,\n\t\t};\n\t}\n\n\tconst resultModeMap: ResultModeMap = {\n\t\tall: errorVariantDetails,\n\t\tonlyError: errorVariantDetails.error,\n\t\tonlyResponse: errorVariantDetails.response,\n\t\tonlySuccess: errorVariantDetails.data,\n\t\tonlySuccessWithException: errorVariantDetails.data,\n\t};\n\n\tconst getErrorResult = (customInfo?: Pick<ErrorInfo, \"message\">) => {\n\t\tconst errorResult = resultModeMap[resultMode ?? \"all\"] as TCallApiResult;\n\n\t\treturn isObject(customInfo) ? { ...errorResult, ...customInfo } : errorResult;\n\t};\n\n\treturn { errorVariantDetails, getErrorResult };\n};\n\ntype ErrorDetails<TErrorResponse> = {\n\tdefaultErrorMessage: string;\n\terrorData: TErrorResponse;\n\tresponse: Response;\n};\n\ntype ErrorOptions = {\n\tcause?: unknown;\n};\n\nexport class HTTPError<TErrorResponse = Record<string, unknown>> extends Error {\n\terrorData: ErrorDetails<TErrorResponse>[\"errorData\"];\n\tisHTTPError = true;\n\n\toverride name = \"HTTPError\" as const;\n\n\tresponse: ErrorDetails<TErrorResponse>[\"response\"];\n\n\tconstructor(errorDetails: ErrorDetails<TErrorResponse>, errorOptions?: ErrorOptions) {\n\t\tconst { defaultErrorMessage, errorData, response } = errorDetails;\n\n\t\tsuper((errorData as { message?: string } | undefined)?.message ?? defaultErrorMessage, errorOptions);\n\n\t\tthis.errorData = errorData;\n\t\tthis.response = response;\n\n\t\tError.captureStackTrace(this, this.constructor);\n\t}\n}\n","import { HTTPError } from \"@/error\";\nimport type { PossibleHTTPError, PossibleJavaScriptError } from \"@/types/common\";\nimport type { AnyFunction } from \"./type-helpers\";\n\ntype ErrorObjectUnion<TErrorData = unknown> = PossibleHTTPError<TErrorData> | PossibleJavaScriptError;\n\nexport const isHTTPError = <TErrorData>(\n\terror: ErrorObjectUnion<TErrorData> | null\n): error is PossibleHTTPError<TErrorData> => {\n\treturn isPlainObject(error) && error.name === \"HTTPError\";\n};\n\nexport const isHTTPErrorInstance = <TErrorResponse>(\n\terror: unknown\n): error is HTTPError<TErrorResponse> => {\n\treturn (\n\t\t// prettier-ignore\n\t\terror instanceof HTTPError|| (isPlainObject(error) && error.name === \"HTTPError\" && error.isHTTPError === true)\n\t);\n};\n\nexport const isArray = <TArrayItem>(value: unknown): value is TArrayItem[] => Array.isArray(value);\n\nexport const isObject = (value: unknown) => typeof value === \"object\" && value !== null;\n\nexport const isPlainObject = <TPlainObject extends Record<string, unknown>>(\n\tvalue: unknown\n): value is TPlainObject => {\n\tif (!isObject(value)) {\n\t\treturn false;\n\t}\n\n\tconst prototype = Object.getPrototypeOf(value) as unknown;\n\n\t// Check if it's a plain object\n\treturn (\n\t\t// prettier-ignore\n\t\t(prototype == null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value)\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\n// https://github.com/unjs/ofetch/blob/main/src/utils.ts\n// TODO Find a way to incorporate this function in checking when to apply the bodySerializer on the body and also whether to add the content type application/json\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// eslint-disable-next-line ts-eslint/prefer-nullish-coalescing -- Nullish coalescing makes no sense in this boolean context\n\t\t(value?.constructor && value.constructor.name === \"Object\") ||\n\t\ttypeof (value as { toJSON: () => unknown } | null)?.toJSON === \"function\"\n\t);\n};\n","// == 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 & { z_placeholder?: never };\nexport type AnyNumber = number & { z_placeholder?: never };\n\n// eslint-disable-next-line ts-eslint/no-explicit-any -- Any is fine here\nexport type AnyObject = Record<string, 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 Writeable<TObject, TType extends \"deep\" | \"shallow\" = \"shallow\"> = {\n\t-readonly [key in keyof TObject]: TType extends \"shallow\"\n\t\t? TObject[key]\n\t\t: TType extends \"deep\"\n\t\t\t? TObject[key] extends object\n\t\t\t\t? Writeable<TObject[key], TType>\n\t\t\t\t: TObject[key]\n\t\t\t: never;\n};\n\nexport const defineEnum = <const TValue>(value: TValue) => value as Prettify<Writeable<TValue, \"deep\">>;\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 { BaseCallApiExtraOptions } from \"../types/common\";\nimport { defineEnum } from \"./type-helpers\";\n\nexport const fetchSpecificKeys = defineEnum([\n\t\"body\",\n\t\"integrity\",\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 RequestInit>);\n\nconst retryStatusCodesLookup = 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 defaultRetryMethods = [\"GET\", \"POST\"] satisfies BaseCallApiExtraOptions[\"retryMethods\"];\n\n// prettier-ignore\nexport const defaultRetryStatusCodes = Object.keys(retryStatusCodesLookup).map(Number) as Required<BaseCallApiExtraOptions>[\"retryStatusCodes\"];\n","import { getAuthHeader } from \"@/auth\";\nimport {\n\ttype BaseCallApiExtraOptions,\n\ttype CallApiExtraOptions,\n\ttype CallApiRequestOptions,\n\toptionsEnumToOmitFromBase,\n} from \"../types/common\";\nimport { fetchSpecificKeys } from \"./constants\";\nimport { isArray, isFunction, isPlainObject, isQueryString, isString } from \"./type-guards\";\nimport type { AnyFunction, Awaitable } from \"./type-helpers\";\n\nconst omitKeys = <TObject extends Record<string, unknown>, const TOmitArray extends Array<keyof TObject>>(\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\nconst pickKeys = <TObject extends Record<string, unknown>, const TPickArray extends Array<keyof TObject>>(\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, [\n\t\t\t...fetchSpecificKeys,\n\t\t\t...optionsEnumToOmitFromBase,\n\t\t]) 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\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\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\n// export mergeAndResolve\n\nexport const mergeAndResolveHeaders = (options: {\n\tauth: CallApiExtraOptions[\"auth\"];\n\tbaseHeaders: CallApiExtraOptions[\"headers\"];\n\tbody: CallApiExtraOptions[\"body\"];\n\theaders: CallApiExtraOptions[\"headers\"];\n}) => {\n\tconst { auth, baseHeaders, body, headers } = options;\n\n\t// eslint-disable-next-line ts-eslint/prefer-nullish-coalescing -- Nullish coalescing makes no sense in this boolean context\n\tconst shouldResolveHeaders = Boolean(baseHeaders || headers || body || auth);\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\t// == - headers are provided\n\t// == - The body is an object\n\t// == - The auth option is provided\n\tif (!shouldResolveHeaders) return;\n\n\tconst headersObject: Record<string, string | undefined> = {\n\t\t...getAuthHeader(auth),\n\t\t...objectifyHeaders(baseHeaders),\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 (isPlainObject(body) || (isString(body) && body.startsWith(\"{\"))) {\n\t\theadersObject[\"Content-Type\"] = \"application/json\";\n\t\theadersObject.Accept = \"application/json\";\n\t}\n\n\treturn headersObject;\n};\n\nexport const combineHooks = <TInterceptor extends AnyFunction | Array<AnyFunction | undefined>>(\n\tbaseInterceptor: TInterceptor | undefined,\n\tinterceptor: TInterceptor | undefined\n) => {\n\tif (isArray(baseInterceptor)) {\n\t\treturn [baseInterceptor, interceptor].flat() as TInterceptor;\n\t}\n\n\treturn interceptor ?? baseInterceptor;\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\nexport const executeHooks = <TInterceptor extends Awaitable<unknown>>(...interceptors: TInterceptor[]) =>\n\tPromise.all(interceptors);\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 waitUntil = (delay: number) => {\n\tif (delay === 0) return;\n\n\tconst { promise, resolve } = PromiseWithResolvers();\n\n\tsetTimeout(resolve, delay);\n\n\treturn promise;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsEO,IAAM,YAAN,cAAkE,MAAM;AAAA,EAC9E;AAAA,EACA,cAAc;AAAA,EAEL,OAAO;AAAA,EAEhB;AAAA,EAEA,YAAY,cAA4C,cAA6B;AACpF,UAAM,EAAE,qBAAqB,WAAW,SAAS,IAAI;AAErD,UAAO,WAAgD,WAAW,qBAAqB,YAAY;AAEnG,SAAK,YAAY;AACjB,SAAK,WAAW;AAEhB,UAAM,kBAAkB,MAAM,KAAK,WAAW;AAAA,EAC/C;AACD;;;AClFO,IAAM,cAAc,CAC1B,UAC4C;AAC5C,SAAO,cAAc,KAAK,KAAK,MAAM,SAAS;AAC/C;AAEO,IAAM,sBAAsB,CAClC,UACwC;AACxC;AAAA;AAAA,IAEC,iBAAiB,aAAa,cAAc,KAAK,KAAK,MAAM,SAAS,eAAe,MAAM,gBAAgB;AAAA;AAE5G;AAIO,IAAM,WAAW,CAAC,UAAmB,OAAO,UAAU,YAAY,UAAU;AAE5E,IAAM,gBAAgB,CAC5B,UAC2B;AAC3B,MAAI,CAAC,SAAS,KAAK,GAAG;AACrB,WAAO;AAAA,EACR;AAEA,QAAM,YAAY,OAAO,eAAe,KAAK;AAG7C;AAAA;AAAA,KAEE,aAAa,QAAQ,cAAc,OAAO,aAAa,OAAO,eAAe,SAAS,MAAM,SAAS,EAAE,OAAO,eAAe;AAAA;AAEhI;;;ACdO,IAAM,aAAa,CAAe,UAAkB;;;ACtBpD,IAAM,oBAAoB,WAAW;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,CAAoC;AAEpC,IAAM,yBAAyB,WAAW;AAAA,EACzC,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACN,CAAC;AAEM,IAAM,sBAAsB,CAAC,OAAO,MAAM;AAG1C,IAAM,0BAA0B,OAAO,KAAK,sBAAsB,EAAE,IAAI,MAAM;;;ACyC9E,IAAM,gBAAiC,CAAC,WAAW;AACzD,MAAI,CAAC,QAAQ;AACZ,YAAQ,MAAM,kBAAkB,2BAA2B;AAE3D,WAAO;AAAA,EACR;AAEA,SAAO,IAAI,gBAAgB,MAAgC,EAAE,SAAS;AACvE;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/index.ts","../../../src/error.ts","../../../src/utils/type-guards.ts","../../../src/utils/type-helpers.ts","../../../src/utils/constants.ts","../../../src/utils/common.ts"],"sourcesContent":["export { toQueryString } from \"./common\";\nexport { isHTTPError, isHTTPErrorInstance } from \"./type-guards\";\nexport { defaultRetryMethods, defaultRetryStatusCodes } from \"./constants\";\n","import type {\n\tCallApiExtraOptions,\n\tCallApiResultErrorVariant,\n\tPossibleJavascriptErrorNames,\n\tResultModeMap,\n} from \"./types/common\";\nimport { omitKeys } from \"./utils/common\";\nimport { isHTTPErrorInstance, isObject } from \"./utils/type-guards\";\n\ntype ErrorInfo = {\n\tcloneResponse: CallApiExtraOptions[\"cloneResponse\"];\n\tdefaultErrorMessage: Required<CallApiExtraOptions>[\"defaultErrorMessage\"];\n\terror?: unknown;\n\tmessage?: string;\n\tresultMode: CallApiExtraOptions[\"resultMode\"];\n};\n\nexport const resolveErrorResult = <TCallApiResult = never>(info: ErrorInfo) => {\n\tconst { cloneResponse, defaultErrorMessage, error, message: customErrorMessage, resultMode } = info;\n\n\tlet apiDetails: CallApiResultErrorVariant<unknown> = {\n\t\tdata: null,\n\t\terror: {\n\t\t\terrorData: error as Error,\n\t\t\tmessage: customErrorMessage ?? (error as Error).message,\n\t\t\tname: (error as Error).name as PossibleJavascriptErrorNames,\n\t\t},\n\t\tresponse: null,\n\t};\n\n\tif (isHTTPErrorInstance<never>(error)) {\n\t\tconst { errorData, message = defaultErrorMessage, name, response } = error;\n\n\t\tapiDetails = {\n\t\t\tdata: null,\n\t\t\terror: {\n\t\t\t\terrorData,\n\t\t\t\tmessage,\n\t\t\t\tname,\n\t\t\t},\n\t\t\tresponse: cloneResponse ? response.clone() : response,\n\t\t};\n\t}\n\n\tconst resultModeMap = {\n\t\tall: apiDetails,\n\t\tallWithException: apiDetails as never,\n\t\tallWithoutResponse: omitKeys(apiDetails, [\"response\"]),\n\t\tonlyError: apiDetails.error,\n\t\tonlyResponse: apiDetails.response,\n\t\tonlyResponseWithException: apiDetails.response as never,\n\t\tonlySuccess: apiDetails.data,\n\t\tonlySuccessWithException: apiDetails.data,\n\t} satisfies ResultModeMap;\n\n\tconst getErrorResult = (customInfo?: Pick<ErrorInfo, \"message\">) => {\n\t\tconst errorResult = resultModeMap[resultMode ?? \"all\"] as TCallApiResult;\n\n\t\treturn isObject(customInfo) ? { ...errorResult, ...customInfo } : errorResult;\n\t};\n\n\treturn { apiDetails, getErrorResult };\n};\n\ntype ErrorDetails<TErrorResponse> = {\n\tdefaultErrorMessage: string;\n\terrorData: TErrorResponse;\n\tresponse: Response;\n};\n\ntype ErrorOptions = {\n\tcause?: unknown;\n};\n\nexport class HTTPError<TErrorResponse = Record<string, unknown>> extends Error {\n\terrorData: ErrorDetails<TErrorResponse>[\"errorData\"];\n\n\tisHTTPError = true;\n\n\toverride name = \"HTTPError\" as const;\n\n\tresponse: ErrorDetails<TErrorResponse>[\"response\"];\n\n\tconstructor(errorDetails: ErrorDetails<TErrorResponse>, errorOptions?: ErrorOptions) {\n\t\tconst { defaultErrorMessage, errorData, response } = errorDetails;\n\n\t\tsuper((errorData as { message?: string } | undefined)?.message ?? defaultErrorMessage, errorOptions);\n\n\t\tthis.errorData = errorData;\n\t\tthis.response = response;\n\n\t\tError.captureStackTrace(this, this.constructor);\n\t}\n}\n","import { HTTPError } from \"@/error\";\nimport type { PossibleHTTPError, PossibleJavaScriptError } from \"@/types/common\";\nimport type { AnyFunction } from \"./type-helpers\";\n\ntype ErrorObjectUnion<TErrorData = unknown> = PossibleHTTPError<TErrorData> | PossibleJavaScriptError;\n\nexport const isHTTPError = <TErrorData>(\n\terror: ErrorObjectUnion<TErrorData> | null\n): error is PossibleHTTPError<TErrorData> => {\n\treturn isPlainObject(error) && error.name === \"HTTPError\";\n};\n\nexport const isHTTPErrorInstance = <TErrorResponse>(\n\terror: unknown\n): error is HTTPError<TErrorResponse> => {\n\treturn (\n\t\t// prettier-ignore\n\t\terror instanceof HTTPError|| (isPlainObject(error) && error.name === \"HTTPError\" && error.isHTTPError === true)\n\t);\n};\n\nexport const isArray = <TArrayItem>(value: unknown): value is TArrayItem[] => Array.isArray(value);\n\nexport const isObject = (value: unknown) => typeof value === \"object\" && value !== null;\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 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\n// https://github.com/unjs/ofetch/blob/main/src/utils.ts\n// TODO Find a way to incorporate this function in checking when to apply the bodySerializer on the body and also whether to add the content type application/json\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// eslint-disable-next-line ts-eslint/prefer-nullish-coalescing -- Nullish coalescing makes no sense in this boolean context\n\t\t(value?.constructor && value.constructor.name === \"Object\") ||\n\t\ttypeof (value as { toJSON: () => unknown } | null)?.toJSON === \"function\"\n\t);\n};\n","// == 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 & { z_placeholder?: never };\nexport type AnyNumber = number & { z_placeholder?: never };\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 Writeable<TObject, TType extends \"deep\" | \"shallow\" = \"shallow\"> = {\n\t-readonly [key in keyof TObject]: TType extends \"shallow\"\n\t\t? TObject[key]\n\t\t: TType extends \"deep\"\n\t\t\t? TObject[key] extends object\n\t\t\t\t? Writeable<TObject[key], TType>\n\t\t\t\t: TObject[key]\n\t\t\t: never;\n};\n\nexport const defineEnum = <const TValue>(value: TValue) => value as Prettify<Writeable<TValue, \"deep\">>;\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 { BaseCallApiExtraOptions } from \"../types/common\";\nimport { defineEnum } from \"./type-helpers\";\n\nexport const fetchSpecificKeys = defineEnum([\n\t\"body\",\n\t\"integrity\",\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 RequestInit>);\n\nconst retryStatusCodesLookup = 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 defaultRetryMethods = [\"GET\", \"POST\"] satisfies BaseCallApiExtraOptions[\"retryMethods\"];\n\n// prettier-ignore\nexport const defaultRetryStatusCodes = Object.keys(retryStatusCodesLookup).map(Number) as Required<BaseCallApiExtraOptions>[\"retryStatusCodes\"];\n","import { getAuthHeader } from \"@/auth\";\nimport {\n\ttype BaseCallApiExtraOptions,\n\ttype CallApiExtraOptions,\n\ttype CallApiRequestOptions,\n\toptionsEnumToOmitFromBase,\n} from \"../types/common\";\nimport { fetchSpecificKeys } from \"./constants\";\nimport { isArray, isFunction, isPlainObject, isQueryString, isString } from \"./type-guards\";\nimport type { AnyFunction, Awaitable } from \"./type-helpers\";\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, [\n\t\t\t...fetchSpecificKeys,\n\t\t\t...optionsEnumToOmitFromBase,\n\t\t]) 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\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\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\n// export mergeAndResolve\n\nexport const mergeAndResolveHeaders = (options: {\n\tauth: CallApiExtraOptions[\"auth\"];\n\tbaseHeaders: CallApiExtraOptions[\"headers\"];\n\tbody: CallApiExtraOptions[\"body\"];\n\theaders: CallApiExtraOptions[\"headers\"];\n}) => {\n\tconst { auth, baseHeaders, body, headers } = options;\n\n\t// eslint-disable-next-line ts-eslint/prefer-nullish-coalescing -- Nullish coalescing makes no sense in this boolean context\n\tconst shouldResolveHeaders = Boolean(baseHeaders || headers || body || auth);\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\t// == - headers are provided\n\t// == - The body is an object\n\t// == - The auth option is provided\n\tif (!shouldResolveHeaders) return;\n\n\tconst headersObject: Record<string, string | undefined> = {\n\t\t...getAuthHeader(auth),\n\t\t...objectifyHeaders(baseHeaders),\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 (isPlainObject(body) || (isString(body) && body.startsWith(\"{\"))) {\n\t\theadersObject[\"Content-Type\"] = \"application/json\";\n\t\theadersObject.Accept = \"application/json\";\n\t}\n\n\treturn headersObject;\n};\n\nexport const combineHooks = <TInterceptor extends AnyFunction | Array<AnyFunction | undefined>>(\n\tbaseInterceptor: TInterceptor | undefined,\n\tinterceptor: TInterceptor | undefined\n) => {\n\tif (isArray(baseInterceptor)) {\n\t\treturn [baseInterceptor, interceptor].flat() as TInterceptor;\n\t}\n\n\treturn interceptor ?? baseInterceptor;\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\nexport const executeHooks = <TInterceptor extends Awaitable<unknown>>(...interceptors: TInterceptor[]) =>\n\tPromise.all(interceptors);\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 waitUntil = (delay: number) => {\n\tif (delay === 0) return;\n\n\tconst { promise, resolve } = PromiseWithResolvers();\n\n\tsetTimeout(resolve, delay);\n\n\treturn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,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,CAAoC;AAEpC,IAAM,yBAAyB,WAAW;AAAA,EACzC,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACN,CAAC;AAEM,IAAM,sBAAsB,CAAC,OAAO,MAAM;AAG1C,IAAM,0BAA0B,OAAO,KAAK,sBAAsB,EAAE,IAAI,MAAM;;;AC+C9E,IAAM,gBAAiC,CAAC,WAAW;AACzD,MAAI,CAAC,QAAQ;AACZ,YAAQ,MAAM,kBAAkB,2BAA2B;AAE3D,WAAO;AAAA,EACR;AAEA,SAAO,IAAI,gBAAgB,MAAgC,EAAE,SAAS;AACvE;","names":[]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { c as CallApiExtraOptions, i as PossibleHTTPError, h as PossibleJavaScriptError } from '../common-
|
|
2
|
-
export {
|
|
1
|
+
import { c as CallApiExtraOptions, i as PossibleHTTPError, h as PossibleJavaScriptError } from '../common-B_9jiZXC.cjs';
|
|
2
|
+
export { y as defaultRetryMethods, z as defaultRetryStatusCodes } from '../common-B_9jiZXC.cjs';
|
|
3
3
|
import { H as HTTPError } from '../error-lBRMiMeF.cjs';
|
|
4
4
|
import '@standard-schema/spec';
|
|
5
5
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{splitBaseConfig as e,splitConfig as t,combineHooks as r,mergeAndResolveHeaders as o,isPlainObject as s,defaultRetryStatusCodes as n,defaultRetryMethods as a,executeHooks as i,HTTPError as l,resolveErrorResult as u,waitUntil as c,isFunction as d,isHTTPErrorInstance as p,omitKeys as y,isString as f,isArray as h,toQueryString as w,getFetchImpl as m}from"./chunk-MOMG57MZ.js";var g=e=>e,R=(e,t)=>async r=>{if("sequential"!==t){if("parallel"===t){const t=[...e];await Promise.all(t.map((e=>e?.(r))))}}else for(const t of e)await(t?.(r))},E={onError:new Set,onRequest:new Set,onRequestError:new Set,onResponse:new Set,onResponseError:new Set,onRetry:new Set,onSuccess:new Set},S=(e,t)=>e?d(e)?e(t):e:[],q=async e=>{const{initURL:t,options:r,request:o}=e,n=structuredClone(E),a=()=>{for(const e of Object.keys(E)){const t=r[e];n[e].add(t)}},i=e=>{for(const t of Object.keys(E)){const r=e[t];n[t].add(r)}};"mainHooksBeforePlugins"===r.mergedHooksExecutionOrder&&a();const l=[...S(r.plugins,e),...S(r.extend?.plugins,e)];let u=t,c=r,d=o;const p=async e=>{if(!e)return;const n=await e({initURL:t,options:r,request:o});s(n)&&(f(n.initURL)&&(u=n.initURL),s(n.request)&&(d=n.request),s(n.options)&&(c=n.options))};for(const e of l)await p(e.init),e.hooks&&i(e.hooks);r.mergedHooksExecutionOrder&&"mainHooksAfterPlugins"!==r.mergedHooksExecutionOrder||a();const y={};for(const[e,t]of Object.entries(n)){const o=[...t].flat(),s=R(o,r.mergedHooksExecutionMode);y[e]=s}return{resolvedHooks:y,resolvedOptions:c,resolvedRequestOptions:d,url:u?.toString()}},b=async e=>{const{$RequestInfoCache:t,newFetchController:r,options:o,request:s}=e,n=o.dedupeKey??("cancel"===o.dedupeStrategy||"defer"===o.dedupeStrategy?`${o.fullURL}-${JSON.stringify({options:o,request:s})}`:null),a=null!==n?t:null;null!==n&&await c(.1);const i=a?.get(n);return{handleRequestCancelStrategy:()=>{if(!(i&&"cancel"===o.dedupeStrategy))return;const e=o.dedupeKey?`Duplicate request detected - Aborting previous request with key '${o.dedupeKey}' as a new request was initiated`:`Duplicate request detected - Aborting previous request to '${o.fullURL}' as a new request with identical options was initiated`,t=new DOMException(e,"AbortError");return i.controller.abort(t),Promise.resolve()},handleRequestDeferStrategy:()=>{const e=m(o.customFetchImpl),t=i&&"defer"===o.dedupeStrategy?i.responsePromise:e(o.fullURL,s);return a?.set(n,{controller:r,responsePromise:t}),t},removeDedupeKeyFromCache:()=>a?.delete(n)}},M=async(e,t,r)=>{const o=((e,t)=>({arrayBuffer:()=>e.arrayBuffer(),blob:()=>e.blob(),formData:()=>e.formData(),json:async()=>{if(t){const r=await e.text();return t(r)}return e.json()},stream:()=>e.body,text:()=>e.text()}))(e,r);if(!Object.hasOwn(o,t))throw new Error(`Invalid response type: ${t}`);return await o[t]()},O=e=>{const{data:t,response:r,resultMode:o}=e,s={data:t,error:null,response:r};if(!o)return s;return{all:s,allWithException:s,allWithoutResponse:y(s,["response"]),onlyError:s.error,onlyResponse:s.response,onlyResponseWithException:s.response,onlySuccess:s.data,onlySuccessWithException:s.data}[o]},x=(e,t)=>{const r=e["~retryCount"]??0;return{getDelay:()=>"exponential"===e.retryStrategy?((e,t)=>{const r=t.retryMaxDelay??1e4,o=(t.retryDelay??1e3)*2**e;return Math.min(o,r)})(r,e):(e=>e.retryDelay??1e3)(e),shouldAttemptRetry:async()=>{const o=await(e.retryCondition?.(t))??!0,s=(e.retryAttempts??0)>r&&o;if("HTTPError"!==t.error.name)return s;const n=!!t.request.method&&e.retryMethods?.includes(t.request.method);return!!t.response?.status&&e.retryStatusCodes?.includes(t.response.status)&&n&&s}}},D=(e,t,r)=>{if(!e)return;const o=((e,t)=>{if(!t)return e;let r=e;if(h(t)){const e=r.split("/").filter((e=>e.startsWith(":")));for(const[o,s]of e.entries()){const e=t[o];r=r.replace(s,e)}return r}for(const[e,o]of Object.entries(t))r=r.replace(`:${e}`,String(o));return r})(e,t);return((e,t)=>{if(!t)return e;const r=w(t);return 0===r?.length?e:e.endsWith("?")?`${e}${r}`:e.includes("?")?`${e}&${r}`:`${e}?${r}`})(o,r)},v=(...e)=>AbortSignal.any(e.filter(Boolean)),k=e=>AbortSignal.timeout(e),$=e=>({schemas:e.schemas&&{...e.schemas,...e.extend?.schemas},validators:e.validators&&{...e.validators,...e.extend?.validators}}),C=async(e,t,r)=>{const o=r?r(e):e,s=t?await(async(e,t)=>{const r=await e["~standard"].validate(t);if(r.issues)throw new Error(JSON.stringify(r.issues,null,2),{cause:r.issues});return r.value})(t,o):o;return s},H=y=>{const[f,h]=e(y??{}),w=new Map,m=async(...e)=>{const[y,g={}]=e,[R,S]=t(g),H={};for(const e of Object.keys(E)){const t=r(h[e],S[e]);H[e]=t}const A={baseURL:"",bodySerializer:JSON.stringify,dedupeStrategy:"cancel",defaultErrorMessage:"Failed to fetch data from server!",mergedHooksExecutionMode:"parallel",mergedHooksExecutionOrder:"mainHooksAfterPlugins",responseType:"json",resultMode:"all",retryAttempts:0,retryDelay:1e3,retryMaxDelay:1e4,retryMethods:a,retryStatusCodes:n,retryStrategy:"linear",...h,...S,...H},L=R.body??f.body,U={...f,...R,body:s(L)?A.bodySerializer(L):L,headers:o({auth:A.auth,baseHeaders:f.headers,body:L,headers:R.headers}),signal:R.signal??f.signal},{resolvedHooks:j,resolvedOptions:P,resolvedRequestOptions:F,url:T}=await q({initURL:y,options:A,request:U}),W=`${P.baseURL}${D(T,P.params,P.query)}`,K={...P,...j,fullURL:W,initURL:y.toString()},B=new AbortController,I=null!=K.timeout?k(K.timeout):null,J=v(F.signal,I,B.signal),N={...F,signal:J},{handleRequestCancelStrategy:z,handleRequestDeferStrategy:G,removeDedupeKeyFromCache:Z}=await b({$RequestInfoCache:w,newFetchController:B,options:K,request:N});await z();try{await i(K.onRequest({options:K,request:N})),N.headers=o({auth:K.auth,baseHeaders:f.headers,body:L,headers:N.headers});const e=await G(),t="defer"===K.dedupeStrategy||K.cloneResponse,{schemas:r,validators:s}=$(K);if(!e.ok){const o=await M(t?e.clone():e,K.responseType,K.responseParser),n=await C(o,r?.errorData,s?.errorData);throw new l({defaultErrorMessage:K.defaultErrorMessage,errorData:n,response:e})}const n=await M(t?e.clone():e,K.responseType,K.responseParser),a={data:await C(n,r?.data,s?.data),options:K,request:N,response:K.cloneResponse?e.clone():e};return await i(K.onSuccess(a),K.onResponse({...a,error:null})),await O({data:a.data,response:a.response,resultMode:K.resultMode})}catch(e){const{apiDetails:t,getErrorResult:r}=u({cloneResponse:K.cloneResponse,defaultErrorMessage:K.defaultErrorMessage,error:e,resultMode:K.resultMode}),o={error:t.error,options:K,request:N,response:t.response},{getDelay:s,shouldAttemptRetry:n}=x(K,o);if(!J.aborted&&await n()){await i(K.onRetry(o));const e=s();await c(e);const t={...g,"~retryCount":(K["~retryCount"]??0)+1};return await m(y,t)}const a=d(K.throwOnError)?K.throwOnError(o):K.throwOnError,l=()=>{if(a)throw t.error};if(p(e))return await i(K.onResponseError(o),K.onError(o),K.onResponse({...o,data:null})),l(),r();if(e instanceof DOMException&&"AbortError"===e.name){const{message:t,name:o}=e;return console.error(`${o}:`,t),l(),r()}if(e instanceof DOMException&&"TimeoutError"===e.name){const t=`Request timed out after ${K.timeout}ms`;return console.error(`${e.name}:`,t),l(),r({message:t})}return await i(K.onRequestError(o),K.onError(o)),l(),r()}finally{Z()}};return m.create=H,m},A=H();export{A as callApi,v as createCombinedSignal,b as createDedupeStrategy,$ as createExtensibleSchemasAndValidators,H as createFetchClient,x as createRetryStrategy,k as createTimeoutSignal,g as definePlugin,C as handleValidation,E as hooksEnum,q as initializePlugins,D as mergeUrlWithParamsAndQuery,M as resolveResponseData,O as resolveSuccessResult};//# sourceMappingURL=chunk-DQY5GNZB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/plugins.ts","../../src/dedupe.ts","../../src/response.ts","../../src/retry.ts","../../src/url.ts","../../src/utils/polyfills.ts","../../src/validation.ts","../../src/createFetchClient.ts"],"names":["callApi"],"mappings":";AA6Ea,IAAA,YAAA,GAAe,CAI3B,MACI,KAAA;AACJ,EAAO,OAAA,MAAA;AACR;AAEA,IAAM,gBAAA,GAAmB,CACxB,KAAA,EACA,wBACI,KAAA;AACJ,EAAA,OAAO,OAAO,GAAiC,KAAA;AAC9C,IAAA,IAAI,6BAA6B,YAAc,EAAA;AAC9C,MAAA,KAAA,MAAW,QAA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Ae,EAAA;AAAA;AAGvB,MAAA,IAAI,KAAiB,YAAA,YAAA,IAAgB,KAAM,CAAA,IAAA,KAAS,YAAc,EAAA;AACjE,QAAM,MAAA,EAAE,OAAS,EAAA,IAAA,EAAS,GAAA,KAAA;AAE1B,QAAA,OAAA,CAAQ,KAAM,CAAA,CAAA,EAAG,IAAI,CAAA,CAAA,CAAA,EAAK,OAAO,CAAA;AAEjC,QAAmB,kBAAA,EAAA;AAEnB,QAAA,OAAO,cAAe,EAAA;AAAA;AAGvB,MAAA,IAAI,KAAiB,YAAA,YAAA,IAAgB,KAAM,CAAA,IAAA,KAAS,cAAgB,EAAA;AACnE,QAAM,MAAA,OAAA,GAAU,CAA2B,wBAAA,EAAA,OAAA,CAAQ,OAAO,CAAA,EAAA,CAAA;AAE1D,QAAA,OAAA,CAAQ,KAAM,CAAA,CAAA,EAAG,KAAM,CAAA,IAAI,KAAK,OAAO,CAAA;AAEvC,QAAmB,kBAAA,EAAA;AAEnB,QAAO,OAAA,cAAA,CAAe,EAAE,OAAA,EAAS,CAAA;AAAA;AAGlC,MAAM,MAAA,YAAA;AAAA;AAAA,QAEL,OAAA,CAAQ,eAAe,YAAqB,CAAA;AAAA;AAAA,QAG5C,OAAA,CAAQ,QAAQ,YAAY;AAAA,OAC7B;AAEA,MAAmB,kBAAA,EAAA;AAEnB,MAAA,OAAO,cAAe,EAAA;AAAA,KAGrB,SAAA;AACD,MAAyB,wBAAA,EAAA;AAAA;AAC1B,GACD;AAEA,EAAAA,SAAQ,MAAS,GAAA,iBAAA;AAEjB,EAAOA,OAAAA,QAAAA;AACR;AAEO,IAAM,UAAU,iBAAkB","file":"chunk-DQY5GNZB.js","sourcesContent":["/* eslint-disable ts-eslint/consistent-type-definitions -- I need to use interfaces for the sake of user overrides */\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type {\n\tCallApiRequestOptions,\n\tCallApiRequestOptionsForHooks,\n\tCombinedCallApiExtraOptions,\n\tInterceptors,\n\tInterceptorsOrInterceptorArray,\n\tWithMoreOptions,\n} from \"./types/common\";\nimport type { DefaultMoreOptions } from \"./types/default-types\";\nimport type { InitURL } from \"./url\";\nimport { isFunction, isPlainObject, isString } from \"./utils/type-guards\";\nimport type { AnyFunction, Awaitable } from \"./utils/type-helpers\";\nimport type { InferSchemaResult } from \"./validation\";\n\ntype UnionToIntersection<TUnion> = (TUnion extends unknown ? (param: TUnion) => void : never) extends (\n\tparam: infer TParam\n) => void\n\t? TParam\n\t: never;\n\ntype InferSchema<TResult> = TResult extends StandardSchemaV1\n\t? InferSchemaResult<TResult, NonNullable<unknown>>\n\t: TResult;\n\nexport type InferPluginOptions<TPluginArray extends CallApiPlugin[]> = UnionToIntersection<\n\tInferSchema<ReturnType<NonNullable<TPluginArray[number][\"createExtraOptions\"]>>>\n>;\n\nexport type PluginInitContext<TMoreOptions = DefaultMoreOptions> = WithMoreOptions<TMoreOptions> & {\n\tinitURL: InitURL | undefined;\n\toptions: CombinedCallApiExtraOptions;\n\trequest: CallApiRequestOptionsForHooks;\n};\n\nexport type PluginInitResult = Partial<\n\tOmit<PluginInitContext, \"request\"> & { request: CallApiRequestOptions }\n>;\n\nexport interface CallApiPlugin<TData = never, TErrorData = never> {\n\t/**\n\t * Defines additional options that can be passed to callApi\n\t */\n\tcreateExtraOptions?: (...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?: InterceptorsOrInterceptorArray<TData, TErrorData>;\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 createMergedHook = (\n\thooks: Array<AnyFunction | undefined>,\n\tmergedHooksExecutionMode: CombinedCallApiExtraOptions[\"mergedHooksExecutionMode\"]\n) => {\n\treturn async (ctx: Record<string, unknown>) => {\n\t\tif (mergedHooksExecutionMode === \"sequential\") {\n\t\t\tfor (const hook of hooks) {\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\tconst hookArray = [...hooks];\n\n\t\t\tawait Promise.all(hookArray.map((uniqueHook) => uniqueHook?.(ctx)));\n\t\t}\n\t};\n};\n\n// prettier-ignore\ntype HookRegistries = {\n\t[Key in keyof Interceptors]: Set<Interceptors[Key]>;\n};\n\nexport const hooksEnum = {\n\tonError: new Set(),\n\tonRequest: new Set(),\n\tonRequestError: new Set(),\n\tonResponse: new Set(),\n\tonResponseError: new Set(),\n\tonRetry: new Set(),\n\tonSuccess: new Set(),\n} satisfies HookRegistries;\n\nexport type Plugins<TPluginArray extends CallApiPlugin[]> =\n\t| TPluginArray\n\t| ((context: PluginInitContext) => TPluginArray);\n\nconst getPluginArray = (plugins: Plugins<CallApiPlugin[]> | undefined, context: PluginInitContext) => {\n\tif (!plugins) {\n\t\treturn [];\n\t}\n\n\treturn isFunction(plugins) ? plugins(context) : plugins;\n};\n\nexport const initializePlugins = async (context: PluginInitContext) => {\n\tconst { initURL, options, request } = context;\n\n\tconst hookRegistries = structuredClone(hooksEnum);\n\n\tconst addMainHooks = () => {\n\t\tfor (const key of Object.keys(hooksEnum)) {\n\t\t\tconst mainHook = options[key as keyof Interceptors] as never;\n\n\t\t\thookRegistries[key as keyof Interceptors].add(mainHook);\n\t\t}\n\t};\n\n\tconst addPluginHooks = (pluginHooks: Required<CallApiPlugin>[\"hooks\"]) => {\n\t\tfor (const key of Object.keys(hooksEnum)) {\n\t\t\tconst pluginHook = pluginHooks[key as keyof Interceptors] as never;\n\n\t\t\thookRegistries[key as keyof Interceptors].add(pluginHook);\n\t\t}\n\t};\n\n\tif (options.mergedHooksExecutionOrder === \"mainHooksBeforePlugins\") {\n\t\taddMainHooks();\n\t}\n\n\tconst resolvedPlugins = [\n\t\t...getPluginArray(options.plugins, context),\n\t\t...getPluginArray(options.extend?.plugins, context),\n\t];\n\n\tlet resolvedUrl = 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({ initURL, options, request });\n\n\t\tif (!isPlainObject(initResult)) return;\n\n\t\tif (isString(initResult.initURL)) {\n\t\t\tresolvedUrl = initResult.initURL;\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 (\n\t\t!options.mergedHooksExecutionOrder ||\n\t\toptions.mergedHooksExecutionOrder === \"mainHooksAfterPlugins\"\n\t) {\n\t\taddMainHooks();\n\t}\n\n\tconst resolvedHooks = {} as Required<Interceptors>;\n\n\tfor (const [key, hookRegistry] of Object.entries(hookRegistries)) {\n\t\tconst flattenedHookArray = [...hookRegistry].flat();\n\n\t\tconst mergedHook = createMergedHook(flattenedHookArray, options.mergedHooksExecutionMode);\n\n\t\tresolvedHooks[key as keyof Interceptors] = mergedHook;\n\t}\n\n\treturn {\n\t\tresolvedHooks,\n\t\tresolvedOptions,\n\t\tresolvedRequestOptions,\n\t\turl: resolvedUrl?.toString(),\n\t};\n};\n","import type { CallApiExtraOptions, CallApiRequestOptions } from \"./types/common\";\nimport { getFetchImpl, waitUntil } 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 = {\n\t$RequestInfoCache: RequestInfoCache;\n\tnewFetchController: AbortController;\n\toptions: CallApiExtraOptions;\n\trequest: CallApiRequestOptions;\n};\n\nexport const createDedupeStrategy = async (context: DedupeContext) => {\n\tconst { $RequestInfoCache, newFetchController, options, request } = context;\n\n\tconst generateDedupeKey = () => {\n\t\tconst shouldHaveDedupeKey =\n\t\t\toptions.dedupeStrategy === \"cancel\" || options.dedupeStrategy === \"defer\";\n\n\t\tif (!shouldHaveDedupeKey) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn `${options.fullURL}-${JSON.stringify({ options, request })}`;\n\t};\n\n\tconst dedupeKey = options.dedupeKey ?? generateDedupeKey();\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 waitUntil(0.1);\n\t}\n\n\tconst prevRequestInfo = $RequestInfoCacheOrNull?.get(dedupeKey);\n\n\tconst handleRequestCancelStrategy = () => {\n\t\tconst shouldCancelRequest = prevRequestInfo && options.dedupeStrategy === \"cancel\";\n\n\t\tif (!shouldCancelRequest) return;\n\n\t\tconst message = options.dedupeKey\n\t\t\t? `Duplicate request detected - Aborting previous request with key '${options.dedupeKey}' as a new request was initiated`\n\t\t\t: `Duplicate request detected - Aborting previous request to '${options.fullURL}' as a new request with identical options was initiated`;\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 = () => {\n\t\tconst fetchApi = getFetchImpl(options.customFetchImpl);\n\n\t\tconst shouldUsePromiseFromCache = prevRequestInfo && options.dedupeStrategy === \"defer\";\n\n\t\tconst responsePromise = shouldUsePromiseFromCache\n\t\t\t? prevRequestInfo.responsePromise\n\t\t\t: fetchApi(options.fullURL as NonNullable<typeof options.fullURL>, request as RequestInit);\n\n\t\t$RequestInfoCacheOrNull?.set(dedupeKey, { controller: newFetchController, responsePromise });\n\n\t\treturn responsePromise;\n\t};\n\n\tconst removeDedupeKeyFromCache = () => $RequestInfoCacheOrNull?.delete(dedupeKey);\n\n\treturn {\n\t\thandleRequestCancelStrategy,\n\t\thandleRequestDeferStrategy,\n\t\tremoveDedupeKeyFromCache,\n\t};\n};\n","import type { CallApiExtraOptions, CallApiResultSuccessVariant, ResultModeMap } from \"./types\";\nimport { omitKeys } from \"./utils/common\";\nimport type { Awaitable } from \"./utils/type-helpers\";\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\tif (parser) {\n\t\t\tconst text = await response.text();\n\t\t\treturn parser(text) as TResponse;\n\t\t}\n\n\t\treturn response.json() as Promise<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 | undefined;\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\tTComputedMap extends ResponseTypeMap<TResponse> = ResponseTypeMap<TResponse>,\n> = undefined extends TResponseType\n\t? TComputedMap[\"json\"]\n\t: TResponseType extends NonNullable<ResponseTypeUnion>\n\t\t? TComputedMap[TResponseType]\n\t\t: never;\n\nexport const resolveResponseData = async <TResponse>(\n\tresponse: Response,\n\tresponseType: keyof ResponseTypeMap<TResponse>,\n\tparser: Parser | undefined\n) => {\n\tconst RESPONSE_TYPE_LOOKUP = getResponseType<TResponse>(response, parser);\n\n\tif (!Object.hasOwn(RESPONSE_TYPE_LOOKUP, responseType)) {\n\t\tthrow new Error(`Invalid response type: ${responseType}`);\n\t}\n\n\tconst responseData = await RESPONSE_TYPE_LOOKUP[responseType]();\n\n\treturn responseData;\n};\n\ntype SuccessInfo = {\n\tdata: unknown;\n\tresponse: Response;\n\tresultMode: CallApiExtraOptions[\"resultMode\"];\n};\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 = <TCallApiResult>(info: SuccessInfo): TCallApiResult => {\n\tconst { data, response, resultMode } = info;\n\n\tconst apiDetails = { data, error: null, response } satisfies CallApiResultSuccessVariant<unknown>;\n\n\tif (!resultMode) {\n\t\treturn apiDetails as TCallApiResult;\n\t}\n\n\tconst resultModeMap = {\n\t\tall: apiDetails,\n\t\tallWithException: apiDetails,\n\t\tallWithoutResponse: omitKeys(apiDetails, [\"response\"]),\n\t\tonlyError: apiDetails.error,\n\t\tonlyResponse: apiDetails.response,\n\t\tonlyResponseWithException: apiDetails.response,\n\t\tonlySuccess: apiDetails.data,\n\t\tonlySuccessWithException: apiDetails.data,\n\t} satisfies ResultModeMap;\n\n\treturn resultModeMap[resultMode] as TCallApiResult;\n};\n","/* eslint-disable ts-eslint/consistent-type-definitions -- I need to use interfaces for the sake of user overrides */\n\nimport type { Method } from \"./types\";\nimport type { ErrorContext } from \"./types/common\";\nimport type { AnyNumber } from \"./utils/type-helpers\";\n\ntype RetryCondition<TErrorData> = (context: ErrorContext<TErrorData>) => boolean | Promise<boolean>;\n\nexport interface RetryOptions<TErrorData> {\n\t/**\n\t * Keeps track of the number of times the request has already been retried\n\t * @deprecated This property is used internally to track retries. Please abstain from modifying it.\n\t */\n\treadonly \"~retryCount\"?: number;\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;\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?: Method[];\n\n\t/**\n\t * HTTP status codes that trigger a retry\n\t * @default [409, 425, 429, 500, 502, 503, 504]\n\t */\n\tretryStatusCodes?: Array<409 | 425 | 429 | 500 | 502 | 503 | 504 | AnyNumber>;\n\n\t/**\n\t * Strategy to use when retrying\n\t * @default \"linear\"\n\t */\n\tretryStrategy?: \"exponential\" | \"linear\";\n}\n\nconst getLinearDelay = <TErrorData>(options: RetryOptions<TErrorData>) => options.retryDelay ?? 1000;\n\nconst getExponentialDelay = <TErrorData>(\n\tcurrentAttemptCount: number,\n\toptions: RetryOptions<TErrorData>\n) => {\n\tconst maxDelay = options.retryMaxDelay ?? 10000;\n\n\tconst exponentialDelay = (options.retryDelay ?? 1000) * 2 ** currentAttemptCount;\n\n\treturn Math.min(exponentialDelay, maxDelay);\n};\n\nexport const createRetryStrategy = <TErrorData>(\n\toptions: RetryOptions<TErrorData>,\n\tctx: ErrorContext<TErrorData>\n) => {\n\tconst currentRetryCount = options[\"~retryCount\"] ?? 0;\n\n\tconst getDelay = () => {\n\t\tif (options.retryStrategy === \"exponential\") {\n\t\t\treturn getExponentialDelay(currentRetryCount, options);\n\t\t}\n\n\t\treturn getLinearDelay(options);\n\t};\n\n\tconst shouldAttemptRetry = async () => {\n\t\tconst customRetryCondition = (await options.retryCondition?.(ctx)) ?? true;\n\n\t\tconst maxRetryAttempts = options.retryAttempts ?? 0;\n\n\t\tconst baseRetryCondition = maxRetryAttempts > currentRetryCount && customRetryCondition;\n\n\t\tif (ctx.error.name !== \"HTTPError\") {\n\t\t\treturn baseRetryCondition;\n\t\t}\n\n\t\tconst includesMethod =\n\t\t\t// eslint-disable-next-line no-implicit-coercion -- Boolean doesn't narrow\n\t\t\t!!ctx.request.method && options.retryMethods?.includes(ctx.request.method);\n\n\t\tconst includesCodes =\n\t\t\t// eslint-disable-next-line no-implicit-coercion -- Boolean doesn't narrow\n\t\t\t!!ctx.response?.status && options.retryStatusCodes?.includes(ctx.response.status);\n\n\t\treturn includesCodes && includesMethod && baseRetryCondition;\n\t};\n\n\treturn {\n\t\tgetDelay,\n\t\tshouldAttemptRetry,\n\t};\n};\n","/* eslint-disable ts-eslint/consistent-type-definitions -- I need to use interfaces for the sake of user overrides */\n\nimport type { CallApiExtraOptions } from \"./types/common\";\nimport { toQueryString } from \"./utils\";\nimport { isArray } from \"./utils/type-guards\";\nimport type { UnmaskType } from \"./utils/type-helpers\";\nimport type { CallApiSchemas, InferSchemaResult } 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 mergeUrlWithParamsAndQuery = (\n\turl: string | undefined,\n\tparams: CallApiExtraOptions[\"params\"],\n\tquery: CallApiExtraOptions[\"query\"]\n) => {\n\tif (!url) return;\n\n\tconst urlWithMergedParams = mergeUrlWithParams(url, params);\n\n\treturn mergeUrlWithQuery(urlWithMergedParams, query);\n};\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, boolean | number | string> | Array<boolean | number | string>\n>;\n\nexport type Query = UnmaskType<Record<string, boolean | number | string>>;\n\nexport type InitURL = UnmaskType<string | URL>;\n\nexport interface UrlOptions<TSchemas extends CallApiSchemas> {\n\t/**\n\t * URL to be used in the request.\n\t */\n\treadonly initURL?: string;\n\n\t/**\n\t * Parameters to be appended to the URL (i.e: /:id)\n\t */\n\tparams?: InferSchemaResult<TSchemas[\"params\"], Params>;\n\n\t/**\n\t * Query parameters to append to the URL.\n\t */\n\tquery?: InferSchemaResult<TSchemas[\"query\"], Query>;\n}\n","// prettier-ignore\nexport const createCombinedSignal = (...signals: Array<AbortSignal | null | undefined>) => AbortSignal.any(signals.filter(Boolean));\n\nexport const createTimeoutSignal = (milliseconds: number) => AbortSignal.timeout(milliseconds);\n","/* eslint-disable ts-eslint/consistent-type-definitions -- I need to use interfaces for the sake of user overrides */\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Body, GlobalMeta, Headers, Method } from \"./types\";\nimport type { CombinedCallApiExtraOptions } from \"./types/common\";\nimport type { InitURL, Params, Query } from \"./url\";\n\nexport const standardSchemaParser = async <TSchema extends StandardSchemaV1>(\n\tschema: TSchema,\n\tinputData: StandardSchemaV1.InferInput<TSchema>\n): Promise<StandardSchemaV1.InferOutput<TSchema>> => {\n\tconst result = await 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 Error(JSON.stringify(result.issues, null, 2), { cause: result.issues });\n\t}\n\n\treturn result.value;\n};\n\nexport interface CallApiSchemas {\n\t/**\n\t * The schema to use for validating the request body.\n\t */\n\tbody?: StandardSchemaV1<Body>;\n\n\t/**\n\t * The schema to use for validating the response data.\n\t */\n\tdata?: StandardSchemaV1;\n\n\t/**\n\t * The schema to use for validating the response error data.\n\t */\n\terrorData?: StandardSchemaV1;\n\n\t/**\n\t * The schema to use for validating the request headers.\n\t */\n\theaders?: StandardSchemaV1<Headers>;\n\n\t/**\n\t * The schema to use for validating the request url.\n\t */\n\tinitURL?: StandardSchemaV1<InitURL>;\n\n\t/**\n\t * The schema to use for validating the meta option.\n\t */\n\tmeta?: StandardSchemaV1<GlobalMeta>;\n\n\t/**\n\t * The schema to use for validating the request method.\n\t */\n\tmethod?: StandardSchemaV1<Method>;\n\n\t/**\n\t * The schema to use for validating the request url parameter.\n\t */\n\tparams?: StandardSchemaV1<Params>;\n\n\t/**\n\t * The schema to use for validating the request url querys.\n\t */\n\tquery?: StandardSchemaV1<Query>;\n}\n\nexport interface CallApiValidators<TData = unknown, TErrorData = unknown> {\n\t/**\n\t * Custom function to validate the response data.\n\t */\n\tdata?: (value: unknown) => TData;\n\n\t/**\n\t * Custom function to validate the response error data, stemming from the api.\n\t * This only runs if the api actually sends back error status codes, else it will be ignored, in which case you should only use the `responseValidator` option.\n\t */\n\terrorData?: (value: unknown) => TErrorData;\n}\n\nexport type InferSchemaResult<TSchema, TData> = TSchema extends StandardSchemaV1\n\t? StandardSchemaV1.InferOutput<TSchema>\n\t: TData;\n\nexport const createExtensibleSchemasAndValidators = (options: CombinedCallApiExtraOptions) => {\n\tconst schemas =\n\t\toptions.schemas && ({ ...options.schemas, ...options.extend?.schemas } as CallApiSchemas);\n\n\tconst validators = options.validators && { ...options.validators, ...options.extend?.validators };\n\n\treturn { schemas, validators };\n};\n\nexport const handleValidation = async (\n\tresponseData: unknown,\n\tschema: CallApiSchemas[keyof NonNullable<CallApiSchemas>],\n\tvalidator?: CallApiValidators[keyof NonNullable<CallApiValidators>]\n) => {\n\tconst validResponseData = validator ? validator(responseData) : responseData;\n\n\tconst schemaValidResponseData = schema\n\t\t? await standardSchemaParser(schema, validResponseData)\n\t\t: validResponseData;\n\n\treturn schemaValidResponseData;\n};\n","import { type RequestInfoCache, createDedupeStrategy } from \"./dedupe\";\nimport { HTTPError, resolveErrorResult } from \"./error\";\nimport { type CallApiPlugin, hooksEnum, initializePlugins } from \"./plugins\";\nimport { type ResponseTypeUnion, resolveResponseData, resolveSuccessResult } from \"./response\";\nimport { createRetryStrategy } from \"./retry\";\nimport type {\n\tBaseCallApiExtraOptions,\n\tCallApiParameters,\n\tCallApiRequestOptions,\n\tCallApiRequestOptionsForHooks,\n\tCombinedCallApiExtraOptions,\n\tErrorContext,\n\tGetCallApiResult,\n\tInterceptors,\n\tResultModeUnion,\n\tSuccessContext,\n} from \"./types/common\";\nimport type {\n\tDefaultDataType,\n\tDefaultMoreOptions,\n\tDefaultPluginArray,\n\tDefaultThrowOnError,\n} from \"./types/default-types\";\nimport { mergeUrlWithParamsAndQuery } from \"./url\";\nimport {\n\tcombineHooks,\n\texecuteHooks,\n\tmergeAndResolveHeaders,\n\tsplitBaseConfig,\n\tsplitConfig,\n\twaitUntil,\n} from \"./utils/common\";\nimport { defaultRetryMethods, defaultRetryStatusCodes } from \"./utils/constants\";\nimport { createCombinedSignal, createTimeoutSignal } from \"./utils/polyfills\";\nimport { isFunction, isHTTPErrorInstance, isPlainObject } from \"./utils/type-guards\";\nimport {\n\ttype CallApiSchemas,\n\ttype InferSchemaResult,\n\tcreateExtensibleSchemasAndValidators,\n\thandleValidation,\n} from \"./validation\";\n\nexport const createFetchClient = <\n\tTBaseData = DefaultDataType,\n\tTBaseErrorData = DefaultDataType,\n\tTBaseResultMode extends ResultModeUnion = ResultModeUnion,\n\tTBaseThrowOnError extends boolean = DefaultThrowOnError,\n\tTBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTBaseSchemas extends CallApiSchemas = DefaultMoreOptions,\n\tTBasePluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTBaseComputedData = InferSchemaResult<TBaseSchemas[\"data\"], TBaseData>,\n\tTBaseComputedErrorData = InferSchemaResult<TBaseSchemas[\"errorData\"], TBaseErrorData>,\n>(\n\tbaseConfig?: BaseCallApiExtraOptions<\n\t\tTBaseData,\n\t\tTBaseErrorData,\n\t\tTBaseResultMode,\n\t\tTBaseThrowOnError,\n\t\tTBaseResponseType,\n\t\tTBaseSchemas,\n\t\tTBasePluginArray\n\t>\n) => {\n\tconst [baseFetchOptions, baseExtraOptions] = splitBaseConfig(baseConfig ?? {});\n\n\tconst $RequestInfoCache: RequestInfoCache = new Map();\n\n\tconst callApi = async <\n\t\tTData = TBaseComputedData,\n\t\tTErrorData = TBaseComputedErrorData,\n\t\tTResultMode extends ResultModeUnion = TBaseResultMode,\n\t\tTThrowOnError extends boolean = TBaseThrowOnError,\n\t\tTResponseType extends ResponseTypeUnion = TBaseResponseType,\n\t\tTSchemas extends CallApiSchemas = TBaseSchemas,\n\t\tTPluginArray extends CallApiPlugin[] = TBasePluginArray,\n\t\tTComputedData = InferSchemaResult<TSchemas[\"data\"], TData>,\n\t\tTComputedErrorData = InferSchemaResult<TSchemas[\"errorData\"], TErrorData>,\n\t>(\n\t\t...parameters: CallApiParameters<\n\t\t\tTData,\n\t\t\tTErrorData,\n\t\t\tTResultMode,\n\t\t\tTThrowOnError,\n\t\t\tTResponseType,\n\t\t\tTSchemas,\n\t\t\tTPluginArray\n\t\t>\n\t): Promise<\n\t\tGetCallApiResult<TComputedData, TComputedErrorData, TResultMode, TThrowOnError, TResponseType>\n\t> => {\n\t\tconst [initURL, config = {} as never] = parameters;\n\n\t\tconst [fetchOptions, extraOptions] = splitConfig(config);\n\n\t\tconst initCombinedHooks = {} as Required<Interceptors>;\n\n\t\tfor (const key of Object.keys(hooksEnum)) {\n\t\t\tconst combinedHook = combineHooks(\n\t\t\t\tbaseExtraOptions[key as keyof Interceptors],\n\t\t\t\textraOptions[key as keyof Interceptors]\n\t\t\t);\n\n\t\t\tinitCombinedHooks[key as keyof Interceptors] = combinedHook as never;\n\t\t}\n\n\t\t// == Default Extra Options\n\t\tconst defaultExtraOptions = {\n\t\t\tbaseURL: \"\",\n\t\t\tbodySerializer: JSON.stringify,\n\t\t\tdedupeStrategy: \"cancel\",\n\t\t\tdefaultErrorMessage: \"Failed to fetch data from server!\",\n\t\t\tmergedHooksExecutionMode: \"parallel\",\n\t\t\tmergedHooksExecutionOrder: \"mainHooksAfterPlugins\",\n\t\t\tresponseType: \"json\",\n\t\t\tresultMode: \"all\",\n\t\t\tretryAttempts: 0,\n\t\t\tretryDelay: 1000,\n\t\t\tretryMaxDelay: 10000,\n\t\t\tretryMethods: defaultRetryMethods,\n\t\t\tretryStatusCodes: defaultRetryStatusCodes,\n\t\t\tretryStrategy: \"linear\",\n\n\t\t\t...baseExtraOptions,\n\t\t\t...extraOptions,\n\n\t\t\t...initCombinedHooks,\n\t\t} satisfies CombinedCallApiExtraOptions;\n\n\t\tconst body = fetchOptions.body ?? baseFetchOptions.body;\n\n\t\t// == Default Request Options\n\t\tconst defaultRequestOptions = {\n\t\t\t...baseFetchOptions,\n\t\t\t...fetchOptions,\n\n\t\t\tbody: isPlainObject(body) ? defaultExtraOptions.bodySerializer(body) : body,\n\n\t\t\theaders: mergeAndResolveHeaders({\n\t\t\t\tauth: defaultExtraOptions.auth,\n\t\t\t\tbaseHeaders: baseFetchOptions.headers,\n\t\t\t\tbody,\n\t\t\t\theaders: fetchOptions.headers,\n\t\t\t}),\n\n\t\t\tsignal: fetchOptions.signal ?? baseFetchOptions.signal,\n\t\t} satisfies CallApiRequestOptions;\n\n\t\tconst { resolvedHooks, resolvedOptions, resolvedRequestOptions, url } = await initializePlugins({\n\t\t\tinitURL,\n\t\t\toptions: defaultExtraOptions,\n\t\t\trequest: defaultRequestOptions,\n\t\t});\n\n\t\tconst fullURL = `${resolvedOptions.baseURL}${mergeUrlWithParamsAndQuery(url, resolvedOptions.params, resolvedOptions.query)}`;\n\n\t\tconst options = {\n\t\t\t...resolvedOptions,\n\t\t\t...resolvedHooks,\n\t\t\tfullURL,\n\t\t\tinitURL: initURL.toString(),\n\t\t} satisfies CombinedCallApiExtraOptions as typeof defaultExtraOptions & typeof resolvedHooks;\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\tconst request = {\n\t\t\t...resolvedRequestOptions,\n\t\t\tsignal: combinedSignal,\n\t\t} satisfies CallApiRequestOptionsForHooks;\n\n\t\tconst { handleRequestCancelStrategy, handleRequestDeferStrategy, removeDedupeKeyFromCache } =\n\t\t\tawait createDedupeStrategy({ $RequestInfoCache, newFetchController, options, request });\n\n\t\tawait handleRequestCancelStrategy();\n\n\t\ttry {\n\t\t\tawait executeHooks(options.onRequest({ options, request }));\n\n\t\t\t// == Apply determined headers again after onRequest incase they were modified\n\t\t\trequest.headers = mergeAndResolveHeaders({\n\t\t\t\tauth: options.auth,\n\t\t\t\tbaseHeaders: baseFetchOptions.headers,\n\t\t\t\tbody,\n\t\t\t\theaders: request.headers,\n\t\t\t});\n\n\t\t\tconst response = await handleRequestDeferStrategy();\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 = options.dedupeStrategy === \"defer\" || options.cloneResponse;\n\n\t\t\tconst { schemas, validators } = createExtensibleSchemasAndValidators(options);\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(\n\t\t\t\t\terrorData,\n\t\t\t\t\tschemas?.errorData,\n\t\t\t\t\tvalidators?.errorData\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\tdefaultErrorMessage: options.defaultErrorMessage,\n\t\t\t\t\terrorData: validErrorData,\n\t\t\t\t\tresponse,\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(successData, schemas?.data, validators?.data);\n\n\t\t\tconst successContext = {\n\t\t\t\tdata: validSuccessData,\n\t\t\t\toptions,\n\t\t\t\trequest,\n\t\t\t\tresponse: options.cloneResponse ? response.clone() : response,\n\t\t\t} satisfies SuccessContext<unknown>;\n\n\t\t\tawait executeHooks(\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\treturn await resolveSuccessResult({\n\t\t\t\tdata: successContext.data,\n\t\t\t\tresponse: successContext.response,\n\t\t\t\tresultMode: options.resultMode,\n\t\t\t});\n\n\t\t\t// == Exhaustive Error handling\n\t\t} catch (error) {\n\t\t\tconst { apiDetails, getErrorResult } = resolveErrorResult({\n\t\t\t\tcloneResponse: options.cloneResponse,\n\t\t\t\tdefaultErrorMessage: options.defaultErrorMessage,\n\t\t\t\terror,\n\t\t\t\tresultMode: options.resultMode,\n\t\t\t});\n\n\t\t\tconst errorContext = {\n\t\t\t\terror: apiDetails.error as never,\n\t\t\t\toptions,\n\t\t\t\trequest,\n\t\t\t\tresponse: apiDetails.response as never,\n\t\t\t} satisfies ErrorContext<unknown>;\n\n\t\t\tconst { getDelay, shouldAttemptRetry } = createRetryStrategy(options, errorContext);\n\n\t\t\tconst shouldRetry = !combinedSignal.aborted && (await shouldAttemptRetry());\n\n\t\t\tif (shouldRetry) {\n\t\t\t\tawait executeHooks(options.onRetry(errorContext));\n\n\t\t\t\tconst delay = getDelay();\n\n\t\t\t\tawait waitUntil(delay);\n\n\t\t\t\tconst updatedOptions = {\n\t\t\t\t\t...config,\n\t\t\t\t\t\"~retryCount\": (options[\"~retryCount\"] ?? 0) + 1,\n\t\t\t\t} satisfies typeof config as typeof config;\n\n\t\t\t\treturn await callApi(initURL, updatedOptions);\n\t\t\t}\n\n\t\t\tconst shouldThrowOnError = isFunction(options.throwOnError)\n\t\t\t\t? options.throwOnError(errorContext)\n\t\t\t\t: options.throwOnError;\n\n\t\t\t// eslint-disable-next-line unicorn/consistent-function-scoping -- False alarm: this function is depends on this scope\n\t\t\tconst handleThrowOnError = () => {\n\t\t\t\tif (!shouldThrowOnError) return;\n\n\t\t\t\t// eslint-disable-next-line ts-eslint/only-throw-error -- It's fine to throw this\n\t\t\t\tthrow apiDetails.error;\n\t\t\t};\n\n\t\t\tif (isHTTPErrorInstance<TErrorData>(error)) {\n\t\t\t\tawait executeHooks(\n\t\t\t\t\toptions.onResponseError(errorContext),\n\n\t\t\t\t\toptions.onError(errorContext),\n\n\t\t\t\t\toptions.onResponse({ ...errorContext, data: null })\n\t\t\t\t);\n\n\t\t\t\thandleThrowOnError();\n\n\t\t\t\treturn getErrorResult();\n\t\t\t}\n\n\t\t\tif (error instanceof DOMException && error.name === \"AbortError\") {\n\t\t\t\tconst { message, name } = error;\n\n\t\t\t\tconsole.error(`${name}:`, message);\n\n\t\t\t\thandleThrowOnError();\n\n\t\t\t\treturn getErrorResult();\n\t\t\t}\n\n\t\t\tif (error instanceof DOMException && error.name === \"TimeoutError\") {\n\t\t\t\tconst message = `Request timed out after ${options.timeout}ms`;\n\n\t\t\t\tconsole.error(`${error.name}:`, message);\n\n\t\t\t\thandleThrowOnError();\n\n\t\t\t\treturn getErrorResult({ message });\n\t\t\t}\n\n\t\t\tawait executeHooks(\n\t\t\t\t// == At this point only the request errors exist, so the request error interceptor is called\n\t\t\t\toptions.onRequestError(errorContext as never),\n\n\t\t\t\t// == Also call the onError interceptor\n\t\t\t\toptions.onError(errorContext)\n\t\t\t);\n\n\t\t\thandleThrowOnError();\n\n\t\t\treturn getErrorResult();\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\tcallApi.create = createFetchClient;\n\n\treturn callApi;\n};\n\nexport const callApi = createFetchClient();\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=e=>{const{cloneResponse:r,defaultErrorMessage:t,error:n,message:a,resultMode:i}=e;let c={data:null,error:{errorData:n,message:a??n.message,name:n.name},response:null};if(o(n)){const{errorData:e,message:o=t,name:s,response:a}=n;c={data:null,error:{errorData:e,message:o,name:s},response:r?a.clone():a}}const l={all:c,allWithException:c,allWithoutResponse:T(c,["response"]),onlyError:c.error,onlyResponse:c.response,onlyResponseWithException:c.response,onlySuccess:c.data,onlySuccessWithException:c.data};return{apiDetails:c,getErrorResult:e=>{const r=l[i??"all"];return s(e)?{...r,...e}:r}}},r=class extends Error{errorData;isHTTPError=!0;name="HTTPError";response;constructor(e,r){const{defaultErrorMessage:t,errorData:o,response:n}=e;super(o?.message??t,r),this.errorData=o,this.response=n,Error.captureStackTrace(this,this.constructor)}},t=e=>i(e)&&"HTTPError"===e.name,o=e=>e instanceof r||i(e)&&"HTTPError"===e.name&&!0===e.isHTTPError,n=e=>Array.isArray(e),s=e=>"object"==typeof e&&null!==e,a=e=>"[object Object]"===Object.prototype.toString.call(e),i=e=>{if(!a(e))return!1;const r=e?.constructor;if(void 0===r)return!0;const t=r.prototype;return!!a(t)&&(!!Object.hasOwn(t,"isPrototypeOf")&&Object.getPrototypeOf(e)===Object.prototype)},c=e=>"function"==typeof e,l=e=>"string"==typeof e,u=e=>c(e)?e():e,p=e=>{if(void 0!==e){if(l(e)||null===e)return{Authorization:`Bearer ${e}`};switch(e.type){case"Basic":{const r=u(e.username),t=u(e.password);if(void 0===r||void 0===t)return;return{Authorization:`Basic ${globalThis.btoa(`${r}:${t}`)}`}}case"Custom":{const r=u(e.value);if(void 0===r)return;return{Authorization:`${u(e.prefix)} ${r}`}}default:{const r=u(e.bearer),t=u(e.token);return"token"in e&&void 0!==t?{Authorization:`Token ${t}`}:void 0!==r&&{Authorization:`Bearer ${r}`}}}}},d=["extend","dedupeKey"],f=["body","integrity","method","headers","signal","cache","redirect","window","credentials","keepalive","referrer","priority","mode","referrerPolicy"],h={408:"Request Timeout",409:"Conflict",425:"Too Early",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"},m=["GET","POST"],y=Object.keys(h).map(Number),T=(e,r)=>{const t={},o=new Set(r);for(const[r,n]of Object.entries(e))o.has(r)||(t[r]=n);return t},b=(e,r)=>{const t={},o=new Set(r);for(const[r,n]of Object.entries(e))o.has(r)&&(t[r]=n);return t},g=e=>[b(e,f),T(e,[...f,...d])],E=e=>[b(e,f),T(e,f)],v=e=>!e||i(e)?e:Object.fromEntries(e),w=e=>e?new URLSearchParams(e).toString():(console.error("toQueryString:","No query params provided!"),null),j=e=>{const{auth:r,baseHeaders:t,body:o,headers:n}=e;if(!Boolean(t||n||o||r))return;const s={...p(r),...v(t),...v(n)};return l(a=o)&&a.includes("=")?(s["Content-Type"]="application/x-www-form-urlencoded",s):((i(o)||l(o)&&o.startsWith("{"))&&(s["Content-Type"]="application/json",s.Accept="application/json"),s);var a},O=(e,r)=>n(e)?[e,r].flat():r??e,P=e=>{if(e)return e;if("undefined"!=typeof globalThis&&c(globalThis.fetch))return globalThis.fetch;throw new Error("No fetch implementation found")},S=(...e)=>Promise.all(e),x=e=>{if(0===e)return;const{promise:r,resolve:t}=(()=>{let e,r;return{promise:new Promise(((t,o)=>{r=t,e=o})),reject:e,resolve:r}})();return setTimeout(t,e),r};export{r as HTTPError,O as combineHooks,m as defaultRetryMethods,y as defaultRetryStatusCodes,S as executeHooks,P as getFetchImpl,n as isArray,c as isFunction,t as isHTTPError,o as isHTTPErrorInstance,i as isPlainObject,l as isString,j as mergeAndResolveHeaders,T as omitKeys,e as resolveErrorResult,g as splitBaseConfig,E as splitConfig,w as toQueryString,x as waitUntil};//# sourceMappingURL=chunk-MOMG57MZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/error.ts","../../src/utils/type-guards.ts","../../src/auth.ts","../../src/utils/type-helpers.ts","../../src/types/common.ts","../../src/utils/constants.ts","../../src/utils/common.ts"],"names":[],"mappings":";AAiBa,IAAA,kBAAA,GAAqB,CAAyB,IAAoB,KAAA;AAC9E,EAAA,MAAM,EAAE,aAAe,EAAA,mBAAA,EAAqB,OAAO,OAAS,EAAA,kBAAA,EAAoB,YAAe,GAAA,IAAA;AAE/F,EAAA,IAAI,UAAiD,GAAA;AAAA,IACpD,IAAM,EAAA,IAAA;AAAA,IACN,KAAO,EAAA;AAAA,MACN,SAAW,EAAA,KAAA;AAAA,MACX,OAAA,EAAS,sBAAuB,KAAgB,CAAA,OAAA;AAAA,MAChD,MAAO,KAAgB,CAAA;AAAA,KACxB;AAAA,IACA,QAAU,EAAA;AAAA,GACX;AAEA,EAAI,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CAAG,EAAA;AAEjB,EAAA,MAAM,EAAE,OAAA,EAAS,OAAQ,EAAA,GAAI,oBAAqB,EAAA;AAElD,EAAA,UAAA,CAAW,SAAS,KAAK,CAAA;AAEzB,EAAO,OAAA,OAAA;AACR","file":"chunk-MOMG57MZ.js","sourcesContent":["import type {\n\tCallApiExtraOptions,\n\tCallApiResultErrorVariant,\n\tPossibleJavascriptErrorNames,\n\tResultModeMap,\n} from \"./types/common\";\nimport { omitKeys } from \"./utils/common\";\nimport { isHTTPErrorInstance, isObject } from \"./utils/type-guards\";\n\ntype ErrorInfo = {\n\tcloneResponse: CallApiExtraOptions[\"cloneResponse\"];\n\tdefaultErrorMessage: Required<CallApiExtraOptions>[\"defaultErrorMessage\"];\n\terror?: unknown;\n\tmessage?: string;\n\tresultMode: CallApiExtraOptions[\"resultMode\"];\n};\n\nexport const resolveErrorResult = <TCallApiResult = never>(info: ErrorInfo) => {\n\tconst { cloneResponse, defaultErrorMessage, error, message: customErrorMessage, resultMode } = info;\n\n\tlet apiDetails: CallApiResultErrorVariant<unknown> = {\n\t\tdata: null,\n\t\terror: {\n\t\t\terrorData: error as Error,\n\t\t\tmessage: customErrorMessage ?? (error as Error).message,\n\t\t\tname: (error as Error).name as PossibleJavascriptErrorNames,\n\t\t},\n\t\tresponse: null,\n\t};\n\n\tif (isHTTPErrorInstance<never>(error)) {\n\t\tconst { errorData, message = defaultErrorMessage, name, response } = error;\n\n\t\tapiDetails = {\n\t\t\tdata: null,\n\t\t\terror: {\n\t\t\t\terrorData,\n\t\t\t\tmessage,\n\t\t\t\tname,\n\t\t\t},\n\t\t\tresponse: cloneResponse ? response.clone() : response,\n\t\t};\n\t}\n\n\tconst resultModeMap = {\n\t\tall: apiDetails,\n\t\tallWithException: apiDetails as never,\n\t\tallWithoutResponse: omitKeys(apiDetails, [\"response\"]),\n\t\tonlyError: apiDetails.error,\n\t\tonlyResponse: apiDetails.response,\n\t\tonlyResponseWithException: apiDetails.response as never,\n\t\tonlySuccess: apiDetails.data,\n\t\tonlySuccessWithException: apiDetails.data,\n\t} satisfies ResultModeMap;\n\n\tconst getErrorResult = (customInfo?: Pick<ErrorInfo, \"message\">) => {\n\t\tconst errorResult = resultModeMap[resultMode ?? \"all\"] as TCallApiResult;\n\n\t\treturn isObject(customInfo) ? { ...errorResult, ...customInfo } : errorResult;\n\t};\n\n\treturn { apiDetails, getErrorResult };\n};\n\ntype ErrorDetails<TErrorResponse> = {\n\tdefaultErrorMessage: string;\n\terrorData: TErrorResponse;\n\tresponse: Response;\n};\n\ntype ErrorOptions = {\n\tcause?: unknown;\n};\n\nexport class HTTPError<TErrorResponse = Record<string, unknown>> extends Error {\n\terrorData: ErrorDetails<TErrorResponse>[\"errorData\"];\n\n\tisHTTPError = true;\n\n\toverride name = \"HTTPError\" as const;\n\n\tresponse: ErrorDetails<TErrorResponse>[\"response\"];\n\n\tconstructor(errorDetails: ErrorDetails<TErrorResponse>, errorOptions?: ErrorOptions) {\n\t\tconst { defaultErrorMessage, errorData, response } = errorDetails;\n\n\t\tsuper((errorData as { message?: string } | undefined)?.message ?? defaultErrorMessage, errorOptions);\n\n\t\tthis.errorData = errorData;\n\t\tthis.response = response;\n\n\t\tError.captureStackTrace(this, this.constructor);\n\t}\n}\n","import { HTTPError } from \"@/error\";\nimport type { PossibleHTTPError, PossibleJavaScriptError } from \"@/types/common\";\nimport type { AnyFunction } from \"./type-helpers\";\n\ntype ErrorObjectUnion<TErrorData = unknown> = PossibleHTTPError<TErrorData> | PossibleJavaScriptError;\n\nexport const isHTTPError = <TErrorData>(\n\terror: ErrorObjectUnion<TErrorData> | null\n): error is PossibleHTTPError<TErrorData> => {\n\treturn isPlainObject(error) && error.name === \"HTTPError\";\n};\n\nexport const isHTTPErrorInstance = <TErrorResponse>(\n\terror: unknown\n): error is HTTPError<TErrorResponse> => {\n\treturn (\n\t\t// prettier-ignore\n\t\terror instanceof HTTPError|| (isPlainObject(error) && error.name === \"HTTPError\" && error.isHTTPError === true)\n\t);\n};\n\nexport const isArray = <TArrayItem>(value: unknown): value is TArrayItem[] => Array.isArray(value);\n\nexport const isObject = (value: unknown) => typeof value === \"object\" && value !== null;\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 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\n// https://github.com/unjs/ofetch/blob/main/src/utils.ts\n// TODO Find a way to incorporate this function in checking when to apply the bodySerializer on the body and also whether to add the content type application/json\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// eslint-disable-next-line ts-eslint/prefer-nullish-coalescing -- Nullish coalescing makes no sense in this boolean context\n\t\t(value?.constructor && value.constructor.name === \"Object\") ||\n\t\ttypeof (value as { toJSON: () => unknown } | null)?.toJSON === \"function\"\n\t);\n};\n","/* eslint-disable perfectionist/sort-object-types -- Avoid Sorting for now */\n\nimport type { ExtraOptions } from \"./types/common\";\nimport { isFunction, isString } from \"./utils/type-guards\";\n\ntype ValueOrFunctionResult<TValue> = TValue | (() => TValue);\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?: ValueOrFunctionResult<string | null>;\n\t\t\ttoken?: never;\n\t }\n\t| {\n\t\t\ttype?: \"Token\";\n\t\t\tbearer?: never;\n\t\t\ttoken?: ValueOrFunctionResult<string | null>;\n\t };\n\n/**\n * Basic auth\n */\nexport type BasicAuth = {\n\ttype: \"Basic\";\n\tusername: ValueOrFunctionResult<string | null | undefined>;\n\tpassword: ValueOrFunctionResult<string | null | undefined>;\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: ValueOrFunctionResult<string | null | undefined>;\n\tvalue: ValueOrFunctionResult<string | null | undefined>;\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: ValueOrFunctionResult<string | null | undefined>) => {\n\treturn isFunction(value) ? value() : value;\n};\n\ntype AuthorizationHeader = {\n\tAuthorization: string;\n};\n\nexport const getAuthHeader = (auth: ExtraOptions[\"auth\"]): false | 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 = getValue(auth.username);\n\t\t\tconst password = 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 = getValue(auth.value);\n\n\t\t\tif (value === undefined) return;\n\n\t\t\tconst prefix = 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 = getValue(auth.bearer);\n\t\t\tconst token = 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\treturn bearer !== undefined && { Authorization: `Bearer ${bearer}` };\n\t\t}\n\t}\n};\n","// == 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 & { z_placeholder?: never };\nexport type AnyNumber = number & { z_placeholder?: never };\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 Writeable<TObject, TType extends \"deep\" | \"shallow\" = \"shallow\"> = {\n\t-readonly [key in keyof TObject]: TType extends \"shallow\"\n\t\t? TObject[key]\n\t\t: TType extends \"deep\"\n\t\t\t? TObject[key] extends object\n\t\t\t\t? Writeable<TObject[key], TType>\n\t\t\t\t: TObject[key]\n\t\t\t: never;\n};\n\nexport const defineEnum = <const TValue>(value: TValue) => value as Prettify<Writeable<TValue, \"deep\">>;\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","/* eslint-disable ts-eslint/consistent-type-definitions -- I need to use interfaces for the sake of user overrides */\nimport type { Auth } from \"../auth\";\nimport type { CallApiPlugin, InferPluginOptions, Plugins } from \"../plugins\";\nimport type { GetResponseType, ResponseTypeUnion } from \"../response\";\nimport type { RetryOptions } from \"../retry\";\nimport type { InitURL, UrlOptions } from \"../url\";\nimport type { fetchSpecificKeys } from \"../utils/constants\";\nimport { type Awaitable, type UnmaskType, defineEnum } from \"../utils/type-helpers\";\nimport type { CallApiSchemas, CallApiValidators, InferSchemaResult } from \"../validation\";\nimport type {\n\tBodyOption,\n\tHeadersOption,\n\tMetaOption,\n\tMethodOption,\n\tResultModeOption,\n} from \"./conditional-types\";\nimport type {\n\tDefaultDataType,\n\tDefaultMoreOptions,\n\tDefaultPluginArray,\n\tDefaultThrowOnError,\n} from \"./default-types\";\n\ntype FetchSpecificKeysUnion = Exclude<(typeof fetchSpecificKeys)[number], \"body\" | \"headers\" | \"method\">;\n\nexport type CallApiRequestOptions<TSchemas extends CallApiSchemas = DefaultMoreOptions> =\n\tBodyOption<TSchemas> &\n\t\tHeadersOption<TSchemas> &\n\t\tMethodOption<TSchemas> &\n\t\tPick<RequestInit, FetchSpecificKeysUnion>;\n\nexport type CallApiRequestOptionsForHooks<TSchemas extends CallApiSchemas = DefaultMoreOptions> = Omit<\n\tCallApiRequestOptions<TSchemas>,\n\t\"headers\"\n> & {\n\theaders?: Record<string, string | undefined>;\n};\n\nexport type WithMoreOptions<TMoreOptions = DefaultMoreOptions> = {\n\toptions: CombinedCallApiExtraOptions & Partial<TMoreOptions>;\n};\n\nexport interface Interceptors<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTMoreOptions = DefaultMoreOptions,\n> {\n\t/**\n\t * Interceptor 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` interceptors\n\t */\n\tonError?: (context: ErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;\n\n\t/**\n\t * Interceptor that will be called just before the request is made, allowing for modifications or additional operations.\n\t */\n\tonRequest?: (context: RequestContext & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;\n\n\t/**\n\t * Interceptor that will be called when an error occurs during the fetch request.\n\t */\n\tonRequestError?: (context: RequestErrorContext & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;\n\n\t/**\n\t * Interceptor 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> & WithMoreOptions<TMoreOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Interceptor that will be called when an error response is received from the api.\n\t */\n\tonResponseError?: (\n\t\tcontext: ResponseErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Interceptor that will be called when a request is retried.\n\t */\n\tonRetry?: (response: ErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;\n\t/**\n\t * Interceptor that will be called when a successful response is received from the api.\n\t */\n\tonSuccess?: (context: SuccessContext<TData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;\n}\n\n/* eslint-disable perfectionist/sort-union-types -- I need arrays to be last */\nexport type InterceptorsOrInterceptorArray<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTMoreOptions = DefaultMoreOptions,\n> = {\n\t[Key in keyof Interceptors<TData, TErrorData, TMoreOptions>]:\n\t\t| Interceptors<TData, TErrorData, TMoreOptions>[Key]\n\t\t| Array<Interceptors<TData, TErrorData, TMoreOptions>[Key]>;\n};\n/* eslint-enable perfectionist/sort-union-types -- I need arrays to be last */\n\ntype FetchImpl = UnmaskType<(input: string | Request | URL, init?: RequestInit) => Promise<Response>>;\n\nexport type ExtraOptions<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTThrowOnError extends boolean = DefaultThrowOnError,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTSchemas extends CallApiSchemas = DefaultMoreOptions,\n\tTPluginArray extends CallApiPlugin[] = DefaultPluginArray,\n> = {\n\t/**\n\t * Authorization header value.\n\t */\n\tauth?: string | Auth | null;\n\t/**\n\t * Base URL to be prepended to all request URLs\n\t */\n\tbaseURL?: string;\n\n\t/**\n\t * Custom function to serialize the body object into a string.\n\t */\n\tbodySerializer?: (bodyData: Record<string, unknown>) => string;\n\n\t/**\n\t * Whether or not to clone the response, so response.json() and the like, can be read again else where.\n\t * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/clone\n\t * @default false\n\t */\n\tcloneResponse?: boolean;\n\n\t/**\n\t * Custom fetch implementation\n\t */\n\tcustomFetchImpl?: FetchImpl;\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\t/**\n\t * Default error message to use if none is provided from a response.\n\t * @default \"Failed to fetch data from server!\"\n\t */\n\tdefaultErrorMessage?: string;\n\n\t/**\n\t * Resolved request URL\n\t */\n\treadonly fullURL?: string;\n\n\t/**\n\t * Defines the mode in which the merged hooks are executed, can be set to \"parallel\" | \"sequential\".\n\t * - If set to \"parallel\", main and plugin hooks will be executed in parallel.\n\t * - If set to \"sequential\", the plugin hooks will be executed first, followed by the main hook.\n\t * @default \"parallel\"\n\t */\n\tmergedHooksExecutionMode?: \"parallel\" | \"sequential\";\n\n\t/**\n\t * - Controls what order in which the merged hooks execute\n\t * @default \"mainHooksLast\"\n\t */\n\tmergedHooksExecutionOrder?: \"mainHooksAfterPlugins\" | \"mainHooksBeforePlugins\";\n\n\t/**\n\t * An array of CallApi plugins. It allows you to extend the behavior of the library.\n\t */\n\tplugins?: Plugins<TPluginArray>;\n\n\t/**\n\t * Custom function to parse the response string into a object.\n\t */\n\tresponseParser?: (responseString: string) => Awaitable<Record<string, unknown>>;\n\n\t/**\n\t * Expected response type, affects how response is parsed\n\t * @default \"json\"\n\t */\n\tresponseType?: TResponseType;\n\n\t/**\n\t * Mode of the result, can influence how results are handled or returned.\n\t * Can be set to \"all\" | \"onlySuccess\" | \"onlyError\" | \"onlyResponse\".\n\t * @default \"all\"\n\t */\n\tresultMode?: TResultMode;\n\n\t/**\n\t * Type-safe schemas for the response validation.\n\t */\n\tschemas?: TSchemas;\n\n\t/**\n\t * If true or the function returns true, throws errors instead of returning them\n\t * The function is passed the error object and can be used to conditionally throw the error\n\t * @default false\n\t */\n\tthrowOnError?: TThrowOnError | ((context: ErrorContext<TErrorData>) => TThrowOnError);\n\n\t/**\n\t * Request timeout in milliseconds\n\t */\n\ttimeout?: number;\n\n\t/**\n\t * Custom validation functions for response validation\n\t */\n\tvalidators?: CallApiValidators<TData, TErrorData>;\n\t/* eslint-disable perfectionist/sort-intersection-types -- Allow these to be last for the sake of docs */\n} & InterceptorsOrInterceptorArray<TData, TErrorData> &\n\tPartial<InferPluginOptions<TPluginArray>> &\n\tMetaOption<TSchemas> &\n\tRetryOptions<TErrorData> &\n\tResultModeOption<TErrorData, TResultMode> &\n\tUrlOptions<TSchemas>;\n/* eslint-enable perfectionist/sort-intersection-types -- Allow these to be last for the sake of docs */\n\nexport const optionsEnumToExtendFromBase = defineEnum([\"plugins\", \"validators\", \"schemas\"] satisfies Array<\n\tkeyof ExtraOptions\n>);\n\nexport type CallApiExtraOptions<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTThrowOnError extends boolean = DefaultThrowOnError,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTSchemas extends CallApiSchemas = DefaultMoreOptions,\n\tTPluginArray extends CallApiPlugin[] = DefaultPluginArray,\n> = CallApiRequestOptions<TSchemas> &\n\tExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TSchemas, TPluginArray> & {\n\t\t/**\n\t\t * Options that should extend the base options.\n\t\t */\n\t\textend?: Pick<\n\t\t\tExtraOptions<\n\t\t\t\tTData,\n\t\t\t\tTErrorData,\n\t\t\t\tTResultMode,\n\t\t\t\tTThrowOnError,\n\t\t\t\tTResponseType,\n\t\t\t\tTSchemas,\n\t\t\t\tTPluginArray\n\t\t\t>,\n\t\t\t(typeof optionsEnumToExtendFromBase)[number]\n\t\t>;\n\t};\n\nexport const optionsEnumToOmitFromBase = defineEnum([\"extend\", \"dedupeKey\"] satisfies Array<\n\tkeyof CallApiExtraOptions\n>);\n\nexport type BaseCallApiExtraOptions<\n\tTBaseData = DefaultDataType,\n\tTBaseErrorData = DefaultDataType,\n\tTBaseResultMode extends ResultModeUnion = ResultModeUnion,\n\tTBaseThrowOnError extends boolean = DefaultThrowOnError,\n\tTBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTBaseSchemas extends CallApiSchemas = DefaultMoreOptions,\n\tTBasePluginArray extends CallApiPlugin[] = DefaultPluginArray,\n> = Omit<\n\tPartial<\n\t\tCallApiExtraOptions<\n\t\t\tTBaseData,\n\t\t\tTBaseErrorData,\n\t\t\tTBaseResultMode,\n\t\t\tTBaseThrowOnError,\n\t\t\tTBaseResponseType,\n\t\t\tTBaseSchemas,\n\t\t\tTBasePluginArray\n\t\t>\n\t>,\n\t(typeof optionsEnumToOmitFromBase)[number]\n>;\n\nexport type CombinedCallApiExtraOptions = BaseCallApiExtraOptions & CallApiExtraOptions;\n\nexport type CallApiParameters<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTThrowOnError extends boolean = DefaultThrowOnError,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTSchemas extends CallApiSchemas = DefaultMoreOptions,\n\tTPluginArray extends CallApiPlugin[] = DefaultPluginArray,\n> = [\n\tinitURL: InferSchemaResult<TSchemas[\"initURL\"], InitURL>,\n\tconfig?: CallApiExtraOptions<\n\t\tTData,\n\t\tTErrorData,\n\t\tTResultMode,\n\t\tTThrowOnError,\n\t\tTResponseType,\n\t\tTSchemas,\n\t\tTPluginArray\n\t>,\n];\n\nexport type RequestContext = UnmaskType<{\n\toptions: CombinedCallApiExtraOptions;\n\trequest: CallApiRequestOptionsForHooks;\n}>;\n\nexport type ResponseContext<TData, TErrorData> = UnmaskType<\n\t| {\n\t\t\tdata: TData;\n\t\t\terror: null;\n\t\t\toptions: CombinedCallApiExtraOptions;\n\t\t\trequest: CallApiRequestOptionsForHooks;\n\t\t\tresponse: Response;\n\t }\n\t// eslint-disable-next-line perfectionist/sort-union-types -- I need the first one to be first\n\t| {\n\t\t\tdata: null;\n\t\t\terror: PossibleHTTPError<TErrorData>;\n\t\t\toptions: CombinedCallApiExtraOptions;\n\t\t\trequest: CallApiRequestOptionsForHooks;\n\t\t\tresponse: Response;\n\t }\n>;\n\nexport type SuccessContext<TData> = UnmaskType<{\n\tdata: TData;\n\toptions: CombinedCallApiExtraOptions;\n\trequest: CallApiRequestOptionsForHooks;\n\tresponse: Response;\n}>;\n\nexport type PossibleJavascriptErrorNames =\n\t| \"AbortError\"\n\t| \"Error\"\n\t| \"SyntaxError\"\n\t| \"TimeoutError\"\n\t| \"TypeError\"\n\t| (`${string}Error` & DefaultMoreOptions);\n\nexport type PossibleJavaScriptError = UnmaskType<{\n\terrorData: DOMException | Error | SyntaxError | TypeError;\n\tmessage: string;\n\tname: PossibleJavascriptErrorNames;\n}>;\n\nexport type PossibleHTTPError<TErrorData> = UnmaskType<{\n\terrorData: TErrorData;\n\tmessage: string;\n\tname: \"HTTPError\";\n}>;\n\nexport type RequestErrorContext = UnmaskType<{\n\terror: PossibleJavaScriptError;\n\toptions: CombinedCallApiExtraOptions;\n\trequest: CallApiRequestOptionsForHooks;\n\tresponse: null;\n}>;\n\nexport type ResponseErrorContext<TErrorData> = UnmaskType<{\n\terror: PossibleHTTPError<TErrorData>;\n\toptions: CombinedCallApiExtraOptions;\n\trequest: CallApiRequestOptionsForHooks;\n\tresponse: Response;\n}>;\n\nexport type ErrorContext<TErrorData> = UnmaskType<\n\t| {\n\t\t\terror: PossibleHTTPError<TErrorData>;\n\t\t\toptions: CombinedCallApiExtraOptions;\n\t\t\trequest: CallApiRequestOptionsForHooks;\n\t\t\tresponse: Response;\n\t }\n\t| {\n\t\t\terror: PossibleJavaScriptError;\n\t\t\toptions: CombinedCallApiExtraOptions;\n\t\t\trequest: CallApiRequestOptionsForHooks;\n\t\t\tresponse: null;\n\t }\n>;\n\nexport type CallApiResultSuccessVariant<TData> = {\n\tdata: TData;\n\terror: null;\n\tresponse: Response;\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: PossibleJavaScriptError;\n\t\t\tresponse: 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\tallWithoutResponse:\n\t\t| CallApiResultSuccessVariant<TComputedData>[\"data\" | \"error\"]\n\t\t| CallApiResultErrorVariant<TComputedErrorData>[\"data\" | \"error\"];\n\n\tonlyError:\n\t\t| CallApiResultSuccessVariant<TComputedData>[\"error\"]\n\t\t| CallApiResultErrorVariant<TComputedErrorData>[\"error\"];\n\n\tonlyResponse:\n\t\t| CallApiResultErrorVariant<TComputedErrorData>[\"response\"]\n\t\t| CallApiResultSuccessVariant<TComputedData>[\"response\"];\n\n\tonlyResponseWithException: CallApiResultSuccessVariant<TComputedErrorData>[\"response\"];\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 | undefined;\n\nexport type GetCallApiResult<\n\tTData,\n\tTErrorData,\n\tTResultMode extends ResultModeUnion,\n\tTThrowOnError extends boolean,\n\tTResponseType extends ResponseTypeUnion,\n> = TErrorData extends false | undefined\n\t? ResultModeMap<TData, TErrorData, TResponseType>[\"onlySuccessWithException\"]\n\t: ResultModeUnion | undefined extends TResultMode\n\t\t? TThrowOnError extends true\n\t\t\t? ResultModeMap<TData, TErrorData, TResponseType>[\"allWithException\"]\n\t\t\t: ResultModeMap<TData, TErrorData, TResponseType>[\"all\"]\n\t\t: TResultMode extends NonNullable<ResultModeUnion>\n\t\t\t? ResultModeMap<TData, TErrorData, TResponseType>[TResultMode]\n\t\t\t: never;\n","import type { BaseCallApiExtraOptions } from \"../types/common\";\nimport { defineEnum } from \"./type-helpers\";\n\nexport const fetchSpecificKeys = defineEnum([\n\t\"body\",\n\t\"integrity\",\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 RequestInit>);\n\nconst retryStatusCodesLookup = 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 defaultRetryMethods = [\"GET\", \"POST\"] satisfies BaseCallApiExtraOptions[\"retryMethods\"];\n\n// prettier-ignore\nexport const defaultRetryStatusCodes = Object.keys(retryStatusCodesLookup).map(Number) as Required<BaseCallApiExtraOptions>[\"retryStatusCodes\"];\n","import { getAuthHeader } from \"@/auth\";\nimport {\n\ttype BaseCallApiExtraOptions,\n\ttype CallApiExtraOptions,\n\ttype CallApiRequestOptions,\n\toptionsEnumToOmitFromBase,\n} from \"../types/common\";\nimport { fetchSpecificKeys } from \"./constants\";\nimport { isArray, isFunction, isPlainObject, isQueryString, isString } from \"./type-guards\";\nimport type { AnyFunction, Awaitable } from \"./type-helpers\";\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, [\n\t\t\t...fetchSpecificKeys,\n\t\t\t...optionsEnumToOmitFromBase,\n\t\t]) 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\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\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\n// export mergeAndResolve\n\nexport const mergeAndResolveHeaders = (options: {\n\tauth: CallApiExtraOptions[\"auth\"];\n\tbaseHeaders: CallApiExtraOptions[\"headers\"];\n\tbody: CallApiExtraOptions[\"body\"];\n\theaders: CallApiExtraOptions[\"headers\"];\n}) => {\n\tconst { auth, baseHeaders, body, headers } = options;\n\n\t// eslint-disable-next-line ts-eslint/prefer-nullish-coalescing -- Nullish coalescing makes no sense in this boolean context\n\tconst shouldResolveHeaders = Boolean(baseHeaders || headers || body || auth);\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\t// == - headers are provided\n\t// == - The body is an object\n\t// == - The auth option is provided\n\tif (!shouldResolveHeaders) return;\n\n\tconst headersObject: Record<string, string | undefined> = {\n\t\t...getAuthHeader(auth),\n\t\t...objectifyHeaders(baseHeaders),\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 (isPlainObject(body) || (isString(body) && body.startsWith(\"{\"))) {\n\t\theadersObject[\"Content-Type\"] = \"application/json\";\n\t\theadersObject.Accept = \"application/json\";\n\t}\n\n\treturn headersObject;\n};\n\nexport const combineHooks = <TInterceptor extends AnyFunction | Array<AnyFunction | undefined>>(\n\tbaseInterceptor: TInterceptor | undefined,\n\tinterceptor: TInterceptor | undefined\n) => {\n\tif (isArray(baseInterceptor)) {\n\t\treturn [baseInterceptor, interceptor].flat() as TInterceptor;\n\t}\n\n\treturn interceptor ?? baseInterceptor;\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\nexport const executeHooks = <TInterceptor extends Awaitable<unknown>>(...interceptors: TInterceptor[]) =>\n\tPromise.all(interceptors);\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 waitUntil = (delay: number) => {\n\tif (delay === 0) return;\n\n\tconst { promise, resolve } = PromiseWithResolvers();\n\n\tsetTimeout(resolve, delay);\n\n\treturn promise;\n};\n"]}
|
|
@@ -117,12 +117,12 @@ type InferSchemaResult<TSchema, TData> = TSchema extends StandardSchemaV1 ? Stan
|
|
|
117
117
|
|
|
118
118
|
type Params = UnmaskType<Record<string, boolean | number | string> | Array<boolean | number | string>>;
|
|
119
119
|
type Query = UnmaskType<Record<string, boolean | number | string>>;
|
|
120
|
-
type InitURL = UnmaskType<string>;
|
|
120
|
+
type InitURL = UnmaskType<string | URL>;
|
|
121
121
|
interface UrlOptions<TSchemas extends CallApiSchemas> {
|
|
122
122
|
/**
|
|
123
123
|
* URL to be used in the request.
|
|
124
124
|
*/
|
|
125
|
-
readonly initURL?:
|
|
125
|
+
readonly initURL?: string;
|
|
126
126
|
/**
|
|
127
127
|
* Parameters to be appended to the URL (i.e: /:id)
|
|
128
128
|
*/
|
|
@@ -176,6 +176,11 @@ interface RetryOptions<TErrorData> {
|
|
|
176
176
|
retryStrategy?: "exponential" | "linear";
|
|
177
177
|
}
|
|
178
178
|
|
|
179
|
+
type DefaultDataType = unknown;
|
|
180
|
+
type DefaultMoreOptions = NonNullable<unknown>;
|
|
181
|
+
type DefaultPluginArray = CallApiPlugin[];
|
|
182
|
+
type DefaultThrowOnError = boolean;
|
|
183
|
+
|
|
179
184
|
type Parser = (responseString: string) => Awaitable<Record<string, unknown>>;
|
|
180
185
|
declare const getResponseType: <TResponse>(response: Response, parser?: Parser) => {
|
|
181
186
|
arrayBuffer: () => Promise<ArrayBuffer>;
|
|
@@ -193,11 +198,10 @@ type ResponseTypeMap<TResponse> = {
|
|
|
193
198
|
type GetResponseType<TResponse, TResponseType extends ResponseTypeUnion, TComputedMap extends ResponseTypeMap<TResponse> = ResponseTypeMap<TResponse>> = undefined extends TResponseType ? TComputedMap["json"] : TResponseType extends NonNullable<ResponseTypeUnion> ? TComputedMap[TResponseType] : never;
|
|
194
199
|
|
|
195
200
|
type UnionToIntersection<TUnion> = (TUnion extends unknown ? (param: TUnion) => void : never) extends (param: infer TParam) => void ? TParam : never;
|
|
196
|
-
type DefaultPlugins = CallApiPlugin[];
|
|
197
201
|
type InferSchema<TResult> = TResult extends StandardSchemaV1 ? InferSchemaResult<TResult, NonNullable<unknown>> : TResult;
|
|
198
202
|
type InferPluginOptions<TPluginArray extends CallApiPlugin[]> = UnionToIntersection<InferSchema<ReturnType<NonNullable<TPluginArray[number]["createExtraOptions"]>>>>;
|
|
199
203
|
type PluginInitContext<TMoreOptions = DefaultMoreOptions> = WithMoreOptions<TMoreOptions> & {
|
|
200
|
-
initURL:
|
|
204
|
+
initURL: InitURL | undefined;
|
|
201
205
|
options: CombinedCallApiExtraOptions;
|
|
202
206
|
request: CallApiRequestOptionsForHooks;
|
|
203
207
|
};
|
|
@@ -237,7 +241,7 @@ interface CallApiPlugin<TData = never, TErrorData = never> {
|
|
|
237
241
|
declare const definePlugin: <TPlugin extends CallApiPlugin | AnyFunction<CallApiPlugin>>(plugin: TPlugin) => TPlugin;
|
|
238
242
|
type Plugins<TPluginArray extends CallApiPlugin[]> = TPluginArray | ((context: PluginInitContext) => TPluginArray);
|
|
239
243
|
|
|
240
|
-
declare const fetchSpecificKeys: ("body" | "
|
|
244
|
+
declare const fetchSpecificKeys: ("body" | "cache" | "credentials" | "headers" | "integrity" | "keepalive" | "method" | "mode" | "priority" | "redirect" | "referrer" | "referrerPolicy" | "signal" | "window")[];
|
|
241
245
|
declare const defaultRetryMethods: ("GET" | "POST")[];
|
|
242
246
|
declare const defaultRetryStatusCodes: Required<BaseCallApiExtraOptions>["retryStatusCodes"];
|
|
243
247
|
|
|
@@ -300,6 +304,8 @@ type MetaOption<TSchemas extends CallApiSchemas> = {
|
|
|
300
304
|
};
|
|
301
305
|
type ResultModeOption<TErrorData, TResultMode extends ResultModeUnion> = TErrorData extends false ? {
|
|
302
306
|
resultMode: "onlySuccessWithException";
|
|
307
|
+
} : TErrorData extends false | undefined ? {
|
|
308
|
+
resultMode?: "onlySuccessWithException";
|
|
303
309
|
} : undefined extends TResultMode ? {
|
|
304
310
|
resultMode?: TResultMode;
|
|
305
311
|
} : {
|
|
@@ -311,8 +317,6 @@ type CallApiRequestOptions<TSchemas extends CallApiSchemas = DefaultMoreOptions>
|
|
|
311
317
|
type CallApiRequestOptionsForHooks<TSchemas extends CallApiSchemas = DefaultMoreOptions> = Omit<CallApiRequestOptions<TSchemas>, "headers"> & {
|
|
312
318
|
headers?: Record<string, string | undefined>;
|
|
313
319
|
};
|
|
314
|
-
type DefaultDataType = unknown;
|
|
315
|
-
type DefaultMoreOptions = NonNullable<unknown>;
|
|
316
320
|
type WithMoreOptions<TMoreOptions = DefaultMoreOptions> = {
|
|
317
321
|
options: CombinedCallApiExtraOptions & Partial<TMoreOptions>;
|
|
318
322
|
};
|
|
@@ -351,7 +355,7 @@ type InterceptorsOrInterceptorArray<TData = DefaultDataType, TErrorData = Defaul
|
|
|
351
355
|
[Key in keyof Interceptors<TData, TErrorData, TMoreOptions>]: Interceptors<TData, TErrorData, TMoreOptions>[Key] | Array<Interceptors<TData, TErrorData, TMoreOptions>[Key]>;
|
|
352
356
|
};
|
|
353
357
|
type FetchImpl = UnmaskType<(input: string | Request | URL, init?: RequestInit) => Promise<Response>>;
|
|
354
|
-
type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemas extends CallApiSchemas = DefaultMoreOptions, TPluginArray extends CallApiPlugin[] =
|
|
358
|
+
type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemas extends CallApiSchemas = DefaultMoreOptions, TPluginArray extends CallApiPlugin[] = DefaultPluginArray> = {
|
|
355
359
|
/**
|
|
356
360
|
* Authorization header value.
|
|
357
361
|
*/
|
|
@@ -436,7 +440,7 @@ type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResult
|
|
|
436
440
|
* The function is passed the error object and can be used to conditionally throw the error
|
|
437
441
|
* @default false
|
|
438
442
|
*/
|
|
439
|
-
throwOnError?:
|
|
443
|
+
throwOnError?: TThrowOnError | ((context: ErrorContext<TErrorData>) => TThrowOnError);
|
|
440
444
|
/**
|
|
441
445
|
* Request timeout in milliseconds
|
|
442
446
|
*/
|
|
@@ -447,18 +451,18 @@ type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResult
|
|
|
447
451
|
validators?: CallApiValidators<TData, TErrorData>;
|
|
448
452
|
} & InterceptorsOrInterceptorArray<TData, TErrorData> & Partial<InferPluginOptions<TPluginArray>> & MetaOption<TSchemas> & RetryOptions<TErrorData> & ResultModeOption<TErrorData, TResultMode> & UrlOptions<TSchemas>;
|
|
449
453
|
declare const optionsEnumToExtendFromBase: ("plugins" | "schemas" | "validators")[];
|
|
450
|
-
type CallApiExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemas extends CallApiSchemas = DefaultMoreOptions, TPluginArray extends CallApiPlugin[] =
|
|
454
|
+
type CallApiExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemas extends CallApiSchemas = DefaultMoreOptions, TPluginArray extends CallApiPlugin[] = DefaultPluginArray> = CallApiRequestOptions<TSchemas> & ExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TSchemas, TPluginArray> & {
|
|
451
455
|
/**
|
|
452
456
|
* Options that should extend the base options.
|
|
453
457
|
*/
|
|
454
|
-
extend?: Pick<ExtraOptions<TData, TErrorData, TResultMode, TResponseType, TSchemas, TPluginArray>, (typeof optionsEnumToExtendFromBase)[number]>;
|
|
458
|
+
extend?: Pick<ExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TSchemas, TPluginArray>, (typeof optionsEnumToExtendFromBase)[number]>;
|
|
455
459
|
};
|
|
456
460
|
declare const optionsEnumToOmitFromBase: ("dedupeKey" | "extend")[];
|
|
457
|
-
type BaseCallApiExtraOptions<TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBaseSchemas extends CallApiSchemas = DefaultMoreOptions, TBasePluginArray extends CallApiPlugin[] =
|
|
461
|
+
type BaseCallApiExtraOptions<TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseThrowOnError extends boolean = DefaultThrowOnError, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBaseSchemas extends CallApiSchemas = DefaultMoreOptions, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray> = Omit<Partial<CallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBaseSchemas, TBasePluginArray>>, (typeof optionsEnumToOmitFromBase)[number]>;
|
|
458
462
|
type CombinedCallApiExtraOptions = BaseCallApiExtraOptions & CallApiExtraOptions;
|
|
459
|
-
type CallApiParameters<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemas extends CallApiSchemas = DefaultMoreOptions, TPluginArray extends CallApiPlugin[] =
|
|
460
|
-
initURL:
|
|
461
|
-
config?: CallApiExtraOptions<TData, TErrorData, TResultMode, TResponseType, TSchemas, TPluginArray>
|
|
463
|
+
type CallApiParameters<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemas extends CallApiSchemas = DefaultMoreOptions, TPluginArray extends CallApiPlugin[] = DefaultPluginArray> = [
|
|
464
|
+
initURL: InferSchemaResult<TSchemas["initURL"], InitURL>,
|
|
465
|
+
config?: CallApiExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TSchemas, TPluginArray>
|
|
462
466
|
];
|
|
463
467
|
type RequestContext = UnmaskType<{
|
|
464
468
|
options: CombinedCallApiExtraOptions;
|
|
@@ -498,6 +502,7 @@ type RequestErrorContext = UnmaskType<{
|
|
|
498
502
|
error: PossibleJavaScriptError;
|
|
499
503
|
options: CombinedCallApiExtraOptions;
|
|
500
504
|
request: CallApiRequestOptionsForHooks;
|
|
505
|
+
response: null;
|
|
501
506
|
}>;
|
|
502
507
|
type ResponseErrorContext<TErrorData> = UnmaskType<{
|
|
503
508
|
error: PossibleHTTPError<TErrorData>;
|
|
@@ -532,13 +537,15 @@ type CallApiResultErrorVariant<TErrorData> = {
|
|
|
532
537
|
};
|
|
533
538
|
type ResultModeMap<TData = DefaultDataType, TErrorData = DefaultDataType, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TComputedData = GetResponseType<TData, TResponseType>, TComputedErrorData = GetResponseType<TErrorData, TResponseType>> = UnmaskType<{
|
|
534
539
|
all: CallApiResultSuccessVariant<TComputedData> | CallApiResultErrorVariant<TComputedErrorData>;
|
|
540
|
+
allWithException: CallApiResultSuccessVariant<TComputedData>;
|
|
541
|
+
allWithoutResponse: CallApiResultSuccessVariant<TComputedData>["data" | "error"] | CallApiResultErrorVariant<TComputedErrorData>["data" | "error"];
|
|
535
542
|
onlyError: CallApiResultSuccessVariant<TComputedData>["error"] | CallApiResultErrorVariant<TComputedErrorData>["error"];
|
|
536
543
|
onlyResponse: CallApiResultErrorVariant<TComputedErrorData>["response"] | CallApiResultSuccessVariant<TComputedData>["response"];
|
|
544
|
+
onlyResponseWithException: CallApiResultSuccessVariant<TComputedErrorData>["response"];
|
|
537
545
|
onlySuccess: CallApiResultErrorVariant<TComputedErrorData>["data"] | CallApiResultSuccessVariant<TComputedData>["data"];
|
|
538
546
|
onlySuccessWithException: CallApiResultSuccessVariant<TComputedData>["data"];
|
|
539
547
|
}>;
|
|
540
548
|
type ResultModeUnion = keyof ResultModeMap | undefined;
|
|
541
|
-
type GetCallApiResult<TData, TErrorData, TResultMode extends ResultModeUnion, TResponseType extends ResponseTypeUnion
|
|
542
|
-
ResultModeUnion | undefined extends TResultMode ? TComputedMap["all"] : TResultMode extends NonNullable<ResultModeUnion> ? TComputedMap[TResultMode] : never;
|
|
549
|
+
type GetCallApiResult<TData, TErrorData, TResultMode extends ResultModeUnion, TThrowOnError extends boolean, TResponseType extends ResponseTypeUnion> = TErrorData extends false | undefined ? ResultModeMap<TData, TErrorData, TResponseType>["onlySuccessWithException"] : ResultModeUnion | undefined extends TResultMode ? TThrowOnError extends true ? ResultModeMap<TData, TErrorData, TResponseType>["allWithException"] : ResultModeMap<TData, TErrorData, TResponseType>["all"] : TResultMode extends NonNullable<ResultModeUnion> ? ResultModeMap<TData, TErrorData, TResponseType>[TResultMode] : never;
|
|
543
550
|
|
|
544
|
-
export { type BaseCallApiExtraOptions as B, type CallApiSchemas as C, type
|
|
551
|
+
export { type BaseCallApiExtraOptions as B, type CallApiSchemas as C, type DefaultPluginArray as D, type ErrorContext as E, type GetCallApiResult as G, type InferSchemaResult as I, type PluginInitContext as P, type ResultModeUnion as R, type SuccessContext as S, type ResponseTypeUnion as a, type CallApiPlugin as b, type CallApiExtraOptions as c, type DefaultDataType as d, type DefaultThrowOnError as e, type DefaultMoreOptions as f, definePlugin as g, type PossibleJavaScriptError as h, type PossibleHTTPError as i, type CallApiParameters as j, type CallApiRequestOptions as k, type CallApiRequestOptionsForHooks as l, type CallApiResultErrorVariant as m, type CallApiResultSuccessVariant as n, type CombinedCallApiExtraOptions as o, type Interceptors as p, type InterceptorsOrInterceptorArray as q, type PossibleJavascriptErrorNames as r, type Register as s, type RequestContext as t, type RequestErrorContext as u, type ResponseContext as v, type ResponseErrorContext as w, type InitURL as x, defaultRetryMethods as y, defaultRetryStatusCodes as z };
|