@zayne-labs/callapi 1.7.4 → 1.7.6

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,774 +0,0 @@
1
- type ValueOrFunctionResult<TValue> = TValue | (() => TValue);
2
- /**
3
- * Bearer Or Token authentication
4
- *
5
- * The value of `bearer` will be added to a header as
6
- * `auth: Bearer some-auth-token`,
7
- *
8
- * The value of `token` will be added to a header as
9
- * `auth: Token some-auth-token`,
10
- */
11
- type BearerOrTokenAuth = {
12
- type?: "Bearer";
13
- bearer?: ValueOrFunctionResult<string | null>;
14
- token?: never;
15
- } | {
16
- type?: "Token";
17
- bearer?: never;
18
- token?: ValueOrFunctionResult<string | null>;
19
- };
20
- /**
21
- * Basic auth
22
- */
23
- type BasicAuth = {
24
- type: "Basic";
25
- username: ValueOrFunctionResult<string | null | undefined>;
26
- password: ValueOrFunctionResult<string | null | undefined>;
27
- };
28
- /**
29
- * Custom auth
30
- *
31
- * @param prefix - prefix of the header
32
- * @param authValue - value of the header
33
- *
34
- * @example
35
- * ```ts
36
- * {
37
- * type: "Custom",
38
- * prefix: "Token",
39
- * authValue: "token"
40
- * }
41
- * ```
42
- */
43
- type CustomAuth = {
44
- type: "Custom";
45
- prefix: ValueOrFunctionResult<string | null | undefined>;
46
- value: ValueOrFunctionResult<string | null | undefined>;
47
- };
48
- type Auth = BearerOrTokenAuth | BasicAuth | CustomAuth;
49
-
50
- type AnyString = string & {
51
- z_placeholder?: never;
52
- };
53
- type AnyNumber = number & {
54
- z_placeholder?: never;
55
- };
56
- type AnyFunction<TResult = unknown> = (...args: any) => TResult;
57
- type Prettify<TObject> = NonNullable<unknown> & {
58
- [Key in keyof TObject]: TObject[Key];
59
- };
60
- type UnmaskType<TValue> = {
61
- _: TValue;
62
- }["_"];
63
- type Awaitable<TValue> = Promise<TValue> | TValue;
64
- 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;
65
- type CommonAuthorizationHeaders = `${"Basic" | "Bearer" | "Token"} ${string}`;
66
- 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;
67
-
68
- type ErrorDetails<TErrorResponse> = {
69
- defaultErrorMessage: string;
70
- errorData: TErrorResponse;
71
- response: Response;
72
- };
73
- type ErrorOptions = {
74
- cause?: unknown;
75
- };
76
- declare class HTTPError<TErrorResponse = Record<string, unknown>> {
77
- cause: ErrorOptions["cause"];
78
- errorData: ErrorDetails<TErrorResponse>["errorData"];
79
- isHTTPError: boolean;
80
- message: string;
81
- name: "HTTPError";
82
- response: ErrorDetails<TErrorResponse>["response"];
83
- constructor(errorDetails: ErrorDetails<TErrorResponse>, errorOptions?: ErrorOptions);
84
- }
85
- type PossibleJavaScriptError = UnmaskType<{
86
- errorData: DOMException | Error | SyntaxError | TypeError;
87
- message: string;
88
- name: "AbortError" | "Error" | "SyntaxError" | "TimeoutError" | "TypeError" | (`${string}Error` & {});
89
- }>;
90
- type PossibleHTTPError<TErrorData> = UnmaskType<{
91
- errorData: TErrorData;
92
- message: string;
93
- name: "HTTPError";
94
- }>;
95
-
96
- /**
97
- * The Standard Schema interface.
98
- * @see https://github.com/standard-schema/standard-schema
99
- */
100
- interface StandardSchemaV1<Input = unknown, Output = Input> {
101
- /**
102
- * The Standard Schema properties.
103
- */
104
- readonly "~standard": StandardSchemaV1.Props<Input, Output>;
105
- }
106
- declare namespace StandardSchemaV1 {
107
- /**
108
- * The Standard Schema properties interface.
109
- */
110
- interface Props<Input = unknown, Output = Input> {
111
- /**
112
- * Inferred types associated with the schema.
113
- */
114
- readonly types?: Types<Input, Output> | undefined;
115
- /**
116
- * Validates unknown input values.
117
- */
118
- readonly validate: (value: unknown) => Promise<Result<Output>> | Result<Output>;
119
- /**
120
- * The vendor name of the schema library.
121
- */
122
- readonly vendor: string;
123
- /**
124
- * The version number of the standard.
125
- */
126
- readonly version: 1;
127
- }
128
- /**
129
- * The result interface of the validate function.
130
- */
131
- type Result<Output> = FailureResult | SuccessResult<Output>;
132
- /**
133
- * The result interface if validation succeeds.
134
- */
135
- interface SuccessResult<Output> {
136
- /**
137
- * The non-existent issues.
138
- */
139
- readonly issues?: undefined;
140
- /**
141
- * The typed output value.
142
- */
143
- readonly value: Output;
144
- }
145
- /**
146
- * The result interface if validation fails.
147
- */
148
- interface FailureResult {
149
- /**
150
- * The issues of failed validation.
151
- */
152
- readonly issues: readonly Issue[];
153
- }
154
- /**
155
- * The issue interface of the failure output.
156
- */
157
- interface Issue {
158
- /**
159
- * The error message of the issue.
160
- */
161
- readonly message: string;
162
- /**
163
- * The path of the issue, if any.
164
- */
165
- readonly path?: ReadonlyArray<PathSegment | PropertyKey> | undefined;
166
- }
167
- /**
168
- * The path segment interface of the issue.
169
- */
170
- interface PathSegment {
171
- /**
172
- * The key representing a path segment.
173
- */
174
- readonly key: PropertyKey;
175
- }
176
- /**
177
- * The Standard Schema types interface.
178
- */
179
- interface Types<Input = unknown, Output = Input> {
180
- /** The input type of the schema. */
181
- readonly input: Input;
182
- /** The output type of the schema. */
183
- readonly output: Output;
184
- }
185
- /**
186
- * Infers the input type of a Standard Schema.
187
- */
188
- type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"];
189
- /**
190
- * Infers the output type of a Standard Schema.
191
- */
192
- type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
193
- }
194
-
195
- type Params = UnmaskType<Record<string, boolean | number | string> | Array<boolean | number | string>>;
196
- type Query = UnmaskType<Record<string, boolean | number | string>>;
197
- type InitURL = UnmaskType<string | URL>;
198
- interface UrlOptions<TSchemas extends CallApiSchemas> {
199
- /**
200
- * URL to be used in the request.
201
- */
202
- readonly initURL?: string;
203
- /**
204
- * Parameters to be appended to the URL (i.e: /:id)
205
- */
206
- params?: InferSchemaResult<TSchemas["params"], Params>;
207
- /**
208
- * Query parameters to append to the URL.
209
- */
210
- query?: InferSchemaResult<TSchemas["query"], Query>;
211
- }
212
-
213
- interface CallApiSchemas {
214
- /**
215
- * The schema to use for validating the request body.
216
- */
217
- body?: StandardSchemaV1<Body>;
218
- /**
219
- * The schema to use for validating the response data.
220
- */
221
- data?: StandardSchemaV1;
222
- /**
223
- * The schema to use for validating the response error data.
224
- */
225
- errorData?: StandardSchemaV1;
226
- /**
227
- * The schema to use for validating the request headers.
228
- */
229
- headers?: StandardSchemaV1<Headers>;
230
- /**
231
- * The schema to use for validating the request url.
232
- */
233
- initURL?: StandardSchemaV1<InitURL>;
234
- /**
235
- * The schema to use for validating the meta option.
236
- */
237
- meta?: StandardSchemaV1<GlobalMeta>;
238
- /**
239
- * The schema to use for validating the request method.
240
- */
241
- method?: StandardSchemaV1<Method>;
242
- /**
243
- * The schema to use for validating the request url parameter.
244
- */
245
- params?: StandardSchemaV1<Params>;
246
- /**
247
- * The schema to use for validating the request url querys.
248
- */
249
- query?: StandardSchemaV1<Query>;
250
- }
251
- interface CallApiValidators<TData = unknown, TErrorData = unknown> {
252
- /**
253
- * Custom function to validate the response data.
254
- */
255
- data?: (value: unknown) => TData;
256
- /**
257
- * Custom function to validate the response error data, stemming from the api.
258
- * 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.
259
- */
260
- errorData?: (value: unknown) => TErrorData;
261
- }
262
- type InferSchemaResult<TSchema, TData> = TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> : TData;
263
-
264
- type Parser = (responseString: string) => Awaitable<Record<string, unknown>>;
265
- declare const getResponseType: <TResponse>(response: Response, parser?: Parser) => {
266
- arrayBuffer: () => Promise<ArrayBuffer>;
267
- blob: () => Promise<Blob>;
268
- formData: () => Promise<FormData>;
269
- json: () => Promise<TResponse>;
270
- stream: () => ReadableStream<Uint8Array<ArrayBufferLike>> | null;
271
- text: () => Promise<string>;
272
- };
273
- type InitResponseTypeMap<TResponse = unknown> = ReturnType<typeof getResponseType<TResponse>>;
274
- type ResponseTypeUnion = keyof InitResponseTypeMap | undefined;
275
- type ResponseTypeMap<TResponse> = {
276
- [Key in keyof InitResponseTypeMap<TResponse>]: Awaited<ReturnType<InitResponseTypeMap<TResponse>[Key]>>;
277
- };
278
- type GetResponseType<TResponse, TResponseType extends ResponseTypeUnion, TComputedMap extends ResponseTypeMap<TResponse> = ResponseTypeMap<TResponse>> = undefined extends TResponseType ? TComputedMap["json"] : TResponseType extends NonNullable<ResponseTypeUnion> ? TComputedMap[TResponseType] : never;
279
-
280
- type StreamProgressEvent = {
281
- /**
282
- * Current chunk of data being streamed
283
- */
284
- chunk: Uint8Array;
285
- /**
286
- * Progress in percentage
287
- */
288
- progress: number;
289
- /**
290
- * Total size of data in bytes
291
- */
292
- totalBytes: number;
293
- /**
294
- * Amount of data transferred so far
295
- */
296
- transferredBytes: number;
297
- };
298
- declare global {
299
- interface ReadableStream<R> {
300
- [Symbol.asyncIterator]: () => AsyncIterableIterator<R>;
301
- }
302
- }
303
-
304
- type UnionToIntersection<TUnion> = (TUnion extends unknown ? (param: TUnion) => void : never) extends (param: infer TParam) => void ? TParam : never;
305
- type InferSchema<TResult> = TResult extends StandardSchemaV1 ? InferSchemaResult<TResult, NonNullable<unknown>> : TResult;
306
- type InferPluginOptions<TPluginArray extends CallApiPlugin[]> = UnionToIntersection<InferSchema<ReturnType<NonNullable<TPluginArray[number]["createExtraOptions"]>>>>;
307
- type PluginInitContext<TMoreOptions = DefaultMoreOptions> = Prettify<SharedHookContext & WithMoreOptions<TMoreOptions> & {
308
- initURL: InitURL | undefined;
309
- }>;
310
- type PluginInitResult = Partial<Omit<PluginInitContext, "request"> & {
311
- request: CallApiRequestOptions;
312
- }>;
313
- interface CallApiPlugin<TData = never, TErrorData = never> {
314
- /**
315
- * Defines additional options that can be passed to callApi
316
- */
317
- createExtraOptions?: (...params: never[]) => unknown;
318
- /**
319
- * A description for the plugin
320
- */
321
- description?: string;
322
- /**
323
- * Hooks / Interceptors for the plugin
324
- */
325
- hooks?: hooksOrHooksArray<TData, TErrorData>;
326
- /**
327
- * A unique id for the plugin
328
- */
329
- id: string;
330
- /**
331
- * A function that will be called when the plugin is initialized. This will be called before the any of the other internal functions.
332
- */
333
- init?: (context: PluginInitContext) => Awaitable<PluginInitResult> | Awaitable<void>;
334
- /**
335
- * A name for the plugin
336
- */
337
- name: string;
338
- /**
339
- * A version for the plugin
340
- */
341
- version?: string;
342
- }
343
- declare const definePlugin: <TPlugin extends CallApiPlugin | AnyFunction<CallApiPlugin>>(plugin: TPlugin) => TPlugin;
344
- type Plugins<TPluginArray extends CallApiPlugin[]> = TPluginArray;
345
-
346
- type DefaultDataType = unknown;
347
- type DefaultMoreOptions = NonNullable<unknown>;
348
- type DefaultPluginArray = CallApiPlugin[];
349
- type DefaultThrowOnError = boolean;
350
-
351
- type WithMoreOptions<TMoreOptions = DefaultMoreOptions> = {
352
- options: CombinedCallApiExtraOptions & Partial<TMoreOptions>;
353
- };
354
- type Hooks<TData = DefaultDataType, TErrorData = DefaultDataType, TMoreOptions = DefaultMoreOptions> = {
355
- /**
356
- * Hook that will be called when any error occurs within the request/response lifecycle, regardless of whether the error is from the api or not.
357
- * It is basically a combination of `onRequestError` and `onResponseError` hooks
358
- */
359
- onError?: (context: ErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;
360
- /**
361
- * Hook that will be called just before the request is made, allowing for modifications or additional operations.
362
- */
363
- onRequest?: (context: Prettify<RequestContext & WithMoreOptions<TMoreOptions>>) => Awaitable<unknown>;
364
- /**
365
- * Hook that will be called when an error occurs during the fetch request.
366
- */
367
- onRequestError?: (context: Prettify<RequestErrorContext & WithMoreOptions<TMoreOptions>>) => Awaitable<unknown>;
368
- /**
369
- * Hook that will be called when upload stream progress is tracked
370
- */
371
- onRequestStream?: (context: Prettify<RequestStreamContext & WithMoreOptions<TMoreOptions>>) => Awaitable<unknown>;
372
- /**
373
- * Hook that will be called when any response is received from the api, whether successful or not
374
- */
375
- onResponse?: (context: ResponseContext<TData, TErrorData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;
376
- /**
377
- * Hook that will be called when an error response is received from the api.
378
- */
379
- onResponseError?: (context: Prettify<ResponseErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>>) => Awaitable<unknown>;
380
- /**
381
- * Hook that will be called when download stream progress is tracked
382
- */
383
- onResponseStream?: (context: Prettify<ResponseStreamContext & WithMoreOptions<TMoreOptions>>) => Awaitable<unknown>;
384
- /**
385
- * Hook that will be called when a request is retried.
386
- */
387
- onRetry?: (response: ErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;
388
- /**
389
- * Hook that will be called when a successful response is received from the api.
390
- */
391
- onSuccess?: (context: Prettify<SuccessContext<TData> & WithMoreOptions<TMoreOptions>>) => Awaitable<unknown>;
392
- };
393
- type hooksOrHooksArray<TData = DefaultDataType, TErrorData = DefaultDataType, TMoreOptions = DefaultMoreOptions> = {
394
- [Key in keyof Hooks<TData, TErrorData, TMoreOptions>]: Hooks<TData, TErrorData, TMoreOptions>[Key] | Array<Hooks<TData, TErrorData, TMoreOptions>[Key]>;
395
- };
396
- type SharedHookContext = {
397
- /**
398
- * Config object passed to createFetchClient
399
- */
400
- baseConfig: BaseCallApiExtraOptions & CallApiRequestOptions;
401
- /**
402
- * Config object passed to the callApi instance
403
- */
404
- config: CallApiExtraOptions & CallApiRequestOptions;
405
- /**
406
- * Merged options consisting of extra options from createFetchClient, the callApi instance and default options.
407
- *
408
- */
409
- options: CombinedCallApiExtraOptions;
410
- /**
411
- * Merged request consisting of request options from createFetchClient, the callApi instance and default request options.
412
- */
413
- request: CallApiRequestOptionsForHooks;
414
- };
415
- type RequestContext = UnmaskType<SharedHookContext>;
416
- type ResponseContext<TData, TErrorData> = UnmaskType<Prettify<SharedHookContext & {
417
- data: TData;
418
- error: null;
419
- response: Response;
420
- }> | Prettify<SharedHookContext & {
421
- data: null;
422
- error: PossibleHTTPError<TErrorData>;
423
- response: Response;
424
- }>>;
425
- type SuccessContext<TData> = UnmaskType<Prettify<SharedHookContext & {
426
- data: TData;
427
- response: Response;
428
- }>>;
429
- type RequestErrorContext = UnmaskType<Prettify<SharedHookContext & {
430
- error: PossibleJavaScriptError;
431
- response: null;
432
- }>>;
433
- type ResponseErrorContext<TErrorData> = UnmaskType<Prettify<SharedHookContext & {
434
- error: PossibleHTTPError<TErrorData>;
435
- response: Response;
436
- }>>;
437
- type ErrorContext<TErrorData> = UnmaskType<Prettify<SharedHookContext & {
438
- error: PossibleHTTPError<TErrorData>;
439
- response: Response;
440
- }> | Prettify<SharedHookContext & {
441
- error: PossibleJavaScriptError;
442
- response: null;
443
- }>>;
444
- type RequestStreamContext = UnmaskType<Prettify<SharedHookContext & {
445
- event: StreamProgressEvent;
446
- requestInstance: Request;
447
- }>>;
448
- type ResponseStreamContext = UnmaskType<Prettify<SharedHookContext & {
449
- event: StreamProgressEvent;
450
- response: Response;
451
- }>>;
452
-
453
- type RetryCondition<TErrorData> = (context: ErrorContext<TErrorData>) => Awaitable<boolean>;
454
- interface RetryOptions<TErrorData> {
455
- /**
456
- * Keeps track of the number of times the request has already been retried
457
- * @deprecated This property is used internally to track retries. Please abstain from modifying it.
458
- */
459
- readonly ["~retryCount"]?: number;
460
- /**
461
- * Number of allowed retry attempts on HTTP errors
462
- * @default 0
463
- */
464
- retryAttempts?: number;
465
- /**
466
- * Callback whose return value determines if a request should be retried or not
467
- */
468
- retryCondition?: RetryCondition<TErrorData>;
469
- /**
470
- * Delay between retries in milliseconds
471
- * @default 1000
472
- */
473
- retryDelay?: number;
474
- /**
475
- * Maximum delay in milliseconds. Only applies to exponential strategy
476
- * @default 10000
477
- */
478
- retryMaxDelay?: number;
479
- /**
480
- * HTTP methods that are allowed to retry
481
- * @default ["GET", "POST"]
482
- */
483
- retryMethods?: Method[];
484
- /**
485
- * HTTP status codes that trigger a retry
486
- * @default [409, 425, 429, 500, 502, 503, 504]
487
- */
488
- retryStatusCodes?: Array<409 | 425 | 429 | 500 | 502 | 503 | 504 | AnyNumber>;
489
- /**
490
- * Strategy to use when retrying
491
- * @default "linear"
492
- */
493
- retryStrategy?: "exponential" | "linear";
494
- }
495
-
496
- type ModifiedRequestInit = RequestInit & {
497
- duplex?: "half";
498
- };
499
- declare const fetchSpecificKeys: (keyof RequestInit | "duplex")[];
500
- declare const getDefaultOptions: () => {
501
- baseURL: string;
502
- bodySerializer: {
503
- (value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
504
- (value: any, replacer?: (number | string)[] | null, space?: string | number): string;
505
- };
506
- dedupeStrategy: "cancel";
507
- defaultErrorMessage: string;
508
- mergedHooksExecutionMode: "parallel";
509
- mergedHooksExecutionOrder: "mainHooksAfterPlugins";
510
- responseType: "json";
511
- resultMode: "all";
512
- retryAttempts: number;
513
- retryDelay: number;
514
- retryMaxDelay: number;
515
- retryMethods: ("GET" | "POST")[];
516
- retryStatusCodes: (AnyNumber | 409 | 425 | 429 | 500 | 502 | 503 | 504)[];
517
- retryStrategy: "linear";
518
- };
519
-
520
- /**
521
- * @description Makes a type required if TSchema type is undefined or if the output type of TSchema contains undefined, otherwise keeps it as is
522
- */
523
- type MakeSchemaOptionRequired<TSchema extends StandardSchemaV1 | undefined, TObject> = undefined extends TSchema ? TObject : undefined extends InferSchemaResult<TSchema, NonNullable<unknown>> ? TObject : Required<TObject>;
524
- type JsonPrimitive = boolean | number | string | null | undefined;
525
- type SerializableObject = Record<keyof object, unknown>;
526
- type SerializableArray = Array<JsonPrimitive | SerializableArray | SerializableObject> | ReadonlyArray<JsonPrimitive | SerializableArray | SerializableObject>;
527
- type Body = UnmaskType<RequestInit["body"] | SerializableArray | SerializableObject>;
528
- type BodyOption<TSchemas extends CallApiSchemas> = MakeSchemaOptionRequired<TSchemas["body"], {
529
- /**
530
- * Body of the request, can be a object or any other supported body type.
531
- */
532
- body?: InferSchemaResult<TSchemas["body"], Body>;
533
- }>;
534
- type Method = UnmaskType<"CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE" | AnyString>;
535
- type MethodOption<TSchemas extends CallApiSchemas> = MakeSchemaOptionRequired<TSchemas["method"], {
536
- /**
537
- * HTTP method for the request.
538
- * @default "GET"
539
- */
540
- method?: InferSchemaResult<TSchemas["method"], Method>;
541
- }>;
542
- type Headers = UnmaskType<Record<"Authorization", CommonAuthorizationHeaders> | Record<"Content-Type", CommonContentTypes> | Record<CommonRequestHeaders, string | undefined> | Record<string, string | undefined> | RequestInit["headers"]>;
543
- type HeadersOption<TSchemas extends CallApiSchemas> = MakeSchemaOptionRequired<TSchemas["headers"], {
544
- /**
545
- * Headers to be used in the request.
546
- */
547
- headers?: InferSchemaResult<TSchemas["headers"], Headers>;
548
- }>;
549
- interface Register {
550
- }
551
- type GlobalMeta = Register extends {
552
- meta?: infer TMeta extends Record<string, unknown>;
553
- } ? TMeta : never;
554
- type MetaOption<TSchemas extends CallApiSchemas> = {
555
- /**
556
- * - An optional field you can fill with additional information,
557
- * to associate with the request, typically used for logging or tracing.
558
- *
559
- * - A good use case for this, would be to use the info to handle specific cases in any of the shared interceptors.
560
- *
561
- * @example
562
- * ```ts
563
- * const callMainApi = callApi.create({
564
- * baseURL: "https://main-api.com",
565
- * onResponseError: ({ response, options }) => {
566
- * if (options.meta?.userId) {
567
- * console.error(`User ${options.meta.userId} made an error`);
568
- * }
569
- * },
570
- * });
571
- *
572
- * const response = await callMainApi({
573
- * url: "https://example.com/api/data",
574
- * meta: { userId: "123" },
575
- * });
576
- * ```
577
- */
578
- meta?: InferSchemaResult<TSchemas["meta"], GlobalMeta>;
579
- };
580
- type ResultModeOption<TErrorData, TResultMode extends ResultModeUnion> = TErrorData extends false ? {
581
- resultMode: "onlySuccessWithException";
582
- } : TErrorData extends false | undefined ? {
583
- resultMode?: "onlySuccessWithException";
584
- } : undefined extends TResultMode ? {
585
- resultMode?: TResultMode;
586
- } : {
587
- resultMode: TResultMode;
588
- };
589
-
590
- type FetchSpecificKeysUnion = Exclude<(typeof fetchSpecificKeys)[number], "body" | "headers" | "method">;
591
- type CallApiRequestOptions<TSchemas extends CallApiSchemas = DefaultMoreOptions> = Prettify<BodyOption<TSchemas> & HeadersOption<TSchemas> & MethodOption<TSchemas> & Pick<ModifiedRequestInit, FetchSpecificKeysUnion>>;
592
- type CallApiRequestOptionsForHooks<TSchemas extends CallApiSchemas = DefaultMoreOptions> = Omit<CallApiRequestOptions<TSchemas>, "headers"> & {
593
- headers?: Record<string, string | undefined>;
594
- };
595
- type FetchImpl = UnmaskType<(input: string | Request | URL, init?: RequestInit) => Promise<Response>>;
596
- type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TPluginArray extends CallApiPlugin[] = DefaultPluginArray, TSchemas extends CallApiSchemas = DefaultMoreOptions> = {
597
- /**
598
- * Authorization header value.
599
- */
600
- auth?: string | Auth | null;
601
- /**
602
- * Base URL to be prepended to all request URLs
603
- */
604
- baseURL?: string;
605
- /**
606
- * Custom function to serialize the body object into a string.
607
- */
608
- bodySerializer?: (bodyData: Record<string, unknown>) => string;
609
- /**
610
- * Whether or not to clone the response, so response.json() and the like, can be read again else where.
611
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/clone
612
- * @default false
613
- */
614
- cloneResponse?: boolean;
615
- /**
616
- * Custom fetch implementation
617
- */
618
- customFetchImpl?: FetchImpl;
619
- /**
620
- * Custom request key to be used to identify a request in the fetch deduplication strategy.
621
- * @default the full request url + string formed from the request options
622
- */
623
- dedupeKey?: string;
624
- /**
625
- * Defines the deduplication strategy for the request, can be set to "none" | "defer" | "cancel".
626
- * - If set to "cancel", the previous pending request with the same request key will be cancelled and lets the new request through.
627
- * - If set to "defer", all new request with the same request key will be share the same response, until the previous one is completed.
628
- * - If set to "none", deduplication is disabled.
629
- * @default "cancel"
630
- */
631
- dedupeStrategy?: "cancel" | "defer" | "none";
632
- /**
633
- * Default error message to use if none is provided from a response.
634
- * @default "Failed to fetch data from server!"
635
- */
636
- defaultErrorMessage?: string;
637
- /**
638
- * If true, forces the calculation of the total byte size from the request or response body, in case the content-length header is not present or is incorrect.
639
- * @default false
640
- */
641
- forceCalculateStreamSize?: boolean | {
642
- request?: boolean;
643
- response?: boolean;
644
- };
645
- /**
646
- * Resolved request URL
647
- */
648
- readonly fullURL?: string;
649
- /**
650
- * Defines the mode in which the composed hooks are executed".
651
- * - If set to "parallel", main and plugin hooks will be executed in parallel.
652
- * - If set to "sequential", the plugin hooks will be executed first, followed by the main hook.
653
- * @default "parallel"
654
- */
655
- mergedHooksExecutionMode?: "parallel" | "sequential";
656
- /**
657
- * - Controls what order in which the composed hooks execute
658
- * @default "mainHooksAfterPlugins"
659
- */
660
- mergedHooksExecutionOrder?: "mainHooksAfterPlugins" | "mainHooksBeforePlugins";
661
- /**
662
- * An array of CallApi plugins. It allows you to extend the behavior of the library.
663
- */
664
- plugins?: Plugins<TPluginArray>;
665
- /**
666
- * Custom function to parse the response string
667
- */
668
- responseParser?: (responseString: string) => Awaitable<Record<string, unknown>>;
669
- /**
670
- * Expected response type, affects how response is parsed
671
- * @default "json"
672
- */
673
- responseType?: TResponseType;
674
- /**
675
- * Mode of the result, can influence how results are handled or returned.
676
- * Can be set to "all" | "onlySuccess" | "onlyError" | "onlyResponse".
677
- * @default "all"
678
- */
679
- resultMode?: TResultMode;
680
- /**
681
- * Type-safe schemas for the response validation.
682
- */
683
- schemas?: TSchemas;
684
- /**
685
- * If true or the function returns true, throws errors instead of returning them
686
- * The function is passed the error object and can be used to conditionally throw the error
687
- * @default false
688
- */
689
- throwOnError?: TThrowOnError | ((context: ErrorContext<TErrorData>) => TThrowOnError);
690
- /**
691
- * Request timeout in milliseconds
692
- */
693
- timeout?: number;
694
- /**
695
- * Custom validation functions for response validation
696
- */
697
- validators?: CallApiValidators<TData, TErrorData>;
698
- } & hooksOrHooksArray<TData, TErrorData> & Partial<InferPluginOptions<TPluginArray>> & MetaOption<TSchemas> & RetryOptions<TErrorData> & ResultModeOption<TErrorData, TResultMode> & UrlOptions<TSchemas>;
699
- type CallApiExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TPluginArray extends CallApiPlugin[] = DefaultPluginArray, TSchemas extends CallApiSchemas = DefaultMoreOptions> = ExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TPluginArray, TSchemas> & {
700
- plugins?: Plugins<TPluginArray> | ((context: {
701
- basePlugins: Plugins<TPluginArray>;
702
- }) => Plugins<TPluginArray>);
703
- schemas?: TSchemas | ((context: {
704
- baseSchemas: TSchemas;
705
- }) => TSchemas);
706
- validators?: CallApiValidators<TData, TErrorData> | ((context: {
707
- baseValidators: CallApiValidators<TData, TErrorData>;
708
- }) => CallApiValidators<TData, TErrorData>);
709
- };
710
- declare const optionsEnumToOmitFromBase: "dedupeKey"[];
711
- type BaseCallApiExtraOptions<TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseThrowOnError extends boolean = DefaultThrowOnError, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TBaseSchemas extends CallApiSchemas = DefaultMoreOptions> = Omit<Partial<CallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBasePluginArray, TBaseSchemas>>, (typeof optionsEnumToOmitFromBase)[number]> & {
712
- /**
713
- * Specifies which configuration parts should skip automatic merging between base and main configs.
714
- * Use this when you need manual control over how configs are combined.
715
- *
716
- * @values
717
- * - "all" - Disables automatic merging for both request and options
718
- * - "options" - Disables automatic merging of options only
719
- * - "request" - Disables automatic merging of request only
720
- *
721
- * @example
722
- * ```ts
723
- * const client = createFetchClient((ctx) => ({
724
- * skipAutoMergeFor: "options",
725
- *
726
- * // Now you can manually merge options in your config function
727
- * ...ctx.options,
728
- * }));
729
- * ```
730
- */
731
- skipAutoMergeFor?: "all" | "options" | "request";
732
- };
733
- type CombinedExtraOptionsWithoutHooks = Omit<BaseCallApiExtraOptions & CallApiExtraOptions, keyof Hooks>;
734
- type ResolvedHooks = Hooks;
735
- type CombinedCallApiExtraOptions = CombinedExtraOptionsWithoutHooks & ResolvedHooks;
736
- type BaseCallApiConfig<TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseThrowOnError extends boolean = DefaultThrowOnError, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TBaseSchemas extends CallApiSchemas = DefaultMoreOptions> = (CallApiRequestOptions<TBaseSchemas> & BaseCallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBasePluginArray, TBaseSchemas>) | ((context: {
737
- initURL: string;
738
- options: CallApiExtraOptions;
739
- request: CallApiRequestOptions;
740
- }) => CallApiRequestOptions<TBaseSchemas> & BaseCallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBasePluginArray, TBaseSchemas>);
741
- type CallApiConfig<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TPluginArray extends CallApiPlugin[] = DefaultPluginArray, TSchemas extends CallApiSchemas = DefaultMoreOptions> = CallApiRequestOptions<TSchemas> & CallApiExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TPluginArray, TSchemas>;
742
- type CallApiParameters<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TPluginArray extends CallApiPlugin[] = DefaultPluginArray, TSchemas extends CallApiSchemas = DefaultMoreOptions> = [
743
- initURL: InferSchemaResult<TSchemas["initURL"], InitURL>,
744
- config?: CallApiConfig<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TPluginArray, TSchemas>
745
- ];
746
- type CallApiResultSuccessVariant<TData> = {
747
- data: TData;
748
- error: null;
749
- response: Response;
750
- };
751
- type CallApiResultErrorVariant<TErrorData> = {
752
- data: null;
753
- error: PossibleHTTPError<TErrorData>;
754
- response: Response;
755
- } | {
756
- data: null;
757
- error: PossibleJavaScriptError;
758
- response: null;
759
- };
760
- type ResultModeMap<TData = DefaultDataType, TErrorData = DefaultDataType, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TComputedData = GetResponseType<TData, TResponseType>, TComputedErrorData = GetResponseType<TErrorData, TResponseType>> = UnmaskType<{
761
- all: CallApiResultSuccessVariant<TComputedData> | CallApiResultErrorVariant<TComputedErrorData>;
762
- allWithException: CallApiResultSuccessVariant<TComputedData>;
763
- allWithoutResponse: CallApiResultSuccessVariant<TComputedData>["data" | "error"] | CallApiResultErrorVariant<TComputedErrorData>["data" | "error"];
764
- onlyError: CallApiResultSuccessVariant<TComputedData>["error"] | CallApiResultErrorVariant<TComputedErrorData>["error"];
765
- onlyResponse: CallApiResultErrorVariant<TComputedErrorData>["response"] | CallApiResultSuccessVariant<TComputedData>["response"];
766
- onlyResponseWithException: CallApiResultSuccessVariant<TComputedData>["response"];
767
- onlySuccess: CallApiResultErrorVariant<TComputedErrorData>["data"] | CallApiResultSuccessVariant<TComputedData>["data"];
768
- onlySuccessWithException: CallApiResultSuccessVariant<TComputedData>["data"];
769
- }>;
770
- type ResultModeUnion = keyof ResultModeMap | undefined;
771
- 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> ? TResultMode extends "onlySuccess" ? ResultModeMap<TData, TErrorData, TResponseType>["onlySuccessWithException"] : TResultMode extends "onlyResponse" ? ResultModeMap<TData, TErrorData, TResponseType>["onlyResponseWithException"] : ResultModeMap<TData, TErrorData, TResponseType>[TResultMode] : never;
772
- type CallApiResult<TData, TErrorData, TResultMode extends ResultModeUnion, TThrowOnError extends boolean, TResponseType extends ResponseTypeUnion> = Promise<GetCallApiResult<TData, TErrorData, TResultMode, TThrowOnError, TResponseType>>;
773
-
774
- export { type CallApiResultErrorVariant as A, type BaseCallApiConfig as B, type CallApiPlugin as C, type DefaultPluginArray as D, type ErrorContext as E, type CallApiResultSuccessVariant as F, type CombinedCallApiExtraOptions as G, HTTPError as H, type InferSchemaResult as I, type Register as J, type PluginInitContext as P, type ResultModeUnion as R, type SharedHookContext as S, type ResponseTypeUnion as a, type CallApiSchemas as b, type CallApiConfig as c, type CallApiResult as d, type DefaultDataType as e, type DefaultThrowOnError as f, type DefaultMoreOptions as g, type CallApiParameters as h, definePlugin as i, getDefaultOptions as j, type RetryOptions as k, type PossibleHTTPError as l, type PossibleJavaScriptError as m, type Hooks as n, type hooksOrHooksArray as o, type RequestContext as p, type RequestErrorContext as q, type RequestStreamContext as r, type ResponseContext as s, type ResponseErrorContext as t, type ResponseStreamContext as u, type SuccessContext as v, type BaseCallApiExtraOptions as w, type CallApiExtraOptions as x, type CallApiRequestOptions as y, type CallApiRequestOptionsForHooks as z };