@zayne-labs/callapi 1.3.7 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,5 @@
1
+ import { StandardSchemaV1 } from '@standard-schema/spec';
2
+
1
3
  type ValueOrFunctionResult<TValue> = TValue | (() => TValue);
2
4
  /**
3
5
  * Bearer Or Token authentication
@@ -62,6 +64,72 @@ type CommonRequestHeaders = "Access-Control-Allow-Credentials" | "Access-Control
62
64
  type CommonAuthorizationHeaders = `${"Basic" | "Bearer" | "Token"} ${string}`;
63
65
  type CommonContentTypes = "application/epub+zip" | "application/gzip" | "application/json" | "application/ld+json" | "application/octet-stream" | "application/ogg" | "application/pdf" | "application/rtf" | "application/vnd.ms-fontobject" | "application/wasm" | "application/xhtml+xml" | "application/xml" | "application/zip" | "audio/aac" | "audio/mpeg" | "audio/ogg" | "audio/opus" | "audio/webm" | "audio/x-midi" | "font/otf" | "font/ttf" | "font/woff" | "font/woff2" | "image/avif" | "image/bmp" | "image/gif" | "image/jpeg" | "image/png" | "image/svg+xml" | "image/tiff" | "image/webp" | "image/x-icon" | "model/gltf-binary" | "model/gltf+json" | "text/calendar" | "text/css" | "text/csv" | "text/html" | "text/javascript" | "text/plain" | "video/3gpp" | "video/3gpp2" | "video/av1" | "video/mp2t" | "video/mp4" | "video/mpeg" | "video/ogg" | "video/webm" | "video/x-msvideo" | AnyString;
64
66
 
67
+ type RetryCondition<TErrorData> = (context: ErrorContext<TErrorData>) => boolean | Promise<boolean>;
68
+ interface RetryOptions<TErrorData> {
69
+ /**
70
+ * Keeps track of the number of times the request has already been retried
71
+ * @deprecated This property is used internally to track retries. Please abstain from modifying it.
72
+ */
73
+ readonly "~retryCount"?: number;
74
+ /**
75
+ * Number of allowed retry attempts on HTTP errors
76
+ * @default 0
77
+ */
78
+ retryAttempts?: number;
79
+ /**
80
+ * Callback whose return value determines if a request should be retried or not
81
+ */
82
+ retryCondition?: RetryCondition<TErrorData>;
83
+ /**
84
+ * Delay between retries in milliseconds
85
+ * @default 1000
86
+ */
87
+ retryDelay?: number;
88
+ /**
89
+ * Maximum delay in milliseconds. Only applies to exponential strategy
90
+ * @default 10000
91
+ */
92
+ retryMaxDelay?: number;
93
+ /**
94
+ * HTTP methods that are allowed to retry
95
+ * @default ["GET", "POST"]
96
+ */
97
+ retryMethods?: Array<"GET" | "POST" | AnyString>;
98
+ /**
99
+ * HTTP status codes that trigger a retry
100
+ * @default [409, 425, 429, 500, 502, 503, 504]
101
+ */
102
+ retryStatusCodes?: Array<409 | 425 | 429 | 500 | 502 | 503 | 504 | AnyNumber>;
103
+ /**
104
+ * Strategy to use when retrying
105
+ * @default "linear"
106
+ */
107
+ retryStrategy?: "exponential" | "linear";
108
+ }
109
+
110
+ interface Schemas {
111
+ /**
112
+ * The schema to use for validating the response data.
113
+ */
114
+ data?: StandardSchemaV1;
115
+ /**
116
+ * The schema to use for validating the response error data.
117
+ */
118
+ errorData?: StandardSchemaV1;
119
+ }
120
+ interface Validators<TData = unknown, TErrorData = unknown> {
121
+ /**
122
+ * Custom function to validate the response data.
123
+ */
124
+ data?: (data: unknown) => TData;
125
+ /**
126
+ * Custom function to validate the response error data, stemming from the api.
127
+ * 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.
128
+ */
129
+ errorData?: (data: unknown) => TErrorData;
130
+ }
131
+ type InferSchemaResult<TSchema extends StandardSchemaV1 | undefined, TData> = TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> : TData;
132
+
65
133
  type ToQueryStringFn = {
66
134
  (params: CallApiConfig["query"]): string | null;
67
135
  (params: Required<CallApiConfig>["query"]): string;
@@ -76,6 +144,48 @@ declare const getResponseType: <TResponse>(response: Response, parser?: Required
76
144
  text: () => Promise<TResponse>;
77
145
  };
78
146
 
147
+ type UnionToIntersection<TUnion> = (TUnion extends unknown ? (param: TUnion) => void : never) extends (param: infer TParam) => void ? TParam : never;
148
+ type InferPluginOptions<TPluginArray extends CallApiPlugin[]> = TPluginArray extends Array<infer TPlugin extends CallApiPlugin> ? TPlugin["createExtraOptions"] extends (...params: never[]) => infer TResult ? UnionToIntersection<TResult> : NonNullable<unknown> : NonNullable<unknown>;
149
+ type PluginInitContext<TMoreOptions = DefaultMoreOptions> = WithMoreOptions<TMoreOptions> & {
150
+ initURL: string;
151
+ options: CombinedCallApiExtraOptions;
152
+ request: CallApiRequestOptionsForHooks;
153
+ };
154
+ type PluginInitResult = Partial<Omit<PluginInitContext, "request"> & {
155
+ request: CallApiRequestOptions;
156
+ }>;
157
+ type CallApiPlugin = {
158
+ /**
159
+ * Defines additional options that can be passed to callApi
160
+ */
161
+ createExtraOptions?: (...params: never[]) => unknown;
162
+ /**
163
+ * A description for the plugin
164
+ */
165
+ description?: string;
166
+ /**
167
+ * Hooks / Interceptors for the plugin
168
+ */
169
+ hooks?: InterceptorsOrInterceptorArray;
170
+ /**
171
+ * A unique id for the plugin
172
+ */
173
+ id: string;
174
+ /**
175
+ * A function that will be called when the plugin is initialized. This will be called before the any of the other internal functions.
176
+ */
177
+ init?: (context: PluginInitContext) => Awaitable<PluginInitResult> | Awaitable<void>;
178
+ /**
179
+ * A name for the plugin
180
+ */
181
+ name: string;
182
+ /**
183
+ * A version for the plugin
184
+ */
185
+ version?: string;
186
+ };
187
+ declare const definePlugin: <TPlugin extends CallApiPlugin | AnyFunction<CallApiPlugin> = CallApiPlugin>(plugin: TPlugin) => TPlugin;
188
+
79
189
  declare const fetchSpecificKeys: ("headers" | "body" | "cache" | "credentials" | "integrity" | "keepalive" | "method" | "mode" | "priority" | "redirect" | "referrer" | "referrerPolicy" | "signal" | "window")[];
80
190
  declare const defaultRetryMethods: ("GET" | "POST")[];
81
191
  declare const defaultRetryStatusCodes: Required<BaseCallApiConfig>["retryStatusCodes"];
@@ -94,7 +204,7 @@ interface CallApiRequestOptions extends Pick<RequestInit, FetchSpecificKeysUnion
94
204
  * HTTP method for the request.
95
205
  * @default "GET"
96
206
  */
97
- method?: "DELETE" | "GET" | "PATCH" | "POST" | "PUT" | AnyString;
207
+ method?: "CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE" | AnyString;
98
208
  }
99
209
  interface CallApiRequestOptionsForHooks extends Omit<CallApiRequestOptions, "headers"> {
100
210
  headers?: Record<string, string | undefined>;
@@ -144,7 +254,7 @@ type FetchImpl = UnmaskType<(input: string | Request | URL, init?: RequestInit)
144
254
  type Meta = Register extends {
145
255
  meta?: infer TMeta extends Record<string, unknown>;
146
256
  } ? TMeta : never;
147
- type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TPluginArray extends CallApiPlugin[] = CallApiPlugin[]> = {
257
+ type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TPluginArray extends CallApiPlugin[] = never[], TSchemas extends Schemas = DefaultMoreOptions> = {
148
258
  /**
149
259
  * Authorization header value.
150
260
  */
@@ -241,11 +351,6 @@ type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResult
241
351
  * Query parameters to append to the URL.
242
352
  */
243
353
  query?: Record<string, boolean | number | string>;
244
- /**
245
- * Custom function to validate the response error data, stemming from the api.
246
- * 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.
247
- */
248
- responseErrorValidator?: (data: unknown) => TErrorData;
249
354
  /**
250
355
  * Custom function to parse the response string into a object.
251
356
  */
@@ -255,16 +360,13 @@ type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResult
255
360
  * @default "json"
256
361
  */
257
362
  responseType?: keyof ReturnType<typeof getResponseType>;
258
- /**
259
- * Custom function to validate the response data.
260
- */
261
- responseValidator?: (data: unknown) => TData;
262
363
  /**
263
364
  * Mode of the result, can influence how results are handled or returned.
264
365
  * Can be set to "all" | "onlySuccess" | "onlyError" | "onlyResponse".
265
366
  * @default "all"
266
367
  */
267
368
  resultMode?: TErrorData extends false ? "onlySuccessWithException" : TResultMode | undefined;
369
+ schemas?: TSchemas;
268
370
  /**
269
371
  * If true or the function returns true, throws errors instead of returning them
270
372
  * The function is passed the error object and can be used to conditionally throw the error
@@ -275,20 +377,21 @@ type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResult
275
377
  * Request timeout in milliseconds
276
378
  */
277
379
  timeout?: number;
380
+ validators?: Validators<TData, TErrorData>;
278
381
  } & InterceptorsOrInterceptorArray<TData, TErrorData> & Partial<InferPluginOptions<TPluginArray>> & RetryOptions<TErrorData>;
279
- declare const optionsEnumToExtendFromBase: "plugins"[];
280
- type CallApiExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TPluginArray extends CallApiPlugin[] = CallApiPlugin[]> = ExtraOptions<TData, TErrorData, TResultMode, TPluginArray> & {
382
+ declare const optionsEnumToExtendFromBase: ("plugins" | "schemas" | "validators")[];
383
+ type CallApiExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TPluginArray extends CallApiPlugin[] = never[], TSchemas extends Schemas = DefaultMoreOptions> = ExtraOptions<TData, TErrorData, TResultMode, TPluginArray, TSchemas> & {
281
384
  /**
282
385
  * Options that should extend the base options.
283
386
  */
284
- extend?: Pick<ExtraOptions<TData, TErrorData, TResultMode, TPluginArray>, (typeof optionsEnumToExtendFromBase)[number]>;
387
+ extend?: Pick<ExtraOptions<TData, TErrorData, TResultMode, TPluginArray, TSchemas>, (typeof optionsEnumToExtendFromBase)[number]>;
285
388
  };
286
389
  declare const optionsEnumToOmitFromBase: ("dedupeKey" | "extend")[];
287
- type BaseCallApiExtraOptions<TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBasePluginArray extends CallApiPlugin[] = CallApiPlugin[]> = Omit<CallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBasePluginArray>, (typeof optionsEnumToOmitFromBase)[number]>;
288
- type CombinedCallApiExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TPluginArray extends CallApiPlugin[] = CallApiPlugin[]> = BaseCallApiExtraOptions<TData, TErrorData, TResultMode, TPluginArray> & CallApiExtraOptions<TData, TErrorData, TResultMode, TPluginArray>;
289
- type CallApiConfig<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TPluginArray extends CallApiPlugin[] = CallApiPlugin[]> = CallApiRequestOptions & CallApiExtraOptions<TData, TErrorData, TResultMode, TPluginArray>;
290
- type BaseCallApiConfig<TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBasePluginArray extends CallApiPlugin[] = CallApiPlugin[]> = CallApiRequestOptions & BaseCallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBasePluginArray>;
291
- type CallApiParameters<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TPluginArray extends CallApiPlugin[] = CallApiPlugin[]> = [initURL: string, config?: CallApiConfig<TData, TErrorData, TResultMode, TPluginArray>];
390
+ type BaseCallApiExtraOptions<TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBasePluginArray extends CallApiPlugin[] = never[], TBaseSchemas extends Schemas = DefaultMoreOptions> = Omit<CallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBasePluginArray, TBaseSchemas>, (typeof optionsEnumToOmitFromBase)[number]>;
391
+ type CombinedCallApiExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TPluginArray extends CallApiPlugin[] = never[], TSchemas extends Schemas = DefaultMoreOptions> = BaseCallApiExtraOptions<TData, TErrorData, TResultMode, TPluginArray, TSchemas> & CallApiExtraOptions<TData, TErrorData, TResultMode, TPluginArray, TSchemas>;
392
+ type CallApiConfig<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TPluginArray extends CallApiPlugin[] = never[], TSchemas extends Schemas = DefaultMoreOptions> = CallApiRequestOptions & CallApiExtraOptions<TData, TErrorData, TResultMode, TPluginArray, TSchemas>;
393
+ type BaseCallApiConfig<TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBasePluginArray extends CallApiPlugin[] = never[], TBaseSchemas extends Schemas = DefaultMoreOptions> = CallApiRequestOptions & BaseCallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBasePluginArray, TBaseSchemas>;
394
+ type CallApiParameters<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TPluginArray extends CallApiPlugin[] = never[], TSchemas extends Schemas = DefaultMoreOptions> = [initURL: string, config?: CallApiConfig<TData, TErrorData, TResultMode, TPluginArray, TSchemas>];
292
395
  type RequestContext = UnmaskType<{
293
396
  options: CombinedCallApiExtraOptions;
294
397
  request: CallApiRequestOptionsForHooks;
@@ -312,7 +415,7 @@ type SuccessContext<TData> = UnmaskType<{
312
415
  request: CallApiRequestOptionsForHooks;
313
416
  response: Response;
314
417
  }>;
315
- type PossibleJavascriptErrorNames = "AbortError" | "Error" | "SyntaxError" | "TimeoutError" | "TypeError" | (`${string}Error` & {});
418
+ type PossibleJavascriptErrorNames = "AbortError" | "Error" | "SyntaxError" | "TimeoutError" | "TypeError" | (`${string}Error` & DefaultMoreOptions);
316
419
  type PossibleJavaScriptError = UnmaskType<{
317
420
  errorData: DOMException | Error | SyntaxError | TypeError;
318
421
  message: string;
@@ -371,89 +474,4 @@ type ResultModeUnion = {
371
474
  }[keyof ResultModeMap] | undefined;
372
475
  type GetCallApiResult<TData, TErrorData, TResultMode> = TErrorData extends false ? ResultModeMap<TData, TErrorData>["onlySuccessWithException"] : undefined extends TResultMode ? ResultModeMap<TData, TErrorData>["all"] : TResultMode extends NonNullable<ResultModeUnion> ? ResultModeMap<TData, TErrorData>[TResultMode] : never;
373
476
 
374
- type RetryCondition<TErrorData> = (context: ErrorContext<TErrorData>) => boolean | Promise<boolean>;
375
- interface RetryOptions<TErrorData> {
376
- /**
377
- * Keeps track of the number of times the request has already been retried
378
- * @deprecated This property is used internally to track retries. Please abstain from modifying it.
379
- */
380
- readonly "~retryCount"?: number;
381
- /**
382
- * Number of allowed retry attempts on HTTP errors
383
- * @default 0
384
- */
385
- retryAttempts?: number;
386
- /**
387
- * Callback whose return value determines if a request should be retried or not
388
- */
389
- retryCondition?: RetryCondition<TErrorData>;
390
- /**
391
- * Delay between retries in milliseconds
392
- * @default 1000
393
- */
394
- retryDelay?: number;
395
- /**
396
- * Maximum delay in milliseconds. Only applies to exponential strategy
397
- * @default 10000
398
- */
399
- retryMaxDelay?: number;
400
- /**
401
- * HTTP methods that are allowed to retry
402
- * @default ["GET", "POST"]
403
- */
404
- retryMethods?: Array<"GET" | "POST" | AnyString>;
405
- /**
406
- * HTTP status codes that trigger a retry
407
- * @default [409, 425, 429, 500, 502, 503, 504]
408
- */
409
- retryStatusCodes?: Array<409 | 425 | 429 | 500 | 502 | 503 | 504 | AnyNumber>;
410
- /**
411
- * Strategy to use when retrying
412
- * @default "linear"
413
- */
414
- retryStrategy?: "exponential" | "linear";
415
- }
416
-
417
- type UnionToIntersection<TUnion> = (TUnion extends unknown ? (param: TUnion) => void : never) extends (param: infer TParam) => void ? TParam : never;
418
- type InferPluginOptions<TPluginArray extends CallApiPlugin[]> = TPluginArray extends Array<infer TPlugin extends CallApiPlugin> ? TPlugin["createExtraOptions"] extends (...params: never[]) => infer TResult ? UnionToIntersection<TResult> : NonNullable<unknown> : NonNullable<unknown>;
419
- type PluginInitContext<TMoreOptions = DefaultMoreOptions> = WithMoreOptions<TMoreOptions> & {
420
- initURL: string;
421
- options: CombinedCallApiExtraOptions;
422
- request: CallApiRequestOptionsForHooks;
423
- };
424
- type PluginInitResult = Partial<Omit<PluginInitContext, "request"> & {
425
- request: CallApiRequestOptions;
426
- }>;
427
- type CallApiPlugin = {
428
- /**
429
- * Defines additional options that can be passed to callApi
430
- */
431
- createExtraOptions?: (...params: never[]) => unknown;
432
- /**
433
- * A description for the plugin
434
- */
435
- description?: string;
436
- /**
437
- * Hooks / Interceptors for the plugin
438
- */
439
- hooks?: InterceptorsOrInterceptorArray;
440
- /**
441
- * A unique id for the plugin
442
- */
443
- id: string;
444
- /**
445
- * A function that will be called when the plugin is initialized. This will be called before the any of the other internal functions.
446
- */
447
- init?: (context: PluginInitContext) => Awaitable<PluginInitResult> | Awaitable<void>;
448
- /**
449
- * A name for the plugin
450
- */
451
- name: string;
452
- /**
453
- * A version for the plugin
454
- */
455
- version?: string;
456
- };
457
- declare const definePlugin: <TPlugin extends CallApiPlugin | AnyFunction<CallApiPlugin> = CallApiPlugin>(plugin: TPlugin) => TPlugin;
458
-
459
- export { type BaseCallApiConfig as B, type CallApiPlugin as C, type DefaultDataType as D, type ErrorContext as E, type GetCallApiResult as G, type Interceptors as I, type PluginInitContext as P, type ResultModeUnion as R, type SuccessContext as S, type CallApiConfig as a, type BaseCallApiExtraOptions as b, type CallApiExtraOptions as c, definePlugin as d, type PossibleJavaScriptError as e, type PossibleHTTPError as f, type CallApiParameters as g, type CallApiRequestOptions as h, type CallApiRequestOptionsForHooks as i, type CallApiResultErrorVariant as j, type CallApiResultSuccessVariant as k, type CombinedCallApiExtraOptions as l, type InterceptorsOrInterceptorArray as m, type PossibleJavascriptErrorNames as n, type Register as o, type RequestContext as p, type RequestErrorContext as q, type ResponseContext as r, type ResponseErrorContext as s, toQueryString as t, defaultRetryMethods as u, defaultRetryStatusCodes as v };
477
+ export { type BaseCallApiConfig as B, type CallApiPlugin as C, type DefaultDataType as D, type ErrorContext as E, type GetCallApiResult as G, type InferSchemaResult as I, type PluginInitContext as P, type ResultModeUnion as R, type Schemas as S, type CallApiConfig as a, type BaseCallApiExtraOptions as b, type CallApiExtraOptions as c, definePlugin as d, type PossibleJavaScriptError as e, type PossibleHTTPError as f, type CallApiParameters as g, type CallApiRequestOptions as h, type CallApiRequestOptionsForHooks as i, type CallApiResultErrorVariant as j, type CallApiResultSuccessVariant as k, type CombinedCallApiExtraOptions as l, type Interceptors as m, type InterceptorsOrInterceptorArray as n, type PossibleJavascriptErrorNames as o, type Register as p, type RequestContext as q, type RequestErrorContext as r, type ResponseContext as s, type ResponseErrorContext as t, type SuccessContext as u, toQueryString as v, defaultRetryMethods as w, defaultRetryStatusCodes as x };
@@ -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\";\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\";\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 = any> = (...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 { BaseCallApiConfig } from \"../types\";\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 BaseCallApiConfig[\"retryMethods\"];\n\n// prettier-ignore\nexport const defaultRetryStatusCodes = Object.keys(retryStatusCodesLookup).map(Number) as Required<BaseCallApiConfig>[\"retryStatusCodes\"];\n","import { getAuthHeader } from \"@/auth\";\nimport {\n\ttype BaseCallApiExtraOptions,\n\ttype CallApiConfig,\n\ttype CallApiExtraOptions,\n\ttype CallApiRequestOptions,\n\ttype ResultModeMap,\n\toptionsEnumToOmitFromBase,\n} from \"../types\";\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: CallApiConfig[\"query\"]): string | null;\n\t(params: Required<CallApiConfig>[\"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: CallApiConfig[\"auth\"];\n\tbaseHeaders: CallApiConfig[\"headers\"];\n\tbody: CallApiConfig[\"body\"];\n\theaders: CallApiConfig[\"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 = <\n\tTInterceptor extends\n\t\t| AnyFunction<Awaitable<unknown>>\n\t\t| Array<AnyFunction<Awaitable<unknown>> | undefined>,\n>(\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 getResponseType = <TResponse>(\n\tresponse: Response,\n\tparser?: Required<CallApiExtraOptions>[\"responseParser\"]\n) => ({\n\tarrayBuffer: () => response.arrayBuffer() as Promise<TResponse>,\n\tblob: () => response.blob() as Promise<TResponse>,\n\tformData: () => response.formData() as Promise<TResponse>,\n\tjson: async () => {\n\t\tif (parser) {\n\t\t\tconst text = await response.text();\n\t\t\treturn parser(text);\n\t\t}\n\n\t\treturn response.json() as Promise<TResponse>;\n\t},\n\tstream: () => response.body,\n\ttext: () => response.text() as Promise<TResponse>,\n});\n\nexport const executeHooks = <TInterceptor extends Awaitable<unknown>>(...interceptors: TInterceptor[]) =>\n\tPromise.all(interceptors);\n\nexport const getResponseData = async <TResponse>(\n\tresponse: Response,\n\tresponseType: keyof ReturnType<typeof getResponseType>,\n\tparser: CallApiExtraOptions[\"responseParser\"],\n\tvalidator?: CallApiExtraOptions[\"responseValidator\"]\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\tconst validResponseData = validator ? validator(responseData) : responseData;\n\n\treturn validResponseData;\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 };\n\n\tif (!resultMode) {\n\t\treturn apiDetails as TCallApiResult;\n\t}\n\n\tconst resultModeMap: ResultModeMap = {\n\t\tall: apiDetails,\n\t\tonlyError: apiDetails.error,\n\t\tonlyResponse: apiDetails.response,\n\t\tonlySuccess: apiDetails.data,\n\t\tonlySuccessWithException: apiDetails.data,\n\t};\n\n\treturn resultModeMap[resultMode] as TCallApiResult;\n};\n\nconst PromiseWithResolvers = () => {\n\tlet reject!: (reason?: unknown) => void;\n\tlet resolve!: (value: unknown) => void;\n\n\tconst promise = new Promise((res, rej) => {\n\t\tresolve = res;\n\t\treject = rej;\n\t});\n\n\treturn { promise, reject, resolve };\n};\n\nexport const 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;;;AC2C9E,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\";\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\";\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 = any> = (...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 { BaseCallApiConfig } from \"../types\";\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 BaseCallApiConfig[\"retryMethods\"];\n\n// prettier-ignore\nexport const defaultRetryStatusCodes = Object.keys(retryStatusCodesLookup).map(Number) as Required<BaseCallApiConfig>[\"retryStatusCodes\"];\n","import { getAuthHeader } from \"@/auth\";\nimport { type Schemas, type Validators, standardSchemaParser } from \"@/validation\";\nimport {\n\ttype BaseCallApiExtraOptions,\n\ttype CallApiConfig,\n\ttype CallApiExtraOptions,\n\ttype CallApiRequestOptions,\n\ttype ResultModeMap,\n\toptionsEnumToOmitFromBase,\n} from \"../types\";\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: CallApiConfig[\"query\"]): string | null;\n\t(params: Required<CallApiConfig>[\"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: CallApiConfig[\"auth\"];\n\tbaseHeaders: CallApiConfig[\"headers\"];\n\tbody: CallApiConfig[\"body\"];\n\theaders: CallApiConfig[\"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 = <\n\tTInterceptor extends\n\t\t| AnyFunction<Awaitable<unknown>>\n\t\t| Array<AnyFunction<Awaitable<unknown>> | undefined>,\n>(\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 getResponseType = <TResponse>(\n\tresponse: Response,\n\tparser?: Required<CallApiExtraOptions>[\"responseParser\"]\n) => ({\n\tarrayBuffer: () => response.arrayBuffer() as Promise<TResponse>,\n\tblob: () => response.blob() as Promise<TResponse>,\n\tformData: () => response.formData() as Promise<TResponse>,\n\tjson: async () => {\n\t\tif (parser) {\n\t\t\tconst text = await response.text();\n\t\t\treturn parser(text);\n\t\t}\n\n\t\treturn response.json() as Promise<TResponse>;\n\t},\n\tstream: () => response.body,\n\ttext: () => response.text() as Promise<TResponse>,\n});\n\nexport const executeHooks = <TInterceptor extends Awaitable<unknown>>(...interceptors: TInterceptor[]) =>\n\tPromise.all(interceptors);\n\nexport const getResponseData = async <TResponse>(\n\tresponse: Response,\n\tresponseType: keyof ReturnType<typeof getResponseType>,\n\tparser: CallApiExtraOptions[\"responseParser\"],\n\tschema?: NonNullable<Schemas>[keyof NonNullable<Schemas>],\n\tvalidator?: NonNullable<Validators>[keyof NonNullable<Validators>]\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\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\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 };\n\n\tif (!resultMode) {\n\t\treturn apiDetails as TCallApiResult;\n\t}\n\n\tconst resultModeMap: ResultModeMap = {\n\t\tall: apiDetails,\n\t\tonlyError: apiDetails.error,\n\t\tonlyResponse: apiDetails.response,\n\t\tonlySuccess: apiDetails.data,\n\t\tonlySuccessWithException: apiDetails.data,\n\t};\n\n\treturn resultModeMap[resultMode] as TCallApiResult;\n};\n\nconst PromiseWithResolvers = () => {\n\tlet reject!: (reason?: unknown) => void;\n\tlet resolve!: (value: unknown) => void;\n\n\tconst promise = new Promise((res, rej) => {\n\t\tresolve = res;\n\t\treject = rej;\n\t});\n\n\treturn { promise, reject, resolve };\n};\n\nexport const 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;;;AC4C9E,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,6 +1,7 @@
1
- import { f as PossibleHTTPError, e as PossibleJavaScriptError } from '../plugins-jILLQxo1.cjs';
2
- export { u as defaultRetryMethods, v as defaultRetryStatusCodes, t as toQueryString } from '../plugins-jILLQxo1.cjs';
1
+ import { f as PossibleHTTPError, e as PossibleJavaScriptError } from '../types-CNYLI9wS.cjs';
2
+ export { w as defaultRetryMethods, x as defaultRetryStatusCodes, v as toQueryString } from '../types-CNYLI9wS.cjs';
3
3
  import { H as HTTPError } from '../error-lBRMiMeF.cjs';
4
+ import '@standard-schema/spec';
4
5
 
5
6
  type ErrorObjectUnion<TErrorData = unknown> = PossibleHTTPError<TErrorData> | PossibleJavaScriptError;
6
7
  declare const isHTTPError: <TErrorData>(error: ErrorObjectUnion<TErrorData> | null) => error is PossibleHTTPError<TErrorData>;
@@ -0,0 +1 @@
1
+ var e=e=>{const{cloneResponse:r,defaultErrorMessage:t,error:s,message:a,resultMode:i}=e;let l={data:null,error:{errorData:s,message:a??s.message,name:s.name},response:null};if(o(s)){const{errorData:e,message:o=t,name:n,response:a}=s;l={data:null,error:{errorData:e,message:o,name:n},response:r?a.clone():a}}const c={all:l,onlyError:l.error,onlyResponse:l.response,onlySuccess:l.data,onlySuccessWithException:l.data};return{errorVariantDetails:l,getErrorResult:e=>{const r=c[i??"all"];return n(e)?{...r,...e}:r}}},r=class extends Error{errorData;isHTTPError=!0;name="HTTPError";response;constructor(e,r){const{defaultErrorMessage:t,errorData:o,response:s}=e;super(o?.message??t,r),this.errorData=o,this.response=s,Error.captureStackTrace(this,this.constructor)}},t=e=>a(e)&&"HTTPError"===e.name,o=e=>e instanceof r||a(e)&&"HTTPError"===e.name&&!0===e.isHTTPError,s=e=>Array.isArray(e),n=e=>"object"==typeof e&&null!==e,a=e=>{if(!n(e))return!1;const r=Object.getPrototypeOf(e);return(null==r||r===Object.prototype||null===Object.getPrototypeOf(r))&&!(Symbol.toStringTag in e)},i=e=>"function"==typeof e,l=e=>"string"==typeof e,c=e=>i(e)?e():e,u=e=>{if(void 0!==e){if(l(e)||null===e)return{Authorization:`Bearer ${e}`};switch(e.type){case"Basic":{const r=c(e.username),t=c(e.password);if(void 0===r||void 0===t)return;return{Authorization:`Basic ${globalThis.btoa(`${r}:${t}`)}`}}case"Custom":{const r=c(e.value);if(void 0===r)return;return{Authorization:`${c(e.prefix)} ${r}`}}default:{const r=c(e.bearer),t=c(e.token);return"token"in e&&void 0!==t?{Authorization:`Token ${t}`}:void 0!==r&&{Authorization:`Bearer ${r}`}}}}},d=e=>({schemas:e.schemas?{...e.schemas,...e.extend?.schemas}:void 0,validators:e.validators?{...e.validators,...e.extend?.validators}:void 0}),p=["extend","dedupeKey"],f=["body","integrity","method","headers","signal","cache","redirect","window","credentials","keepalive","referrer","priority","mode","referrerPolicy"],y={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"],h=Object.keys(y).map(Number),b=(e,r)=>{const t={},o=new Set(r);for(const[r,s]of Object.entries(e))o.has(r)||(t[r]=s);return t},T=(e,r)=>{const t={},o=new Set(r);for(const[r,s]of Object.entries(e))o.has(r)&&(t[r]=s);return t},v=e=>[T(e,f),b(e,[...f,...p])],w=e=>[T(e,f),b(e,f)],g=e=>!e||a(e)?e:Object.fromEntries(e),E=e=>e?new URLSearchParams(e).toString():(console.error("toQueryString:","No query params provided!"),null),S=e=>{const{auth:r,baseHeaders:t,body:o,headers:s}=e;if(!Boolean(t||s||o||r))return;const n={...u(r),...g(t),...g(s)};return l(i=o)&&i.includes("=")?(n["Content-Type"]="application/x-www-form-urlencoded",n):((a(o)||l(o)&&o.startsWith("{"))&&(n["Content-Type"]="application/json",n.Accept="application/json"),n);var i},j=(e,r)=>s(e)?[e,r].flat():r??e,O=e=>{if(e)return e;if("undefined"!=typeof globalThis&&i(globalThis.fetch))return globalThis.fetch;throw new Error("No fetch implementation found")},x=(...e)=>Promise.all(e),P=async(e,r,t,o,s)=>{const n=((e,r)=>({arrayBuffer:()=>e.arrayBuffer(),blob:()=>e.blob(),formData:()=>e.formData(),json:async()=>{if(r){const t=await e.text();return r(t)}return e.json()},stream:()=>e.body,text:()=>e.text()}))(e,t);if(!Object.hasOwn(n,r))throw new Error(`Invalid response type: ${r}`);const a=await n[r](),i=s?s(a):a,l=o?await(async(e,r)=>{const t=await e["~standard"].validate(r);if(t.issues)throw new Error(JSON.stringify(t.issues,null,2));return t.value})(o,i):i;return l},D=e=>{const{data:r,response:t,resultMode:o}=e,s={data:r,error:null,response:t};if(!o)return s;return{all:s,onlyError:s.error,onlyResponse:s.response,onlySuccess:s.data,onlySuccessWithException:s.data}[o]},$=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,j as combineHooks,d as createExtensibleSchemasAndValidators,m as defaultRetryMethods,h as defaultRetryStatusCodes,x as executeHooks,O as getFetchImpl,P as getResponseData,s as isArray,i as isFunction,t as isHTTPError,o as isHTTPErrorInstance,a as isPlainObject,l as isString,S as mergeAndResolveHeaders,e as resolveErrorResult,D as resolveSuccessResult,v as splitBaseConfig,w as splitConfig,E as toQueryString,$ as waitUntil};//# sourceMappingURL=chunk-KABMV5OF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/error.ts","../../src/utils/type-guards.ts","../../src/auth.ts","../../src/validation.ts","../../src/utils/type-helpers.ts","../../src/types.ts","../../src/utils/constants.ts","../../src/utils/common.ts"],"names":[],"mappings":";AAgBa,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,mBAA0D,GAAA;AAAA,IAC7D,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,IAAA,mBAAA,CAAoB,KAAK,CAAG,EAAA;AAC/B,IAAA,MAAM,EAAE,SAAW,EAAA,OAAA,GAAU,mBAAqB,EAAA,IAAA,EAAM,UAAa,GAAA,KAAA;AAErE,IAAsB,mBAAA,GAAA;AAAA,MACrB,IAAM,EAAA,IAAA;AAAA,MACN,KAAO,EAAA;AAAA,QACN,SAAA;AAAA,QACA,OAAA;AAAA,QACA;AAAA,OAC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AAc,UAAU,CAAA;AAChC;AAEA,IAAM,uBAAuB,MAAM;AAClC,EAAI,IAAA,MAAA;AACJ,EAAI,IAAA,OAAA;AAEJ,EAAA,MAAM,OAAU,GAAA,IAAI,OAAQ,CAAA,CAAC,KAAK,GAAQ,KAAA;AACzC,IAAU,OAAA,GAAA,GAAA;AACV,IAAS,MAAA,GAAA,GAAA;AAAA,GACT,CAAA;AAED,EAAO,OAAA,EAAE,OAAS,EAAA,MAAA,EAAQ,OAAQ,EAAA;AACnC,CAAA;AAEa,IAAA,SAAA,GAAY,CAAC,KAAkB,KAAA;AAC3C,EAAA,IAAI,UAAU,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-KABMV5OF.js","sourcesContent":["import type {\n\tCallApiExtraOptions,\n\tCallApiResultErrorVariant,\n\tPossibleJavascriptErrorNames,\n\tResultModeMap,\n} from \"./types\";\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\";\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","/* eslint-disable perfectionist/sort-object-types -- Avoid Sorting for now */\n\nimport type { ExtraOptions } from \"./types\";\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","/* 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 { CombinedCallApiExtraOptions } from \"./types\";\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));\n\t}\n\n\treturn result.value;\n};\n\nexport interface Schemas {\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\nexport interface Validators<TData = unknown, TErrorData = unknown> {\n\t/**\n\t * Custom function to validate the response data.\n\t */\n\tdata?: (data: 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?: (data: unknown) => TErrorData;\n}\n\nexport type InferSchemaResult<\n\tTSchema extends StandardSchemaV1 | undefined,\n\tTData,\n> = TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> : TData;\n\nexport const createExtensibleSchemasAndValidators = (options: CombinedCallApiExtraOptions) => {\n\tconst schemas = options.schemas\n\t\t? ({ ...options.schemas, ...options.extend?.schemas } as Schemas)\n\t\t: undefined;\n\n\tconst validators = options.validators\n\t\t? { ...options.validators, ...options.extend?.validators }\n\t\t: undefined;\n\n\treturn { schemas, validators };\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 = any> = (...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, PluginInitContext } from \"./plugins\";\nimport type { RetryOptions } from \"./retry\";\nimport type { getResponseType } from \"./utils/common\";\nimport type { fetchSpecificKeys } from \"./utils/constants\";\nimport {\n\ttype AnyString,\n\ttype Awaitable,\n\ttype CommonAuthorizationHeaders,\n\ttype CommonContentTypes,\n\ttype CommonRequestHeaders,\n\ttype UnmaskType,\n\tdefineEnum,\n} from \"./utils/type-helpers\";\nimport type { Schemas, Validators } from \"./validation\";\n\ntype FetchSpecificKeysUnion = Exclude<(typeof fetchSpecificKeys)[number], \"body\" | \"headers\" | \"method\">;\n\nexport interface CallApiRequestOptions extends Pick<RequestInit, FetchSpecificKeysUnion> {\n\t/**\n\t * Optional body of the request, can be a object or any other supported body type.\n\t */\n\tbody?: Record<string, unknown> | RequestInit[\"body\"];\n\n\t/**\n\t * Headers to be used in the request.\n\t */\n\theaders?:\n\t\t| Record<\"Authorization\", CommonAuthorizationHeaders>\n\t\t| Record<\"Content-Type\", CommonContentTypes>\n\t\t| Record<CommonRequestHeaders, string | undefined>\n\t\t| Record<string, string | undefined>\n\t\t| RequestInit[\"headers\"];\n\n\t/**\n\t * HTTP method for the request.\n\t * @default \"GET\"\n\t */\n\tmethod?:\n\t\t| \"CONNECT\"\n\t\t| \"DELETE\"\n\t\t| \"GET\"\n\t\t| \"HEAD\"\n\t\t| \"OPTIONS\"\n\t\t| \"PATCH\"\n\t\t| \"POST\"\n\t\t| \"PUT\"\n\t\t| \"TRACE\"\n\t\t| AnyString;\n}\n\nexport interface CallApiRequestOptionsForHooks extends Omit<CallApiRequestOptions, \"headers\"> {\n\theaders?: Record<string, string | undefined>;\n}\n\n// eslint-disable-next-line ts-eslint/no-empty-object-type -- This needs to be empty to allow users to register their own meta\nexport interface Register {\n\t// == meta: Meta\n}\nexport type DefaultDataType = unknown;\n\nexport type DefaultMoreOptions = NonNullable<unknown>;\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 Meta = Register extends { meta?: infer TMeta extends Record<string, unknown> } ? TMeta : never;\n\n// Helper type to extract plugin options\n\n// Helper type to merge all plugin options into a single type\n\nexport type ExtraOptions<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTPluginArray extends CallApiPlugin[] = never[],\n\tTSchemas extends Schemas = DefaultMoreOptions,\n> = {\n\t/**\n\t * Authorization header value.\n\t */\n\tauth?: string | Auth | null;\n\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 * URL to be used in the request.\n\t */\n\treadonly initURL?: 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 optional field you can fill with additional information,\n\t * to associate with the request, typically used for logging or tracing.\n\t *\n\t * - A good use case for this, would be to use the info to handle specific cases in any of the shared interceptors.\n\t *\n\t * @example\n\t * ```ts\n\t * const callMainApi = callApi.create({\n\t * \tbaseURL: \"https://main-api.com\",\n\t * \tonResponseError: ({ response, options }) => {\n\t * \t\tif (options.meta?.userId) {\n\t * \t\t\tconsole.error(`User ${options.meta.userId} made an error`);\n\t * \t\t}\n\t * \t},\n\t * });\n\t *\n\t * const response = await callMainApi({\n\t * \turl: \"https://example.com/api/data\",\n\t * \tmeta: { userId: \"123\" },\n\t * });\n\t * ```\n\t */\n\tmeta?: Meta;\n\n\t/**\n\t * Params to be appended to the URL (i.e: /:id)\n\t */\n\t// eslint-disable-next-line perfectionist/sort-union-types -- I need the Record to be first\n\tparams?: Record<string, boolean | number | string> | Array<boolean | number | string>;\n\n\t/**\n\t * An array of CallApi plugins. It allows you to extend the behavior of the library.\n\t */\n\tplugins?: TPluginArray | ((context: PluginInitContext) => TPluginArray);\n\n\t/**\n\t * Query parameters to append to the URL.\n\t */\n\tquery?: Record<string, boolean | number | string>;\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?: keyof ReturnType<typeof getResponseType>;\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?: TErrorData extends false ? \"onlySuccessWithException\" : TResultMode | undefined;\n\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?: boolean | ((context: ErrorContext<TErrorData>) => boolean);\n\n\t/**\n\t * Request timeout in milliseconds\n\t */\n\ttimeout?: number;\n\n\tvalidators?: Validators<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\tRetryOptions<TErrorData>;\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\tTPluginArray extends CallApiPlugin[] = never[],\n\tTSchemas extends Schemas = DefaultMoreOptions,\n> = ExtraOptions<TData, TErrorData, TResultMode, TPluginArray, TSchemas> & {\n\t/**\n\t * Options that should extend the base options.\n\t */\n\textend?: Pick<\n\t\tExtraOptions<TData, TErrorData, TResultMode, TPluginArray, TSchemas>,\n\t\t(typeof optionsEnumToExtendFromBase)[number]\n\t>;\n};\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\tTBasePluginArray extends CallApiPlugin[] = never[],\n\tTBaseSchemas extends Schemas = DefaultMoreOptions,\n> = Omit<\n\tCallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBasePluginArray, TBaseSchemas>,\n\t(typeof optionsEnumToOmitFromBase)[number]\n>;\n\nexport type CombinedCallApiExtraOptions<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTPluginArray extends CallApiPlugin[] = never[],\n\tTSchemas extends Schemas = DefaultMoreOptions,\n> = BaseCallApiExtraOptions<TData, TErrorData, TResultMode, TPluginArray, TSchemas> &\n\tCallApiExtraOptions<TData, TErrorData, TResultMode, TPluginArray, TSchemas>;\n\nexport type CallApiConfig<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTPluginArray extends CallApiPlugin[] = never[],\n\tTSchemas extends Schemas = DefaultMoreOptions,\n> = CallApiRequestOptions &\n\t// eslint-disable-next-line perfectionist/sort-intersection-types -- Allow request options to be first due to docs\n\tCallApiExtraOptions<TData, TErrorData, TResultMode, TPluginArray, TSchemas>;\n\nexport type BaseCallApiConfig<\n\tTBaseData = DefaultDataType,\n\tTBaseErrorData = DefaultDataType,\n\tTBaseResultMode extends ResultModeUnion = ResultModeUnion,\n\tTBasePluginArray extends CallApiPlugin[] = never[],\n\tTBaseSchemas extends Schemas = DefaultMoreOptions,\n> = CallApiRequestOptions &\n\t// eslint-disable-next-line perfectionist/sort-intersection-types -- Allow request options to be first due to docs\n\tBaseCallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBasePluginArray, TBaseSchemas>;\n\nexport type CallApiParameters<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTPluginArray extends CallApiPlugin[] = never[],\n\tTSchemas extends Schemas = DefaultMoreOptions,\n> = [initURL: string, config?: CallApiConfig<TData, TErrorData, TResultMode, TPluginArray, TSchemas>];\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}>;\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<TData = DefaultDataType, TErrorData = DefaultDataType> = {\n\t// eslint-disable-next-line perfectionist/sort-union-types -- I need the first one to be first\n\tall: CallApiResultSuccessVariant<TData> | CallApiResultErrorVariant<TErrorData>;\n\tonlyError: CallApiResultErrorVariant<TErrorData>[\"error\"] | CallApiResultSuccessVariant<TData>[\"error\"];\n\tonlyResponse:\n\t\t| CallApiResultErrorVariant<TErrorData>[\"response\"]\n\t\t| CallApiResultSuccessVariant<TData>[\"response\"];\n\tonlySuccess: CallApiResultErrorVariant<TErrorData>[\"data\"] | CallApiResultSuccessVariant<TData>[\"data\"];\n\tonlySuccessWithException: CallApiResultSuccessVariant<TData>[\"data\"];\n};\n\nexport type ResultModeUnion = { [Key in keyof ResultModeMap]: Key }[keyof ResultModeMap] | undefined;\n\nexport type GetCallApiResult<TData, TErrorData, TResultMode> = TErrorData extends false\n\t? ResultModeMap<TData, TErrorData>[\"onlySuccessWithException\"]\n\t: undefined extends TResultMode\n\t\t? ResultModeMap<TData, TErrorData>[\"all\"]\n\t\t: TResultMode extends NonNullable<ResultModeUnion>\n\t\t\t? ResultModeMap<TData, TErrorData>[TResultMode]\n\t\t\t: never;\n","import type { BaseCallApiConfig } from \"../types\";\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 BaseCallApiConfig[\"retryMethods\"];\n\n// prettier-ignore\nexport const defaultRetryStatusCodes = Object.keys(retryStatusCodesLookup).map(Number) as Required<BaseCallApiConfig>[\"retryStatusCodes\"];\n","import { getAuthHeader } from \"@/auth\";\nimport { type Schemas, type Validators, standardSchemaParser } from \"@/validation\";\nimport {\n\ttype BaseCallApiExtraOptions,\n\ttype CallApiConfig,\n\ttype CallApiExtraOptions,\n\ttype CallApiRequestOptions,\n\ttype ResultModeMap,\n\toptionsEnumToOmitFromBase,\n} from \"../types\";\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: CallApiConfig[\"query\"]): string | null;\n\t(params: Required<CallApiConfig>[\"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: CallApiConfig[\"auth\"];\n\tbaseHeaders: CallApiConfig[\"headers\"];\n\tbody: CallApiConfig[\"body\"];\n\theaders: CallApiConfig[\"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 = <\n\tTInterceptor extends\n\t\t| AnyFunction<Awaitable<unknown>>\n\t\t| Array<AnyFunction<Awaitable<unknown>> | undefined>,\n>(\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 getResponseType = <TResponse>(\n\tresponse: Response,\n\tparser?: Required<CallApiExtraOptions>[\"responseParser\"]\n) => ({\n\tarrayBuffer: () => response.arrayBuffer() as Promise<TResponse>,\n\tblob: () => response.blob() as Promise<TResponse>,\n\tformData: () => response.formData() as Promise<TResponse>,\n\tjson: async () => {\n\t\tif (parser) {\n\t\t\tconst text = await response.text();\n\t\t\treturn parser(text);\n\t\t}\n\n\t\treturn response.json() as Promise<TResponse>;\n\t},\n\tstream: () => response.body,\n\ttext: () => response.text() as Promise<TResponse>,\n});\n\nexport const executeHooks = <TInterceptor extends Awaitable<unknown>>(...interceptors: TInterceptor[]) =>\n\tPromise.all(interceptors);\n\nexport const getResponseData = async <TResponse>(\n\tresponse: Response,\n\tresponseType: keyof ReturnType<typeof getResponseType>,\n\tparser: CallApiExtraOptions[\"responseParser\"],\n\tschema?: NonNullable<Schemas>[keyof NonNullable<Schemas>],\n\tvalidator?: NonNullable<Validators>[keyof NonNullable<Validators>]\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\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\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 };\n\n\tif (!resultMode) {\n\t\treturn apiDetails as TCallApiResult;\n\t}\n\n\tconst resultModeMap: ResultModeMap = {\n\t\tall: apiDetails,\n\t\tonlyError: apiDetails.error,\n\t\tonlyResponse: apiDetails.response,\n\t\tonlySuccess: apiDetails.data,\n\t\tonlySuccessWithException: apiDetails.data,\n\t};\n\n\treturn resultModeMap[resultMode] as TCallApiResult;\n};\n\nconst PromiseWithResolvers = () => {\n\tlet reject!: (reason?: unknown) => void;\n\tlet resolve!: (value: unknown) => void;\n\n\tconst promise = new Promise((res, rej) => {\n\t\tresolve = res;\n\t\treject = rej;\n\t});\n\n\treturn { promise, reject, resolve };\n};\n\nexport const 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"]}
@@ -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,createExtensibleSchemasAndValidators as u,getResponseData as l,HTTPError as d,resolveSuccessResult as c,resolveErrorResult as p,waitUntil as y,isFunction as f,isHTTPErrorInstance as g,isString as h,isArray as m,toQueryString as w,getFetchImpl as R}from"./chunk-KABMV5OF.js";var q=e=>e,E=(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))},S={onError:new Set,onRequest:new Set,onRequestError:new Set,onResponse:new Set,onResponseError:new Set,onRetry:new Set,onSuccess:new Set},b=async e=>{const{initURL:t,options:r,request:o}=e,n=structuredClone(S),a=()=>{for(const e of Object.keys(S)){const t=r[e];n[e].add(t)}},i=e=>{for(const t of Object.keys(S)){const r=e[t];n[t].add(r)}};"mainHooksBeforePlugins"===r.mergedHooksExecutionOrder&&a();const u=e=>e?f(e)?e({initURL:t,options:r,request:o}):e:[],l=[...u(r.plugins),...u(r.extend?.plugins)];let d=t,c=r,p=o;const y=async e=>{if(!e)return;const n=await e({initURL:t,options:r,request:o});s(n)&&(h(n.initURL)&&(d=n.initURL),s(n.request)&&(p=n.request),s(n.options)&&(c=n.options))};for(const e of l)await y(e.init),e.hooks&&i(e.hooks);r.mergedHooksExecutionOrder&&"mainHooksAfterPlugins"!==r.mergedHooksExecutionOrder||a();const g={};for(const[e,t]of Object.entries(n)){const o=[...t].flat(),s=E(o,r.mergedHooksExecutionMode);g[e]=s}return{resolvedHooks:g,resolvedOptions:c,resolvedRequestOptions:p,url:d}},D=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 y(.1);const i=a?.get(n);return{handleRequestCancelDedupeStrategy:()=>{if(i&&"cancel"===o.dedupeStrategy){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");i.controller.abort(t)}},handleRequestDeferDedupeStrategy:()=>{const e=R(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=(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}}},O=(e,t,r)=>{const o=((e,t)=>{if(!t)return e;let r=e;if(m(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)},k=(...e)=>AbortSignal.any(e.filter(Boolean)),$=e=>AbortSignal.timeout(e),C=h=>{const[m,w]=e(h??{}),R=new Map,q=async(...e)=>{const[h,E={}]=e,[C,x]=t(E),A={};for(const e of Object.keys(S)){const t=r(w[e],x[e]);A[e]=t}const H={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",...w,...x,...A},v=C.body??m.body,L={body:s(v)?H.bodySerializer(v):v,method:"GET",...m,...C,headers:o({auth:H.auth,baseHeaders:m.headers,body:v,headers:C.headers}),signal:C.signal??m.signal},{resolvedHooks:U,resolvedOptions:P,resolvedRequestOptions:j,url:F}=await b({initURL:h,options:H,request:L}),T=`${P.baseURL}${O(F,P.params,P.query)}`,K={...P,...U,fullURL:T,initURL:h},B=new AbortController,I=null!=K.timeout?$(K.timeout):null,z=k(j.signal,I,B.signal),J={...j,signal:z},{handleRequestCancelDedupeStrategy:N,handleRequestDeferDedupeStrategy:V,removeDedupeKeyFromCache:W}=await D({$RequestInfoCache:R,newFetchController:B,options:K,request:J});N();try{await i(K.onRequest({options:K,request:J})),J.headers=o({auth:K.auth,baseHeaders:m.headers,body:v,headers:J.headers});const e=await V(),t="defer"===K.dedupeStrategy||K.cloneResponse,{schemas:r,validators:s}=u(K);if(!e.ok){const o=await l(t?e.clone():e,K.responseType,K.responseParser,r?.errorData,s?.errorData);throw new d({defaultErrorMessage:K.defaultErrorMessage,errorData:o,response:e})}const n={data:await l(t?e.clone():e,K.responseType,K.responseParser,r?.data,s?.data),options:K,request:J,response:K.cloneResponse?e.clone():e};return await i(K.onSuccess(n),K.onResponse({...n,error:null})),await c({data:n.data,response:n.response,resultMode:K.resultMode})}catch(e){const{errorVariantDetails:t,getErrorResult:r}=p({cloneResponse:K.cloneResponse,defaultErrorMessage:K.defaultErrorMessage,error:e,resultMode:K.resultMode}),o={error:t.error,options:K,request:J},s={...o,response:t.response},{getDelay:n,shouldAttemptRetry:a}=M(K,s);if(!z.aborted&&await a()){await i(K.onRetry(s));const e=n();await y(e);const t={...E,"~retryCount":(K["~retryCount"]??0)+1};return await q(h,t)}const u=f(K.throwOnError)?K.throwOnError(s):K.throwOnError,l=()=>{if(u)throw t.error};if(g(e))return await i(K.onResponseError(s),K.onError(s),K.onResponse({...s,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(s)),l(),r()}finally{W()}};return q.create=C,q},x=C();export{x as callApi,k as createCombinedSignal,D as createDedupeStrategy,C as createFetchClient,M as createRetryStrategy,$ as createTimeoutSignal,q as definePlugin,S as hooksEnum,b as initializePlugins,O as mergeUrlWithParamsAndQuery};//# sourceMappingURL=chunk-UMFL27YA.js.map