@zayne-labs/callapi 1.7.5 → 1.7.8

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