@zayne-labs/callapi 1.6.11 → 1.6.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,551 @@
1
+ import { StandardSchemaV1 } from '@standard-schema/spec';
2
+
3
+ type ValueOrFunctionResult<TValue> = TValue | (() => TValue);
4
+ /**
5
+ * Bearer Or Token authentication
6
+ *
7
+ * The value of `bearer` will be added to a header as
8
+ * `auth: Bearer some-auth-token`,
9
+ *
10
+ * The value of `token` will be added to a header as
11
+ * `auth: Token some-auth-token`,
12
+ */
13
+ type BearerOrTokenAuth = {
14
+ type?: "Bearer";
15
+ bearer?: ValueOrFunctionResult<string | null>;
16
+ token?: never;
17
+ } | {
18
+ type?: "Token";
19
+ bearer?: never;
20
+ token?: ValueOrFunctionResult<string | null>;
21
+ };
22
+ /**
23
+ * Basic auth
24
+ */
25
+ type BasicAuth = {
26
+ type: "Basic";
27
+ username: ValueOrFunctionResult<string | null | undefined>;
28
+ password: ValueOrFunctionResult<string | null | undefined>;
29
+ };
30
+ /**
31
+ * Custom auth
32
+ *
33
+ * @param prefix - prefix of the header
34
+ * @param authValue - value of the header
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * {
39
+ * type: "Custom",
40
+ * prefix: "Token",
41
+ * authValue: "token"
42
+ * }
43
+ * ```
44
+ */
45
+ type CustomAuth = {
46
+ type: "Custom";
47
+ prefix: ValueOrFunctionResult<string | null | undefined>;
48
+ value: ValueOrFunctionResult<string | null | undefined>;
49
+ };
50
+ type Auth = BearerOrTokenAuth | BasicAuth | CustomAuth;
51
+
52
+ type AnyString = string & {
53
+ z_placeholder?: never;
54
+ };
55
+ type AnyNumber = number & {
56
+ z_placeholder?: never;
57
+ };
58
+ type AnyFunction<TResult = unknown> = (...args: any) => TResult;
59
+ type UnmaskType<TValue> = {
60
+ _: TValue;
61
+ }["_"];
62
+ type Awaitable<TValue> = Promise<TValue> | TValue;
63
+ type CommonRequestHeaders = "Access-Control-Allow-Credentials" | "Access-Control-Allow-Headers" | "Access-Control-Allow-Methods" | "Access-Control-Allow-Origin" | "Access-Control-Expose-Headers" | "Access-Control-Max-Age" | "Age" | "Allow" | "Cache-Control" | "Clear-Site-Data" | "Content-Disposition" | "Content-Encoding" | "Content-Language" | "Content-Length" | "Content-Location" | "Content-Range" | "Content-Security-Policy-Report-Only" | "Content-Security-Policy" | "Cookie" | "Cross-Origin-Embedder-Policy" | "Cross-Origin-Opener-Policy" | "Cross-Origin-Resource-Policy" | "Date" | "ETag" | "Expires" | "Last-Modified" | "Location" | "Permissions-Policy" | "Pragma" | "Retry-After" | "Save-Data" | "Sec-CH-Prefers-Color-Scheme" | "Sec-CH-Prefers-Reduced-Motion" | "Sec-CH-UA-Arch" | "Sec-CH-UA-Bitness" | "Sec-CH-UA-Form-Factor" | "Sec-CH-UA-Full-Version-List" | "Sec-CH-UA-Full-Version" | "Sec-CH-UA-Mobile" | "Sec-CH-UA-Model" | "Sec-CH-UA-Platform-Version" | "Sec-CH-UA-Platform" | "Sec-CH-UA-WoW64" | "Sec-CH-UA" | "Sec-Fetch-Dest" | "Sec-Fetch-Mode" | "Sec-Fetch-Site" | "Sec-Fetch-User" | "Sec-GPC" | "Server-Timing" | "Server" | "Service-Worker-Navigation-Preload" | "Set-Cookie" | "Strict-Transport-Security" | "Timing-Allow-Origin" | "Trailer" | "Transfer-Encoding" | "Upgrade" | "Vary" | "Warning" | "WWW-Authenticate" | "X-Content-Type-Options" | "X-DNS-Prefetch-Control" | "X-Frame-Options" | "X-Permitted-Cross-Domain-Policies" | "X-Powered-By" | "X-Robots-Tag" | "X-XSS-Protection" | AnyString;
64
+ type CommonAuthorizationHeaders = `${"Basic" | "Bearer" | "Token"} ${string}`;
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;
66
+
67
+ interface CallApiSchemas {
68
+ /**
69
+ * The schema to use for validating the request body.
70
+ */
71
+ body?: StandardSchemaV1<Body>;
72
+ /**
73
+ * The schema to use for validating the response data.
74
+ */
75
+ data?: StandardSchemaV1;
76
+ /**
77
+ * The schema to use for validating the response error data.
78
+ */
79
+ errorData?: StandardSchemaV1;
80
+ /**
81
+ * The schema to use for validating the request headers.
82
+ */
83
+ headers?: StandardSchemaV1<Headers>;
84
+ /**
85
+ * The schema to use for validating the request url.
86
+ */
87
+ initURL?: StandardSchemaV1<InitURL>;
88
+ /**
89
+ * The schema to use for validating the meta option.
90
+ */
91
+ meta?: StandardSchemaV1<GlobalMeta>;
92
+ /**
93
+ * The schema to use for validating the request method.
94
+ */
95
+ method?: StandardSchemaV1<Method>;
96
+ /**
97
+ * The schema to use for validating the request url parameter.
98
+ */
99
+ params?: StandardSchemaV1<Params>;
100
+ /**
101
+ * The schema to use for validating the request url querys.
102
+ */
103
+ query?: StandardSchemaV1<Query>;
104
+ }
105
+ interface CallApiValidators<TData = unknown, TErrorData = unknown> {
106
+ /**
107
+ * Custom function to validate the response data.
108
+ */
109
+ data?: (value: unknown) => TData;
110
+ /**
111
+ * Custom function to validate the response error data, stemming from the api.
112
+ * 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.
113
+ */
114
+ errorData?: (value: unknown) => TErrorData;
115
+ }
116
+ type InferSchemaResult<TSchema, TData> = TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> : TData;
117
+
118
+ type Params = UnmaskType<Record<string, boolean | number | string> | Array<boolean | number | string>>;
119
+ type Query = UnmaskType<Record<string, boolean | number | string>>;
120
+ type InitURL = UnmaskType<string | URL>;
121
+ interface UrlOptions<TSchemas extends CallApiSchemas> {
122
+ /**
123
+ * URL to be used in the request.
124
+ */
125
+ readonly initURL?: string;
126
+ /**
127
+ * Parameters to be appended to the URL (i.e: /:id)
128
+ */
129
+ params?: InferSchemaResult<TSchemas["params"], Params>;
130
+ /**
131
+ * Query parameters to append to the URL.
132
+ */
133
+ query?: InferSchemaResult<TSchemas["query"], Query>;
134
+ }
135
+
136
+ type RetryCondition<TErrorData> = (context: ErrorContext<TErrorData>) => boolean | Promise<boolean>;
137
+ interface RetryOptions<TErrorData> {
138
+ /**
139
+ * Keeps track of the number of times the request has already been retried
140
+ * @deprecated This property is used internally to track retries. Please abstain from modifying it.
141
+ */
142
+ readonly "~retryCount"?: number;
143
+ /**
144
+ * Number of allowed retry attempts on HTTP errors
145
+ * @default 0
146
+ */
147
+ retryAttempts?: number;
148
+ /**
149
+ * Callback whose return value determines if a request should be retried or not
150
+ */
151
+ retryCondition?: RetryCondition<TErrorData>;
152
+ /**
153
+ * Delay between retries in milliseconds
154
+ * @default 1000
155
+ */
156
+ retryDelay?: number;
157
+ /**
158
+ * Maximum delay in milliseconds. Only applies to exponential strategy
159
+ * @default 10000
160
+ */
161
+ retryMaxDelay?: number;
162
+ /**
163
+ * HTTP methods that are allowed to retry
164
+ * @default ["GET", "POST"]
165
+ */
166
+ retryMethods?: Method[];
167
+ /**
168
+ * HTTP status codes that trigger a retry
169
+ * @default [409, 425, 429, 500, 502, 503, 504]
170
+ */
171
+ retryStatusCodes?: Array<409 | 425 | 429 | 500 | 502 | 503 | 504 | AnyNumber>;
172
+ /**
173
+ * Strategy to use when retrying
174
+ * @default "linear"
175
+ */
176
+ retryStrategy?: "exponential" | "linear";
177
+ }
178
+
179
+ type DefaultDataType = unknown;
180
+ type DefaultMoreOptions = NonNullable<unknown>;
181
+ type DefaultPluginArray = CallApiPlugin[];
182
+ type DefaultThrowOnError = boolean;
183
+
184
+ type Parser = (responseString: string) => Awaitable<Record<string, unknown>>;
185
+ declare const getResponseType: <TResponse>(response: Response, parser?: Parser) => {
186
+ arrayBuffer: () => Promise<ArrayBuffer>;
187
+ blob: () => Promise<Blob>;
188
+ formData: () => Promise<FormData>;
189
+ json: () => Promise<TResponse>;
190
+ stream: () => ReadableStream<Uint8Array<ArrayBufferLike>> | null;
191
+ text: () => Promise<string>;
192
+ };
193
+ type InitResponseTypeMap<TResponse = unknown> = ReturnType<typeof getResponseType<TResponse>>;
194
+ type ResponseTypeUnion = keyof InitResponseTypeMap | undefined;
195
+ type ResponseTypeMap<TResponse> = {
196
+ [Key in keyof InitResponseTypeMap<TResponse>]: Awaited<ReturnType<InitResponseTypeMap<TResponse>[Key]>>;
197
+ };
198
+ type GetResponseType<TResponse, TResponseType extends ResponseTypeUnion, TComputedMap extends ResponseTypeMap<TResponse> = ResponseTypeMap<TResponse>> = undefined extends TResponseType ? TComputedMap["json"] : TResponseType extends NonNullable<ResponseTypeUnion> ? TComputedMap[TResponseType] : never;
199
+
200
+ type UnionToIntersection<TUnion> = (TUnion extends unknown ? (param: TUnion) => void : never) extends (param: infer TParam) => void ? TParam : never;
201
+ type InferSchema<TResult> = TResult extends StandardSchemaV1 ? InferSchemaResult<TResult, NonNullable<unknown>> : TResult;
202
+ type InferPluginOptions<TPluginArray extends CallApiPlugin[]> = UnionToIntersection<InferSchema<ReturnType<NonNullable<TPluginArray[number]["createExtraOptions"]>>>>;
203
+ type PluginInitContext<TMoreOptions = DefaultMoreOptions> = WithMoreOptions<TMoreOptions> & {
204
+ initURL: InitURL | undefined;
205
+ options: CombinedCallApiExtraOptions;
206
+ request: CallApiRequestOptionsForHooks;
207
+ };
208
+ type PluginInitResult = Partial<Omit<PluginInitContext, "request"> & {
209
+ request: CallApiRequestOptions;
210
+ }>;
211
+ interface CallApiPlugin<TData = never, TErrorData = never> {
212
+ /**
213
+ * Defines additional options that can be passed to callApi
214
+ */
215
+ createExtraOptions?: (...params: never[]) => unknown;
216
+ /**
217
+ * A description for the plugin
218
+ */
219
+ description?: string;
220
+ /**
221
+ * Hooks / Interceptors for the plugin
222
+ */
223
+ hooks?: InterceptorsOrInterceptorArray<TData, TErrorData>;
224
+ /**
225
+ * A unique id for the plugin
226
+ */
227
+ id: string;
228
+ /**
229
+ * A function that will be called when the plugin is initialized. This will be called before the any of the other internal functions.
230
+ */
231
+ init?: (context: PluginInitContext) => Awaitable<PluginInitResult> | Awaitable<void>;
232
+ /**
233
+ * A name for the plugin
234
+ */
235
+ name: string;
236
+ /**
237
+ * A version for the plugin
238
+ */
239
+ version?: string;
240
+ }
241
+ declare const definePlugin: <TPlugin extends CallApiPlugin | AnyFunction<CallApiPlugin>>(plugin: TPlugin) => TPlugin;
242
+ type Plugins<TPluginArray extends CallApiPlugin[]> = TPluginArray | ((context: PluginInitContext) => TPluginArray);
243
+
244
+ declare const fetchSpecificKeys: ("body" | "cache" | "credentials" | "headers" | "integrity" | "keepalive" | "method" | "mode" | "priority" | "redirect" | "referrer" | "referrerPolicy" | "signal" | "window")[];
245
+ declare const defaultRetryMethods: ("GET" | "POST")[];
246
+ declare const defaultRetryStatusCodes: Required<BaseCallApiExtraOptions>["retryStatusCodes"];
247
+
248
+ /**
249
+ * @description Makes a type required if TSchema type is undefined or if the output type of TSchema contains undefined, otherwise keeps it as is
250
+ */
251
+ type MakeSchemaOptionRequired<TSchema extends StandardSchemaV1 | undefined, TObject> = undefined extends TSchema ? TObject : undefined extends InferSchemaResult<TSchema, NonNullable<unknown>> ? TObject : Required<TObject>;
252
+ type Body = UnmaskType<Record<string, unknown> | RequestInit["body"]>;
253
+ type BodyOption<TSchemas extends CallApiSchemas> = MakeSchemaOptionRequired<TSchemas["body"], {
254
+ /**
255
+ * Body of the request, can be a object or any other supported body type.
256
+ */
257
+ body?: InferSchemaResult<TSchemas["body"], Body>;
258
+ }>;
259
+ type Method = UnmaskType<"CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE" | AnyString>;
260
+ type MethodOption<TSchemas extends CallApiSchemas> = MakeSchemaOptionRequired<TSchemas["method"], {
261
+ /**
262
+ * HTTP method for the request.
263
+ * @default "GET"
264
+ */
265
+ method?: InferSchemaResult<TSchemas["method"], Method>;
266
+ }>;
267
+ type Headers = UnmaskType<Record<"Authorization", CommonAuthorizationHeaders> | Record<"Content-Type", CommonContentTypes> | Record<CommonRequestHeaders, string | undefined> | Record<string, string | undefined> | RequestInit["headers"]>;
268
+ type HeadersOption<TSchemas extends CallApiSchemas> = MakeSchemaOptionRequired<TSchemas["headers"], {
269
+ /**
270
+ * Headers to be used in the request.
271
+ */
272
+ headers?: InferSchemaResult<TSchemas["headers"], Headers>;
273
+ }>;
274
+ interface Register {
275
+ }
276
+ type GlobalMeta = Register extends {
277
+ meta?: infer TMeta extends Record<string, unknown>;
278
+ } ? TMeta : never;
279
+ type MetaOption<TSchemas extends CallApiSchemas> = {
280
+ /**
281
+ * - An optional field you can fill with additional information,
282
+ * to associate with the request, typically used for logging or tracing.
283
+ *
284
+ * - A good use case for this, would be to use the info to handle specific cases in any of the shared interceptors.
285
+ *
286
+ * @example
287
+ * ```ts
288
+ * const callMainApi = callApi.create({
289
+ * baseURL: "https://main-api.com",
290
+ * onResponseError: ({ response, options }) => {
291
+ * if (options.meta?.userId) {
292
+ * console.error(`User ${options.meta.userId} made an error`);
293
+ * }
294
+ * },
295
+ * });
296
+ *
297
+ * const response = await callMainApi({
298
+ * url: "https://example.com/api/data",
299
+ * meta: { userId: "123" },
300
+ * });
301
+ * ```
302
+ */
303
+ meta?: InferSchemaResult<TSchemas["meta"], GlobalMeta>;
304
+ };
305
+ type ResultModeOption<TErrorData, TResultMode extends ResultModeUnion> = TErrorData extends false ? {
306
+ resultMode: "onlySuccessWithException";
307
+ } : TErrorData extends false | undefined ? {
308
+ resultMode?: "onlySuccessWithException";
309
+ } : undefined extends TResultMode ? {
310
+ resultMode?: TResultMode;
311
+ } : {
312
+ resultMode: TResultMode;
313
+ };
314
+
315
+ type FetchSpecificKeysUnion = Exclude<(typeof fetchSpecificKeys)[number], "body" | "headers" | "method">;
316
+ type CallApiRequestOptions<TSchemas extends CallApiSchemas = DefaultMoreOptions> = BodyOption<TSchemas> & HeadersOption<TSchemas> & MethodOption<TSchemas> & Pick<RequestInit, FetchSpecificKeysUnion>;
317
+ type CallApiRequestOptionsForHooks<TSchemas extends CallApiSchemas = DefaultMoreOptions> = Omit<CallApiRequestOptions<TSchemas>, "headers"> & {
318
+ headers?: Record<string, string | undefined>;
319
+ };
320
+ type WithMoreOptions<TMoreOptions = DefaultMoreOptions> = {
321
+ options: CombinedCallApiExtraOptions & Partial<TMoreOptions>;
322
+ };
323
+ interface Interceptors<TData = DefaultDataType, TErrorData = DefaultDataType, TMoreOptions = DefaultMoreOptions> {
324
+ /**
325
+ * 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.
326
+ * It is basically a combination of `onRequestError` and `onResponseError` interceptors
327
+ */
328
+ onError?: (context: ErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;
329
+ /**
330
+ * Interceptor that will be called just before the request is made, allowing for modifications or additional operations.
331
+ */
332
+ onRequest?: (context: RequestContext & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;
333
+ /**
334
+ * Interceptor that will be called when an error occurs during the fetch request.
335
+ */
336
+ onRequestError?: (context: RequestErrorContext & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;
337
+ /**
338
+ * Interceptor that will be called when any response is received from the api, whether successful or not
339
+ */
340
+ onResponse?: (context: ResponseContext<TData, TErrorData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;
341
+ /**
342
+ * Interceptor that will be called when an error response is received from the api.
343
+ */
344
+ onResponseError?: (context: ResponseErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;
345
+ /**
346
+ * Interceptor that will be called when a request is retried.
347
+ */
348
+ onRetry?: (response: ErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;
349
+ /**
350
+ * Interceptor that will be called when a successful response is received from the api.
351
+ */
352
+ onSuccess?: (context: SuccessContext<TData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;
353
+ }
354
+ type InterceptorsOrInterceptorArray<TData = DefaultDataType, TErrorData = DefaultDataType, TMoreOptions = DefaultMoreOptions> = {
355
+ [Key in keyof Interceptors<TData, TErrorData, TMoreOptions>]: Interceptors<TData, TErrorData, TMoreOptions>[Key] | Array<Interceptors<TData, TErrorData, TMoreOptions>[Key]>;
356
+ };
357
+ type FetchImpl = UnmaskType<(input: string | Request | URL, init?: RequestInit) => Promise<Response>>;
358
+ type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemas extends CallApiSchemas = DefaultMoreOptions, TPluginArray extends CallApiPlugin[] = DefaultPluginArray> = {
359
+ /**
360
+ * Authorization header value.
361
+ */
362
+ auth?: string | Auth | null;
363
+ /**
364
+ * Base URL to be prepended to all request URLs
365
+ */
366
+ baseURL?: string;
367
+ /**
368
+ * Custom function to serialize the body object into a string.
369
+ */
370
+ bodySerializer?: (bodyData: Record<string, unknown>) => string;
371
+ /**
372
+ * Whether or not to clone the response, so response.json() and the like, can be read again else where.
373
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/clone
374
+ * @default false
375
+ */
376
+ cloneResponse?: boolean;
377
+ /**
378
+ * Custom fetch implementation
379
+ */
380
+ customFetchImpl?: FetchImpl;
381
+ /**
382
+ * Custom request key to be used to identify a request in the fetch deduplication strategy.
383
+ * @default the full request url + string formed from the request options
384
+ */
385
+ dedupeKey?: string;
386
+ /**
387
+ * Defines the deduplication strategy for the request, can be set to "none" | "defer" | "cancel".
388
+ * - If set to "cancel", the previous pending request with the same request key will be cancelled and lets the new request through.
389
+ * - If set to "defer", all new request with the same request key will be share the same response, until the previous one is completed.
390
+ * - If set to "none", deduplication is disabled.
391
+ * @default "cancel"
392
+ */
393
+ dedupeStrategy?: "cancel" | "defer" | "none";
394
+ /**
395
+ * Default error message to use if none is provided from a response.
396
+ * @default "Failed to fetch data from server!"
397
+ */
398
+ defaultErrorMessage?: string;
399
+ /**
400
+ * Resolved request URL
401
+ */
402
+ readonly fullURL?: string;
403
+ /**
404
+ * Defines the mode in which the merged hooks are executed, can be set to "parallel" | "sequential".
405
+ * - If set to "parallel", main and plugin hooks will be executed in parallel.
406
+ * - If set to "sequential", the plugin hooks will be executed first, followed by the main hook.
407
+ * @default "parallel"
408
+ */
409
+ mergedHooksExecutionMode?: "parallel" | "sequential";
410
+ /**
411
+ * - Controls what order in which the merged hooks execute
412
+ * @default "mainHooksLast"
413
+ */
414
+ mergedHooksExecutionOrder?: "mainHooksAfterPlugins" | "mainHooksBeforePlugins";
415
+ /**
416
+ * An array of CallApi plugins. It allows you to extend the behavior of the library.
417
+ */
418
+ plugins?: Plugins<TPluginArray>;
419
+ /**
420
+ * Custom function to parse the response string into a object.
421
+ */
422
+ responseParser?: (responseString: string) => Awaitable<Record<string, unknown>>;
423
+ /**
424
+ * Expected response type, affects how response is parsed
425
+ * @default "json"
426
+ */
427
+ responseType?: TResponseType;
428
+ /**
429
+ * Mode of the result, can influence how results are handled or returned.
430
+ * Can be set to "all" | "onlySuccess" | "onlyError" | "onlyResponse".
431
+ * @default "all"
432
+ */
433
+ resultMode?: TResultMode;
434
+ /**
435
+ * Type-safe schemas for the response validation.
436
+ */
437
+ schemas?: TSchemas;
438
+ /**
439
+ * If true or the function returns true, throws errors instead of returning them
440
+ * The function is passed the error object and can be used to conditionally throw the error
441
+ * @default false
442
+ */
443
+ throwOnError?: TThrowOnError | ((context: ErrorContext<TErrorData>) => TThrowOnError);
444
+ /**
445
+ * Request timeout in milliseconds
446
+ */
447
+ timeout?: number;
448
+ /**
449
+ * Custom validation functions for response validation
450
+ */
451
+ validators?: CallApiValidators<TData, TErrorData>;
452
+ } & InterceptorsOrInterceptorArray<TData, TErrorData> & Partial<InferPluginOptions<TPluginArray>> & MetaOption<TSchemas> & RetryOptions<TErrorData> & ResultModeOption<TErrorData, TResultMode> & UrlOptions<TSchemas>;
453
+ declare const optionsEnumToExtendFromBase: ("plugins" | "schemas" | "validators")[];
454
+ type CallApiExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemas extends CallApiSchemas = DefaultMoreOptions, TPluginArray extends CallApiPlugin[] = DefaultPluginArray> = CallApiRequestOptions<TSchemas> & ExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TSchemas, TPluginArray> & {
455
+ /**
456
+ * Options that should extend the base options.
457
+ */
458
+ extend?: Pick<ExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TSchemas, TPluginArray>, (typeof optionsEnumToExtendFromBase)[number]>;
459
+ };
460
+ declare const optionsEnumToOmitFromBase: ("dedupeKey" | "extend")[];
461
+ type BaseCallApiExtraOptions<TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseThrowOnError extends boolean = DefaultThrowOnError, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBaseSchemas extends CallApiSchemas = DefaultMoreOptions, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray> = Omit<Partial<CallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBaseSchemas, TBasePluginArray>>, (typeof optionsEnumToOmitFromBase)[number]>;
462
+ type CombinedCallApiExtraOptions = BaseCallApiExtraOptions & CallApiExtraOptions;
463
+ type CallApiParameters<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemas extends CallApiSchemas = DefaultMoreOptions, TPluginArray extends CallApiPlugin[] = DefaultPluginArray> = [
464
+ initURL: InferSchemaResult<TSchemas["initURL"], InitURL>,
465
+ config?: CallApiExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TSchemas, TPluginArray>
466
+ ];
467
+ type RequestContext = UnmaskType<{
468
+ options: CombinedCallApiExtraOptions;
469
+ request: CallApiRequestOptionsForHooks;
470
+ }>;
471
+ type ResponseContext<TData, TErrorData> = UnmaskType<{
472
+ data: TData;
473
+ error: null;
474
+ options: CombinedCallApiExtraOptions;
475
+ request: CallApiRequestOptionsForHooks;
476
+ response: Response;
477
+ } | {
478
+ data: null;
479
+ error: PossibleHTTPError<TErrorData>;
480
+ options: CombinedCallApiExtraOptions;
481
+ request: CallApiRequestOptionsForHooks;
482
+ response: Response;
483
+ }>;
484
+ type SuccessContext<TData> = UnmaskType<{
485
+ data: TData;
486
+ options: CombinedCallApiExtraOptions;
487
+ request: CallApiRequestOptionsForHooks;
488
+ response: Response;
489
+ }>;
490
+ type PossibleJavascriptErrorNames = "AbortError" | "Error" | "SyntaxError" | "TimeoutError" | "TypeError" | (`${string}Error` & DefaultMoreOptions);
491
+ type PossibleJavaScriptError = UnmaskType<{
492
+ errorData: DOMException | Error | SyntaxError | TypeError;
493
+ message: string;
494
+ name: PossibleJavascriptErrorNames;
495
+ }>;
496
+ type PossibleHTTPError<TErrorData> = UnmaskType<{
497
+ errorData: TErrorData;
498
+ message: string;
499
+ name: "HTTPError";
500
+ }>;
501
+ type RequestErrorContext = UnmaskType<{
502
+ error: PossibleJavaScriptError;
503
+ options: CombinedCallApiExtraOptions;
504
+ request: CallApiRequestOptionsForHooks;
505
+ response: null;
506
+ }>;
507
+ type ResponseErrorContext<TErrorData> = UnmaskType<{
508
+ error: PossibleHTTPError<TErrorData>;
509
+ options: CombinedCallApiExtraOptions;
510
+ request: CallApiRequestOptionsForHooks;
511
+ response: Response;
512
+ }>;
513
+ type ErrorContext<TErrorData> = UnmaskType<{
514
+ error: PossibleHTTPError<TErrorData>;
515
+ options: CombinedCallApiExtraOptions;
516
+ request: CallApiRequestOptionsForHooks;
517
+ response: Response;
518
+ } | {
519
+ error: PossibleJavaScriptError;
520
+ options: CombinedCallApiExtraOptions;
521
+ request: CallApiRequestOptionsForHooks;
522
+ response: null;
523
+ }>;
524
+ type CallApiResultSuccessVariant<TData> = {
525
+ data: TData;
526
+ error: null;
527
+ response: Response;
528
+ };
529
+ type CallApiResultErrorVariant<TErrorData> = {
530
+ data: null;
531
+ error: PossibleHTTPError<TErrorData>;
532
+ response: Response;
533
+ } | {
534
+ data: null;
535
+ error: PossibleJavaScriptError;
536
+ response: null;
537
+ };
538
+ type ResultModeMap<TData = DefaultDataType, TErrorData = DefaultDataType, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TComputedData = GetResponseType<TData, TResponseType>, TComputedErrorData = GetResponseType<TErrorData, TResponseType>> = UnmaskType<{
539
+ all: CallApiResultSuccessVariant<TComputedData> | CallApiResultErrorVariant<TComputedErrorData>;
540
+ allWithException: CallApiResultSuccessVariant<TComputedData>;
541
+ allWithoutResponse: CallApiResultSuccessVariant<TComputedData>["data" | "error"] | CallApiResultErrorVariant<TComputedErrorData>["data" | "error"];
542
+ onlyError: CallApiResultSuccessVariant<TComputedData>["error"] | CallApiResultErrorVariant<TComputedErrorData>["error"];
543
+ onlyResponse: CallApiResultErrorVariant<TComputedErrorData>["response"] | CallApiResultSuccessVariant<TComputedData>["response"];
544
+ onlyResponseWithException: CallApiResultSuccessVariant<TComputedErrorData>["response"];
545
+ onlySuccess: CallApiResultErrorVariant<TComputedErrorData>["data"] | CallApiResultSuccessVariant<TComputedData>["data"];
546
+ onlySuccessWithException: CallApiResultSuccessVariant<TComputedData>["data"];
547
+ }>;
548
+ type ResultModeUnion = keyof ResultModeMap | undefined;
549
+ type GetCallApiResult<TData, TErrorData, TResultMode extends ResultModeUnion, TThrowOnError extends boolean, TResponseType extends ResponseTypeUnion> = TErrorData extends false | undefined ? ResultModeMap<TData, TErrorData, TResponseType>["onlySuccessWithException"] : ResultModeUnion | undefined extends TResultMode ? TThrowOnError extends true ? ResultModeMap<TData, TErrorData, TResponseType>["allWithException"] : ResultModeMap<TData, TErrorData, TResponseType>["all"] : TResultMode extends NonNullable<ResultModeUnion> ? ResultModeMap<TData, TErrorData, TResponseType>[TResultMode] : never;
550
+
551
+ export { type BaseCallApiExtraOptions as B, type CallApiSchemas as C, type DefaultPluginArray as D, type ErrorContext as E, type GetCallApiResult as G, type InferSchemaResult as I, type PluginInitContext as P, type ResultModeUnion as R, type SuccessContext as S, type ResponseTypeUnion as a, type CallApiPlugin as b, type CallApiExtraOptions as c, type DefaultDataType as d, type DefaultThrowOnError as e, type DefaultMoreOptions as f, definePlugin as g, type PossibleJavaScriptError as h, type PossibleHTTPError as i, type CallApiParameters as j, type CallApiRequestOptions as k, type CallApiRequestOptionsForHooks as l, type CallApiResultErrorVariant as m, type CallApiResultSuccessVariant as n, type CombinedCallApiExtraOptions as o, type Interceptors as p, type InterceptorsOrInterceptorArray as q, type PossibleJavascriptErrorNames as r, type Register as s, type RequestContext as t, type RequestErrorContext as u, type ResponseContext as v, type ResponseErrorContext as w, type InitURL as x, defaultRetryMethods as y, defaultRetryStatusCodes as z };
@@ -0,0 +1,17 @@
1
+ type ErrorDetails<TErrorResponse> = {
2
+ defaultErrorMessage: string;
3
+ errorData: TErrorResponse;
4
+ response: Response;
5
+ };
6
+ type ErrorOptions = {
7
+ cause?: unknown;
8
+ };
9
+ declare class HTTPError<TErrorResponse = Record<string, unknown>> extends Error {
10
+ errorData: ErrorDetails<TErrorResponse>["errorData"];
11
+ isHTTPError: boolean;
12
+ name: "HTTPError";
13
+ response: ErrorDetails<TErrorResponse>["response"];
14
+ constructor(errorDetails: ErrorDetails<TErrorResponse>, errorOptions?: ErrorOptions);
15
+ }
16
+
17
+ export { HTTPError as H };
@@ -0,0 +1 @@
1
+ "use strict";var e,r=Object.defineProperty,t=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,n={};((e,t)=>{for(var o in t)r(e,o,{get:t[o],enumerable:!0})})(n,{HTTPError:()=>a,callApi:()=>L,createFetchClient:()=>U,definePlugin:()=>x}),module.exports=(e=n,((e,n,a,i)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let l of o(n))s.call(e,l)||l===a||r(e,l,{get:()=>n[l],enumerable:!(i=t(n,l))||i.enumerable});return e})(r({},"__esModule",{value:!0}),e));var a=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)}},i=e=>e instanceof a||d(e)&&"HTTPError"===e.name&&!0===e.isHTTPError,l=e=>Array.isArray(e),u=e=>"object"==typeof e&&null!==e,c=e=>"[object Object]"===Object.prototype.toString.call(e),d=e=>{if(!c(e))return!1;const r=e?.constructor;if(void 0===r)return!0;const t=r.prototype;return!!c(t)&&(!!Object.hasOwn(t,"isPrototypeOf")&&Object.getPrototypeOf(e)===Object.prototype)},p=e=>"function"==typeof e,y=e=>"string"==typeof e,f=e=>p(e)?e():e,h=e=>{if(void 0!==e){if(y(e)||null===e)return{Authorization:`Bearer ${e}`};switch(e.type){case"Basic":{const r=f(e.username),t=f(e.password);if(void 0===r||void 0===t)return;return{Authorization:`Basic ${globalThis.btoa(`${r}:${t}`)}`}}case"Custom":{const r=f(e.value);if(void 0===r)return;return{Authorization:`${f(e.prefix)} ${r}`}}default:{const r=f(e.bearer),t=f(e.token);return"token"in e&&void 0!==t?{Authorization:`Token ${t}`}:void 0!==r&&{Authorization:`Bearer ${r}`}}}}},m=["extend","dedupeKey"],g=["body","integrity","method","headers","signal","cache","redirect","window","credentials","keepalive","referrer","priority","mode","referrerPolicy"],w={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"},b=["GET","POST"],E=Object.keys(w).map(Number),R=(e,r)=>{const t={},o=new Set(r);for(const[r,s]of Object.entries(e))o.has(r)||(t[r]=s);return t},S=(e,r)=>{const t={},o=new Set(r);for(const[r,s]of Object.entries(e))o.has(r)&&(t[r]=s);return t},O=e=>!e||d(e)?e:Object.fromEntries(e),v=e=>{const{auth:r,baseHeaders:t,body:o,headers:s}=e;if(!Boolean(t||s||o||r))return;const n={...h(r),...O(t),...O(s)};return y(a=o)&&a.includes("=")?(n["Content-Type"]="application/x-www-form-urlencoded",n):((d(o)||y(o)&&o.startsWith("{"))&&(n["Content-Type"]="application/json",n.Accept="application/json"),n);var a},q=(...e)=>Promise.all(e),T=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},D=async e=>{const{$RequestInfoCache:r,newFetchController:t,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?r:null;null!==n&&await T(.1);const i=a?.get(n);return{handleRequestCancelStrategy:()=>{if(!(i&&"cancel"===o.dedupeStrategy))return;const e=o.dedupeKey?`Duplicate request detected - Aborting previous request with key '${o.dedupeKey}' as a new request was initiated`:`Duplicate request detected - Aborting previous request to '${o.fullURL}' as a new request with identical options was initiated`,r=new DOMException(e,"AbortError");return i.controller.abort(r),Promise.resolve()},handleRequestDeferStrategy:()=>{const e=(e=>{if(e)return e;if("undefined"!=typeof globalThis&&p(globalThis.fetch))return globalThis.fetch;throw new Error("No fetch implementation found")})(o.customFetchImpl),r=i&&"defer"===o.dedupeStrategy?i.responsePromise:e(o.fullURL,s);return a?.set(n,{controller:t,responsePromise:r}),r},removeDedupeKeyFromCache:()=>a?.delete(n)}},x=e=>e,j=(e,r)=>async t=>{if("sequential"!==r){if("parallel"===r){const r=[...e];await Promise.all(r.map((e=>e?.(t))))}}else for(const r of e)await(r?.(t))},M={onError:new Set,onRequest:new Set,onRequestError:new Set,onResponse:new Set,onResponseError:new Set,onRetry:new Set,onSuccess:new Set},P=(e,r)=>e?p(e)?e(r):e:[],$=async(e,r,t)=>{const o=((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(o,r))throw new Error(`Invalid response type: ${r}`);return await o[r]()},k=(e,r)=>{const t=e["~retryCount"]??0;return{getDelay:()=>"exponential"===e.retryStrategy?((e,r)=>{const t=r.retryMaxDelay??1e4,o=(r.retryDelay??1e3)*2**e;return Math.min(o,t)})(t,e):(e=>e.retryDelay??1e3)(e),shouldAttemptRetry:async()=>{const o=await(e.retryCondition?.(r))??!0,s=(e.retryAttempts??0)>t&&o;if("HTTPError"!==r.error.name)return s;const n=!!r.request.method&&e.retryMethods?.includes(r.request.method);return!!r.response?.status&&e.retryStatusCodes?.includes(r.response.status)&&n&&s}}},A=(e,r)=>{if(!r)return e;const t=(o=r)?new URLSearchParams(o).toString():(console.error("toQueryString:","No query params provided!"),null);var o;return 0===t?.length?e:e.endsWith("?")?`${e}${t}`:e.includes("?")?`${e}&${t}`:`${e}?${t}`},C=(e,r,t)=>{if(!e)return;const o=((e,r)=>{if(!r)return e;let t=e;if(l(r)){const e=t.split("/").filter((e=>e.startsWith(":")));for(const[o,s]of e.entries()){const e=r[o];t=t.replace(s,e)}return t}for(const[e,o]of Object.entries(r))t=t.replace(`:${e}`,String(o));return t})(e,r);return A(o,t)},H=async(e,r,t)=>{const o=t?t(e):e,s=r?await(async(e,r)=>{const t=await e["~standard"].validate(r);if(t.issues)throw new Error(JSON.stringify(t.issues,null,2),{cause:t.issues});return t.value})(r,o):o;return s},U=e=>{const[r,t]=(e=>[S(e,g),R(e,[...g,...m])])(e??{}),o=new Map,s=async(...e)=>{const[n,c={}]=e,[f,h]=(e=>[S(e,g),R(e,g)])(c),m={};for(const e of Object.keys(M)){const r=(w=t[e],O=h[e],l(w)?[w,O].flat():O??w);m[e]=r}var w,O;const x={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:b,retryStatusCodes:E,retryStrategy:"linear",...t,...h,...m},A=f.body??r.body,U={...r,...f,body:d(A)?x.bodySerializer(A):A,headers:v({auth:x.auth,baseHeaders:r.headers,body:A,headers:f.headers}),signal:f.signal??r.signal},{resolvedHooks:L,resolvedOptions:W,resolvedRequestOptions:B,url:z}=await(async e=>{const{initURL:r,options:t,request:o}=e,s=structuredClone(M),n=()=>{for(const e of Object.keys(M)){const r=t[e];s[e].add(r)}},a=e=>{for(const r of Object.keys(M)){const t=e[r];s[r].add(t)}};"mainHooksBeforePlugins"===t.mergedHooksExecutionOrder&&n();const i=[...P(t.plugins,e),...P(t.extend?.plugins,e)];let l=r,u=t,c=o;const p=async e=>{if(!e)return;const s=await e({initURL:r,options:t,request:o});d(s)&&(y(s.initURL)&&(l=s.initURL),d(s.request)&&(c=s.request),d(s.options)&&(u=s.options))};for(const e of i)await p(e.init),e.hooks&&a(e.hooks);t.mergedHooksExecutionOrder&&"mainHooksAfterPlugins"!==t.mergedHooksExecutionOrder||n();const f={};for(const[e,r]of Object.entries(s)){const o=[...r].flat(),s=j(o,t.mergedHooksExecutionMode);f[e]=s}return{resolvedHooks:f,resolvedOptions:u,resolvedRequestOptions:c,url:l?.toString()}})({initURL:n,options:x,request:U}),F=`${W.baseURL}${C(z,W.params,W.query)}`,N={...W,...L,fullURL:F,initURL:n.toString()},K=new AbortController,I=null!=N.timeout?(G=N.timeout,AbortSignal.timeout(G)):null;var G;const J=((...e)=>AbortSignal.any(e.filter(Boolean)))(B.signal,I,K.signal),_={...B,signal:J},{handleRequestCancelStrategy:Q,handleRequestDeferStrategy:V,removeDedupeKeyFromCache:X}=await D({$RequestInfoCache:o,newFetchController:K,options:N,request:_});await Q();try{await q(N.onRequest({options:N,request:_})),_.headers=v({auth:N.auth,baseHeaders:r.headers,body:A,headers:_.headers});const e=await V(),t="defer"===N.dedupeStrategy||N.cloneResponse,{schemas:o,validators:s}=(e=>({schemas:e.schemas&&{...e.schemas,...e.extend?.schemas},validators:e.validators&&{...e.validators,...e.extend?.validators}}))(N);if(!e.ok){const r=await $(t?e.clone():e,N.responseType,N.responseParser),n=await H(r,o?.errorData,s?.errorData);throw new a({defaultErrorMessage:N.defaultErrorMessage,errorData:n,response:e})}const n=await $(t?e.clone():e,N.responseType,N.responseParser),i={data:await H(n,o?.data,s?.data),options:N,request:_,response:N.cloneResponse?e.clone():e};return await q(N.onSuccess(i),N.onResponse({...i,error:null})),await(e=>{const{data:r,response:t,resultMode:o}=e,s={data:r,error:null,response:t};return o?{all:s,allWithException:s,allWithoutResponse:R(s,["response"]),onlyError:s.error,onlyResponse:s.response,onlyResponseWithException:s.response,onlySuccess:s.data,onlySuccessWithException:s.data}[o]:s})({data:i.data,response:i.response,resultMode:N.resultMode})}catch(e){const{apiDetails:r,getErrorResult:t}=(e=>{const{cloneResponse:r,defaultErrorMessage:t,error:o,message:s,resultMode:n}=e;let a={data:null,error:{errorData:o,message:s??o.message,name:o.name},response:null};if(i(o)){const{errorData:e,message:s=t,name:n,response:i}=o;a={data:null,error:{errorData:e,message:s,name:n},response:r?i.clone():i}}const l={all:a,allWithException:a,allWithoutResponse:R(a,["response"]),onlyError:a.error,onlyResponse:a.response,onlyResponseWithException:a.response,onlySuccess:a.data,onlySuccessWithException:a.data};return{apiDetails:a,getErrorResult:e=>{const r=l[n??"all"];return u(e)?{...r,...e}:r}}})({cloneResponse:N.cloneResponse,defaultErrorMessage:N.defaultErrorMessage,error:e,resultMode:N.resultMode}),o={error:r.error,options:N,request:_,response:r.response},{getDelay:a,shouldAttemptRetry:l}=k(N,o);if(!J.aborted&&await l()){await q(N.onRetry(o));const e=a();await T(e);const r={...c,"~retryCount":(N["~retryCount"]??0)+1};return await s(n,r)}const d=p(N.throwOnError)?N.throwOnError(o):N.throwOnError,y=()=>{if(d)throw r.error};if(i(e))return await q(N.onResponseError(o),N.onError(o),N.onResponse({...o,data:null})),y(),t();if(e instanceof DOMException&&"AbortError"===e.name){const{message:r,name:o}=e;return console.error(`${o}:`,r),y(),t()}if(e instanceof DOMException&&"TimeoutError"===e.name){const r=`Request timed out after ${N.timeout}ms`;return console.error(`${e.name}:`,r),y(),t({message:r})}return await q(N.onRequestError(o),N.onError(o)),y(),t()}finally{X()}};return s.create=U,s},L=U();//# sourceMappingURL=index.cjs.map