@zayne-labs/callapi-plugins 5.0.0 → 5.0.2

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,1918 +0,0 @@
1
- import * as _zayne_labs_callapi_utils0 from "@zayne-labs/callapi/utils";
2
- import { AnyFunction } from "@zayne-labs/toolkit-type-helpers";
3
-
4
- //#region ../callapi/dist/default-types-BUYTny8V.d.ts
5
- //#region src/constants/common.d.ts
6
- declare const fetchSpecificKeys: readonly (keyof RequestInit | "duplex")[]; //#endregion
7
- //#region src/types/type-helpers.d.ts
8
- type AnyString = string & NonNullable<unknown>;
9
- type AnyNumber = number & NonNullable<unknown>;
10
- type AnyFunction$1<TResult = unknown> = (...args: any[]) => TResult;
11
- type Prettify<TObject> = NonNullable<unknown> & { [Key in keyof TObject]: TObject[Key] };
12
- type WriteableLevel = "deep" | "shallow";
13
- /**
14
- * Makes all properties in an object type writeable (removes readonly modifiers).
15
- * Supports both shallow and deep modes, and handles special cases like arrays, tuples, and unions.
16
- * @template TObject - The object type to make writeable
17
- * @template TVariant - The level of writeable transformation ("shallow" | "deep")
18
- */
19
- type ArrayOrObject = Record<number | string | symbol, unknown> | unknown[] | readonly unknown[];
20
- type Writeable<TObject, TLevel extends WriteableLevel = "shallow"> = TObject extends ArrayOrObject ? { -readonly [Key in keyof TObject]: TLevel extends "deep" ? NonNullable<TObject[Key]> extends ArrayOrObject ? Writeable<TObject[Key], "deep"> : TObject[Key] : TObject[Key] } : TObject;
21
- type UnionToIntersection<TUnion> = (TUnion extends unknown ? (param: TUnion) => void : never) extends ((param: infer TParam) => void) ? TParam : never;
22
- type UnmaskType<TValue> = {
23
- value: TValue;
24
- }["value"];
25
- /**
26
- * @description Userland implementation of NoInfer intrinsic type, but this one doesn't show up on hover like the intrinsic one
27
- *
28
- * Prevents TypeScript from inferring `TGeneric` at this position by creating a circular dependency.
29
- * The tuple index `[TGeneric extends unknown ? 0 : never]` depends on `TGeneric`, forcing TS to
30
- * skip this site for inference and use other arguments or defaults instead.
31
- */
32
- type NoInferUnMasked<TGeneric> = [TGeneric][TGeneric extends unknown ? 0 : never];
33
- type RemoveSlashImpl<TUrl extends string, TDirection extends "leading" | "trailing"> = TDirection extends "leading" ? TUrl extends `/${infer TWithoutLeadingSlash}` ? TWithoutLeadingSlash : TUrl : TDirection extends "trailing" ? TUrl extends `${infer TWithoutTailingSlash}/` ? TWithoutTailingSlash : TUrl : never;
34
- type RemoveTrailingSlash<TUrl extends string> = RemoveSlashImpl<TUrl, "trailing">;
35
- type RemoveLeadingSlash<TUrl extends string> = RemoveSlashImpl<TUrl, "leading">;
36
- type Awaitable<TValue> = Promise<TValue> | TValue;
37
- type DistributiveOmit<TObject, TKeysToOmit extends keyof TObject> = TObject extends unknown ? Omit<TObject, TKeysToOmit> : never;
38
- 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;
39
- type CommonAuthorizationHeaders = `${"Basic" | "Bearer" | "Token"} ${string}`;
40
- 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; //#endregion
41
- //#region src/auth.d.ts
42
- type PossibleAuthValue = Awaitable<string | null | undefined>;
43
- type PossibleAuthValueOrGetter = PossibleAuthValue | (() => PossibleAuthValue);
44
- type BearerAuth = {
45
- type: "Bearer";
46
- value: PossibleAuthValueOrGetter;
47
- };
48
- type TokenAuth = {
49
- type: "Token";
50
- value: PossibleAuthValueOrGetter;
51
- };
52
- type BasicAuth = {
53
- type: "Basic";
54
- username: PossibleAuthValueOrGetter;
55
- password: PossibleAuthValueOrGetter;
56
- };
57
- /**
58
- * Custom auth
59
- *
60
- * @param prefix - prefix of the header
61
- * @param authValue - value of the header
62
- *
63
- * @example
64
- * ```ts
65
- * {
66
- * type: "Custom",
67
- * prefix: "Token",
68
- * authValue: "token"
69
- * }
70
- * ```
71
- */
72
- type CustomAuth = {
73
- type: "Custom";
74
- prefix: PossibleAuthValueOrGetter;
75
- value: PossibleAuthValueOrGetter;
76
- };
77
- type AuthOption = PossibleAuthValueOrGetter | BearerAuth | TokenAuth | BasicAuth | CustomAuth; //#endregion
78
- //#region src/constants/validation.d.ts
79
- declare const fallBackRouteSchemaKey = "@default";
80
- type FallBackRouteSchemaKey = typeof fallBackRouteSchemaKey; //#endregion
81
- //#region src/types/standard-schema.d.ts
82
- /**
83
- * The Standard Schema interface.
84
- * @see https://github.com/standard-schema/standard-schema
85
- */
86
- /** The Standard Typed interface. This is a base type extended by other specs. */
87
- interface StandardTypedV1<Input = unknown, Output = Input> {
88
- /** The Standard properties. */
89
- readonly "~standard": StandardTypedV1.Props<Input, Output>;
90
- }
91
- declare namespace StandardTypedV1 {
92
- /** The Standard Typed properties interface. */
93
- interface Props<Input = unknown, Output = Input> {
94
- /** Inferred types associated with the schema. */
95
- readonly types?: Types<Input, Output> | undefined;
96
- /** The vendor name of the schema library. */
97
- readonly vendor: string;
98
- /** The version number of the standard. */
99
- readonly version: 1;
100
- }
101
- /** The Standard Typed types interface. */
102
- interface Types<Input = unknown, Output = Input> {
103
- /** The input type of the schema. */
104
- readonly input: Input;
105
- /** The output type of the schema. */
106
- readonly output: Output;
107
- }
108
- /** Infers the input type of a Standard Typed. */
109
- type InferInput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["input"];
110
- /** Infers the output type of a Standard Typed. */
111
- type InferOutput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["output"];
112
- }
113
- /** The Standard Schema interface. */
114
- interface StandardSchemaV1<Input = unknown, Output = Input> {
115
- /** The Standard Schema properties. */
116
- readonly "~standard": StandardSchemaV1.Props<Input, Output>;
117
- }
118
- declare namespace StandardSchemaV1 {
119
- /** The Standard Schema properties interface. */
120
- interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {
121
- /** Validates unknown input values. */
122
- readonly validate: (value: unknown, options?: StandardSchemaV1.Options) => Promise<Result<Output>> | Result<Output>;
123
- }
124
- /** The result interface of the validate function. */
125
- type Result<Output> = FailureResult | SuccessResult<Output>;
126
- /** The result interface if validation succeeds. */
127
- interface SuccessResult<Output> {
128
- /** A falsy value for `issues` indicates success. */
129
- readonly issues?: undefined;
130
- /** The typed output value. */
131
- readonly value: Output;
132
- }
133
- interface Options {
134
- /** Explicit support for additional vendor-specific parameters, if needed. */
135
- readonly libraryOptions?: Record<string, unknown> | undefined;
136
- }
137
- /** The result interface if validation fails. */
138
- interface FailureResult {
139
- /** The issues of failed validation. */
140
- readonly issues: readonly Issue[];
141
- }
142
- /** The issue interface of the failure output. */
143
- interface Issue {
144
- /** The error message of the issue. */
145
- readonly message: string;
146
- /** The path of the issue, if any. */
147
- readonly path?: ReadonlyArray<PathSegment | PropertyKey> | undefined;
148
- }
149
- /** The path segment interface of the issue. */
150
- interface PathSegment {
151
- /** The key representing a path segment. */
152
- readonly key: PropertyKey;
153
- }
154
- /** The Standard types interface. */
155
- type Types<Input = unknown, Output = Input> = StandardTypedV1.Types<Input, Output>;
156
- /** Infers the input type of a Standard. */
157
- type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;
158
- /** Infers the output type of a Standard. */
159
- type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
160
- } //#endregion
161
- //#region src/validation.d.ts
162
- type ResultVariant = "infer-input" | "infer-output";
163
- type InferSchemaResult<TSchema, TFallbackResult, TResultVariant extends ResultVariant> = undefined extends TSchema ? TFallbackResult : TSchema extends StandardSchemaV1 ? TResultVariant extends "infer-input" ? StandardSchemaV1.InferInput<TSchema> : StandardSchemaV1.InferOutput<TSchema> : TSchema extends AnyFunction$1<infer TResult> ? Awaited<TResult> : TFallbackResult;
164
- type InferSchemaOutput<TSchema, TFallbackResult = unknown> = InferSchemaResult<TSchema, TFallbackResult, "infer-output">;
165
- type BooleanObject = { [Key in keyof CallApiSchema]: boolean };
166
- interface CallApiSchemaConfig {
167
- /**
168
- * The base url of the schema. By default it's the baseURL of the callApi instance.
169
- */
170
- baseURL?: "" | AnyString;
171
- /**
172
- * Disables runtime validation for the schema.
173
- */
174
- disableRuntimeValidation?: boolean | BooleanObject;
175
- /**
176
- * If `true`, the original input value will be used instead of the transformed/validated output.
177
- *
178
- * When true, the original input is returned unchanged after validation, ignoring any schema-level
179
- * transformations such as type coercion, default values, or field mapping. Only the validation
180
- * step is executed; the resulting value is discarded in favor of the raw input.
181
- */
182
- disableRuntimeValidationTransform?: boolean | BooleanObject;
183
- /**
184
- * Optional url prefix that will be substituted for the `baseURL` of the schemaConfig at runtime.
185
- *
186
- * Enables a short, stable prefix for routes while keeping the full `baseURL` centralized in config.
187
- * Keeps route definitions concise and shields them from changes to the underlying base URL.
188
- */
189
- prefix?: "" | AnyString;
190
- /**
191
- * Controls the strictness of API route validation.
192
- *
193
- * When true:
194
- * - Only routes explicitly defined in the schema will be considered valid to typescript and the runtime.
195
- * - Attempting to call routes not defined in the schema will result in both type errors and runtime validation errors.
196
- * - Useful for ensuring API calls conform exactly to your schema definition
197
- *
198
- * When false or undefined (default):
199
- * - All routes will be allowed, whether they are defined in the schema or not
200
- */
201
- strict?: boolean;
202
- }
203
- type CallApiSchemaType<TInput> = StandardSchemaV1<TInput | undefined> | ((value: TInput) => Awaitable<TInput | undefined>);
204
- interface CallApiSchema {
205
- auth?: CallApiSchemaType<AuthOption>;
206
- /**
207
- * The schema to use for validating the request body.
208
- */
209
- body?: CallApiSchemaType<Body>;
210
- /**
211
- * The schema to use for validating the response data.
212
- */
213
- data?: CallApiSchemaType<unknown>;
214
- /**
215
- * The schema to use for validating the response error data.
216
- */
217
- errorData?: CallApiSchemaType<unknown>;
218
- /**
219
- * The schema to use for validating the request headers.
220
- */
221
- headers?: CallApiSchemaType<HeadersOption>;
222
- /**
223
- * The schema to use for validating the meta option.
224
- */
225
- meta?: CallApiSchemaType<GlobalMeta>;
226
- /**
227
- * The schema to use for validating the request method.
228
- */
229
- method?: CallApiSchemaType<MethodUnion>;
230
- /**
231
- * The schema to use for validating the request url parameters.
232
- */
233
- params?: CallApiSchemaType<Params>;
234
- /**
235
- * The schema to use for validating the request url queries.
236
- */
237
- query?: CallApiSchemaType<Query>;
238
- }
239
- declare const routeKeyMethods: readonly ["delete", "get", "patch", "post", "put"];
240
- type RouteKeyMethods = (typeof routeKeyMethods)[number];
241
- type RouteKeyMethodsURLUnion = `${AtSymbol}${RouteKeyMethods}/`;
242
- type BaseSchemaRouteKeyPrefixes = FallBackRouteSchemaKey | RouteKeyMethodsURLUnion;
243
- type BaseCallApiSchemaRoutes = Partial<Record<AnyString | BaseSchemaRouteKeyPrefixes, CallApiSchema>>;
244
- type BaseCallApiSchemaAndConfig = {
245
- config?: CallApiSchemaConfig;
246
- routes: BaseCallApiSchemaRoutes;
247
- }; //#endregion
248
- //#region src/url.d.ts
249
- declare const atSymbol = "@";
250
- type AtSymbol = typeof atSymbol;
251
- type AllowedQueryParamValues = UnmaskType<boolean | number | string>;
252
- type RecordStyleParams = UnmaskType<Record<string, AllowedQueryParamValues>>;
253
- type TupleStyleParams = UnmaskType<AllowedQueryParamValues[]>;
254
- type Params = UnmaskType<RecordStyleParams | TupleStyleParams>;
255
- type Query = UnmaskType<Record<string, AllowedQueryParamValues> | URLSearchParams>;
256
- type InitURLOrURLObject = AnyString | RouteKeyMethodsURLUnion | URL;
257
- interface URLOptions {
258
- /**
259
- * Base URL for all API requests. Will only be prepended to relative URLs.
260
- *
261
- * Absolute URLs (starting with http/https) will not be prepended by the baseURL.
262
- *
263
- * @example
264
- * ```ts
265
- * // Set base URL for all requests
266
- * baseURL: "https://api.example.com/v1"
267
- *
268
- * // Then use relative URLs in requests
269
- * callApi("/users") // → https://api.example.com/v1/users
270
- * callApi("/posts/123") // → https://api.example.com/v1/posts/123
271
- *
272
- * // Environment-specific base URLs
273
- * baseURL: process.env.NODE_ENV === "production"
274
- * ? "https://api.example.com"
275
- * : "http://localhost:3000/api"
276
- * ```
277
- */
278
- baseURL?: string;
279
- /**
280
- * Resolved request URL after processing baseURL, parameters, and query strings (readonly)
281
- *
282
- * This is the final URL that will be used for the HTTP request, computed from
283
- * baseURL, initURL, params, and query parameters.
284
- *
285
- */
286
- readonly fullURL?: string;
287
- /**
288
- * The original URL string passed to the callApi instance (readonly)
289
- *
290
- * This preserves the original URL as provided, including any method modifiers like "@get/" or "@post/".
291
- *
292
- */
293
- readonly initURL?: string;
294
- /**
295
- * The URL string after normalization, with method modifiers removed(readonly)
296
- *
297
- * Method modifiers like "@get/", "@post/" are stripped to create a clean URL
298
- * for parameter substitution and final URL construction.
299
- *
300
- */
301
- readonly initURLNormalized?: string;
302
- /**
303
- * Parameters to be substituted into URL path segments.
304
- *
305
- * Supports both object-style (named parameters) and array-style (positional parameters)
306
- * for flexible URL parameter substitution.
307
- *
308
- * @example
309
- * ```typescript
310
- * // Object-style parameters (recommended)
311
- * const namedParams: URLOptions = {
312
- * initURL: "/users/:userId/posts/:postId",
313
- * params: { userId: "123", postId: "456" }
314
- * };
315
- * // Results in: /users/123/posts/456
316
- *
317
- * // Array-style parameters (positional)
318
- * const positionalParams: URLOptions = {
319
- * initURL: "/users/:userId/posts/:postId",
320
- * params: ["123", "456"] // Maps in order: userId=123, postId=456
321
- * };
322
- * // Results in: /users/123/posts/456
323
- *
324
- * // Single parameter
325
- * const singleParam: URLOptions = {
326
- * initURL: "/users/:id",
327
- * params: { id: "user-123" }
328
- * };
329
- * // Results in: /users/user-123
330
- * ```
331
- */
332
- params?: Params;
333
- /**
334
- * Query parameters to append to the URL as search parameters.
335
- *
336
- * These will be serialized into the URL query string using standard
337
- * URL encoding practices.
338
- *
339
- * @example
340
- * ```typescript
341
- * // Basic query parameters
342
- * const queryOptions: URLOptions = {
343
- * initURL: "/users",
344
- * query: {
345
- * page: 1,
346
- * limit: 10,
347
- * search: "john doe",
348
- * active: true
349
- * }
350
- * };
351
- * // Results in: /users?page=1&limit=10&search=john%20doe&active=true
352
- *
353
- * // Filtering and sorting
354
- * const filterOptions: URLOptions = {
355
- * initURL: "/products",
356
- * query: {
357
- * category: "electronics",
358
- * minPrice: 100,
359
- * maxPrice: 500,
360
- * sortBy: "price",
361
- * order: "asc"
362
- * }
363
- * };
364
- * // Results in: /products?category=electronics&minPrice=100&maxPrice=500&sortBy=price&order=asc
365
- * ```
366
- */
367
- query?: Query;
368
- } //#endregion
369
- //#region src/types/conditional-types.d.ts
370
- /**
371
- * @description Makes a type partial if the output type of TSchema is not provided or has undefined in the union, otherwise makes it required
372
- */
373
- type MakeSchemaOptionRequiredIfDefined<TSchemaOption extends CallApiSchema[keyof CallApiSchema], TObject> = undefined extends InferSchemaOutput<TSchemaOption, undefined> ? TObject : Required<TObject>;
374
- type MergeBaseWithRouteKey<TBaseURLOrPrefix extends string | undefined, TRouteKey extends string> = TBaseURLOrPrefix extends string ? TRouteKey extends `${AtSymbol}${infer TMethod extends RouteKeyMethods}/${infer TRestOfRoutKey}` ? `${AtSymbol}${TMethod}/${RemoveLeadingSlash<RemoveTrailingSlash<TBaseURLOrPrefix>>}/${RemoveLeadingSlash<TRestOfRoutKey>}` : `${TBaseURLOrPrefix}${TRouteKey}` : TRouteKey;
375
- type ApplyURLBasedConfig<TSchemaConfig extends CallApiSchemaConfig, TSchemaRouteKeys extends string> = TSchemaConfig["prefix"] extends string ? MergeBaseWithRouteKey<TSchemaConfig["prefix"], TSchemaRouteKeys> : TSchemaConfig["baseURL"] extends string ? MergeBaseWithRouteKey<TSchemaConfig["baseURL"], TSchemaRouteKeys> : TSchemaRouteKeys;
376
- type ApplyStrictConfig<TSchemaConfig extends CallApiSchemaConfig, TSchemaRouteKeys extends string> = TSchemaConfig["strict"] extends true ? TSchemaRouteKeys : // eslint-disable-next-line perfectionist/sort-union-types -- Don't sort union types
377
- TSchemaRouteKeys | Exclude<InitURLOrURLObject, RouteKeyMethodsURLUnion>;
378
- type ApplySchemaConfiguration<TSchemaConfig extends CallApiSchemaConfig, TSchemaRouteKeys extends string> = ApplyStrictConfig<TSchemaConfig, ApplyURLBasedConfig<TSchemaConfig, TSchemaRouteKeys>>;
379
- type InferAllMainRoutes<TBaseSchemaRoutes extends BaseCallApiSchemaRoutes> = Omit<TBaseSchemaRoutes, FallBackRouteSchemaKey>;
380
- type InferAllMainRouteKeys<TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TSchemaConfig extends CallApiSchemaConfig> = ApplySchemaConfiguration<TSchemaConfig, Extract<keyof InferAllMainRoutes<TBaseSchemaRoutes>, string>>;
381
- type InferInitURL<TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TSchemaConfig extends CallApiSchemaConfig> = keyof TBaseSchemaRoutes extends never ? InitURLOrURLObject : InferAllMainRouteKeys<TBaseSchemaRoutes, TSchemaConfig>;
382
- type GetCurrentRouteSchema<TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey extends string, TComputedFallBackRouteSchema = TBaseSchemaRoutes[FallBackRouteSchemaKey], TComputedCurrentRouteSchema = TBaseSchemaRoutes[TCurrentRouteSchemaKey], TComputedRouteSchema extends CallApiSchema = NonNullable<Omit<TComputedFallBackRouteSchema, keyof TComputedCurrentRouteSchema> & TComputedCurrentRouteSchema>> = TComputedRouteSchema extends CallApiSchema ? Writeable<TComputedRouteSchema, "deep"> : CallApiSchema;
383
- type JsonPrimitive = boolean | number | string | null | undefined;
384
- type SerializableObject = Record<PropertyKey, unknown>;
385
- type SerializableArray = Array<JsonPrimitive | SerializableObject> | ReadonlyArray<JsonPrimitive | SerializableObject>;
386
- type Body = UnmaskType<Exclude<RequestInit["body"], undefined> | SerializableArray | SerializableObject>;
387
- type InferBodyOption<TSchema extends CallApiSchema> = MakeSchemaOptionRequiredIfDefined<TSchema["body"], {
388
- /**
389
- * Body of the request, can be a object or any other supported body type.
390
- */
391
- body?: InferSchemaOutput<TSchema["body"], Body>;
392
- }>;
393
- type MethodUnion = UnmaskType<"CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE" | AnyString>;
394
- type ExtractMethodFromURL<TInitURL> = string extends TInitURL ? MethodUnion : TInitURL extends `${AtSymbol}${infer TMethod extends RouteKeyMethods}/${string}` ? Uppercase<TMethod> : MethodUnion;
395
- type InferMethodOption<TSchema extends CallApiSchema, TInitURL extends InitURLOrURLObject> = MakeSchemaOptionRequiredIfDefined<TSchema["method"], {
396
- /**
397
- * HTTP method for the request.
398
- * @default "GET"
399
- */
400
- method?: InferSchemaOutput<TSchema["method"], ExtractMethodFromURL<TInitURL>>;
401
- }>;
402
- type HeadersOption = UnmaskType<Headers | Record<"Authorization", CommonAuthorizationHeaders | undefined> | Record<"Content-Type", CommonContentTypes | undefined> | Record<CommonRequestHeaders, string | undefined> | Record<string, string | undefined> | Array<[string, string]>>;
403
- type InferHeadersOption<TSchema extends CallApiSchema> = MakeSchemaOptionRequiredIfDefined<TSchema["headers"], {
404
- /**
405
- * Headers to be used in the request.
406
- */
407
- headers?: InferSchemaOutput<TSchema["headers"], HeadersOption> | ((context: {
408
- baseHeaders: Extract<HeadersOption, Record<string, unknown>>;
409
- }) => InferSchemaOutput<TSchema["headers"], HeadersOption>);
410
- }>;
411
- type InferRequestOptions<TSchema extends CallApiSchema, TInitURL extends InferInitURL<BaseCallApiSchemaRoutes, CallApiSchemaConfig>> = InferBodyOption<TSchema> & InferHeadersOption<TSchema> & InferMethodOption<TSchema, TInitURL>;
412
- type InferMetaOption<TSchema extends CallApiSchema, TCallApiContext extends CallApiContext> = MakeSchemaOptionRequiredIfDefined<TSchema["meta"], {
413
- /**
414
- * - An optional field you can fill with additional information,
415
- * to associate with the request, typically used for logging or tracing.
416
- *
417
- * - A good use case for this, would be to use the info to handle specific cases in any of the shared interceptors.
418
- *
419
- * @example
420
- * ```ts
421
- * const callMainApi = callApi.create({
422
- * baseURL: "https://main-api.com",
423
- * onResponseError: ({ response, options }) => {
424
- * if (options.meta?.userId) {
425
- * console.error(`User ${options.meta.userId} made an error`);
426
- * }
427
- * },
428
- * });
429
- *
430
- * const response = await callMainApi({
431
- * url: "https://example.com/api/data",
432
- * meta: { userId: "123" },
433
- * });
434
- * ```
435
- */
436
- meta?: InferSchemaOutput<TSchema["meta"], TCallApiContext["Meta"]>;
437
- }>;
438
- type InferAuthOption<TSchema extends CallApiSchema> = MakeSchemaOptionRequiredIfDefined<TSchema["auth"], {
439
- /**
440
- * Automatically add an Authorization header value.
441
- *
442
- * Supports multiple authentication patterns:
443
- * - String: Direct authorization header value
444
- * - Auth object: Structured authentication configuration
445
- *
446
- * @example
447
- * ```ts
448
- * // Bearer auth
449
- * const response = await callMainApi({
450
- * url: "https://example.com/api/data",
451
- * auth: "123456",
452
- * });
453
- *
454
- * // Bearer auth
455
- * const response = await callMainApi({
456
- * url: "https://example.com/api/data",
457
- * auth: {
458
- * type: "Bearer",
459
- * value: "123456",
460
- * },
461
- })
462
- *
463
- * // Token auth
464
- * const response = await callMainApi({
465
- * url: "https://example.com/api/data",
466
- * auth: {
467
- * type: "Token",
468
- * value: "123456",
469
- * },
470
- * });
471
- *
472
- * // Basic auth
473
- * const response = await callMainApi({
474
- * url: "https://example.com/api/data",
475
- * auth: {
476
- * type: "Basic",
477
- * username: "username",
478
- * password: "password",
479
- * },
480
- * });
481
- *
482
- * ```
483
- */
484
- auth?: InferSchemaOutput<TSchema["auth"], AuthOption>;
485
- }>;
486
- type InferQueryOption<TSchema extends CallApiSchema> = MakeSchemaOptionRequiredIfDefined<TSchema["query"], {
487
- /**
488
- * Parameters to be appended to the URL (i.e: /:id)
489
- */
490
- query?: InferSchemaOutput<TSchema["query"], Query>;
491
- }>;
492
- type EmptyString = "";
493
- type EmptyTuple = readonly [];
494
- type StringTuple = readonly string[];
495
- type PossibleParamNamePatterns = `${string}:${string}` | `${string}{${string}}${"" | AnyString}`;
496
- type ExtractRouteParamNames<TCurrentRoute, TParamNamesAccumulator extends StringTuple = EmptyTuple> = TCurrentRoute extends PossibleParamNamePatterns ? TCurrentRoute extends `${infer TRoutePrefix}:${infer TParamAndRemainingRoute}` ? TParamAndRemainingRoute extends `${infer TCurrentParam}/${infer TRemainingRoute}` ? TCurrentParam extends EmptyString ? ExtractRouteParamNames<`${TRoutePrefix}/${TRemainingRoute}`, TParamNamesAccumulator> : ExtractRouteParamNames<`${TRoutePrefix}/${TRemainingRoute}`, [...TParamNamesAccumulator, TCurrentParam]> : TParamAndRemainingRoute extends `${infer TCurrentParam}` ? TCurrentParam extends EmptyString ? ExtractRouteParamNames<TRoutePrefix, TParamNamesAccumulator> : ExtractRouteParamNames<TRoutePrefix, [...TParamNamesAccumulator, TCurrentParam]> : ExtractRouteParamNames<TRoutePrefix, TParamNamesAccumulator> : TCurrentRoute extends `${infer TRoutePrefix}{${infer TCurrentParam}}${infer TRemainingRoute}` ? TCurrentParam extends EmptyString ? ExtractRouteParamNames<`${TRoutePrefix}${TRemainingRoute}`, TParamNamesAccumulator> : ExtractRouteParamNames<`${TRoutePrefix}${TRemainingRoute}`, [...TParamNamesAccumulator, TCurrentParam]> : TParamNamesAccumulator : TParamNamesAccumulator;
497
- type ConvertParamNamesToRecord<TParamNames extends StringTuple> = Prettify<TParamNames extends (readonly [infer TFirstParamName extends string, ...infer TRemainingParamNames extends StringTuple]) ? Record<TFirstParamName, AllowedQueryParamValues> & ConvertParamNamesToRecord<TRemainingParamNames> : NonNullable<unknown>>;
498
- type ConvertParamNamesToTuple<TParamNames extends StringTuple> = TParamNames extends readonly [string, ...infer TRemainingParamNames extends StringTuple] ? [AllowedQueryParamValues, ...ConvertParamNamesToTuple<TRemainingParamNames>] : [];
499
- type InferParamsFromRoute<TCurrentRoute> = ExtractRouteParamNames<TCurrentRoute> extends StringTuple ? ExtractRouteParamNames<TCurrentRoute> extends EmptyTuple ? Params : ConvertParamNamesToRecord<ExtractRouteParamNames<TCurrentRoute>> | ConvertParamNamesToTuple<ExtractRouteParamNames<TCurrentRoute>> : Params;
500
- type MakeParamsOptionRequired<TParamsSchemaOption extends CallApiSchema["params"], TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey extends string, TObject> = MakeSchemaOptionRequiredIfDefined<TParamsSchemaOption, Params extends InferParamsFromRoute<TCurrentRouteSchemaKey> ? TObject : TCurrentRouteSchemaKey extends Extract<keyof TBaseSchemaRoutes, TCurrentRouteSchemaKey> ? undefined extends InferSchemaOutput<TParamsSchemaOption, null> ? TObject : Required<TObject> : TObject>;
501
- type InferParamsOption<TSchema extends CallApiSchema, TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey extends string> = MakeParamsOptionRequired<TSchema["params"], TBaseSchemaRoutes, TCurrentRouteSchemaKey, {
502
- /**
503
- * Parameters to be appended to the URL (i.e: /:id)
504
- */
505
- params?: InferSchemaOutput<TSchema["params"], InferParamsFromRoute<TCurrentRouteSchemaKey>>;
506
- }>;
507
- type InferExtraOptions<TSchema extends CallApiSchema, TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey extends string, TCallApiContext extends CallApiContext> = InferAuthOption<TSchema> & InferMetaOption<TSchema, TCallApiContext> & InferParamsOption<TSchema, TBaseSchemaRoutes, TCurrentRouteSchemaKey> & InferQueryOption<TSchema>;
508
- type ResultModeOption<TErrorData, TResultMode extends ResultModeType> = TErrorData extends false ? {
509
- resultMode: "onlyData";
510
- } : TErrorData extends false | undefined ? {
511
- resultMode?: "onlyData";
512
- } : {
513
- resultMode?: TResultMode;
514
- };
515
- type ThrowOnErrorBoolean = boolean;
516
- type ThrowOnErrorType<TErrorData, TThrowOnError extends ThrowOnErrorBoolean> = TThrowOnError | ((context: ErrorContext<{
517
- ErrorData: TErrorData;
518
- }>) => TThrowOnError);
519
- type ThrowOnErrorOption<TErrorData, TThrowOnError extends ThrowOnErrorBoolean> = TErrorData extends false ? {
520
- throwOnError: true;
521
- } : TErrorData extends false | undefined ? {
522
- throwOnError?: true;
523
- } : {
524
- throwOnError?: ThrowOnErrorType<TErrorData, TThrowOnError>;
525
- }; //#endregion
526
- //#region src/retry.d.ts
527
- declare const defaultRetryStatusCodesLookup: () => Readonly<{
528
- 408: "Request Timeout";
529
- 409: "Conflict";
530
- 425: "Too Early";
531
- 429: "Too Many Requests";
532
- 500: "Internal Server Error";
533
- 502: "Bad Gateway";
534
- 503: "Service Unavailable";
535
- 504: "Gateway Timeout";
536
- }>;
537
- type RetryStatusCodes = UnmaskType<AnyNumber | keyof ReturnType<typeof defaultRetryStatusCodesLookup>>;
538
- type RetryCondition<TErrorData> = (context: ErrorContext<{
539
- ErrorData: TErrorData;
540
- }>) => Awaitable<boolean>;
541
- interface RetryOptions<TErrorData> {
542
- /**
543
- * Keeps track of the number of times the request has already been retried
544
- * @internal
545
- * @deprecated **NOTE**: This property is used internally to track retries. Please abstain from modifying it.
546
- */
547
- readonly ["~retryAttemptCount"]?: number;
548
- /**
549
- * Number of allowed retry attempts on HTTP errors
550
- * @default 0
551
- */
552
- retryAttempts?: number;
553
- /**
554
- * Callback whose return value determines if a request should be retried or not
555
- */
556
- retryCondition?: RetryCondition<TErrorData>;
557
- /**
558
- * Delay between retries in milliseconds
559
- * @default 1000
560
- */
561
- retryDelay?: number | ((currentAttemptCount: number) => number);
562
- /**
563
- * Maximum delay in milliseconds. Only applies to exponential strategy
564
- * @default 10000
565
- */
566
- retryMaxDelay?: number;
567
- /**
568
- * HTTP methods that are allowed to retry
569
- * @default ["GET", "POST"]
570
- */
571
- retryMethods?: MethodUnion[];
572
- /**
573
- * HTTP status codes that trigger a retry
574
- */
575
- retryStatusCodes?: RetryStatusCodes[];
576
- /**
577
- * Strategy to use when retrying
578
- * @default "linear"
579
- */
580
- retryStrategy?: "exponential" | "linear";
581
- } //#endregion
582
- //#region src/refetch.d.ts
583
- interface RefetchOptions {
584
- /**
585
- * Tracks the number of times refetch has been called
586
- * @internal
587
- * @deprecated **NOTE**: This property is used internally to track refetch calls. Please abstain from modifying it.
588
- */
589
- readonly ["~refetchCount"]?: number;
590
- /**
591
- * Maximum number of times refetch can be called from error hooks.
592
- *
593
- * Prevents infinite loops when refetch is called repeatedly in error hooks.
594
- * When the limit is reached, refetch will throw an error instead of retrying.
595
- *
596
- * @default 1
597
- *
598
- * @example
599
- * ```ts
600
- * // Allow up to 5 refetch attempts
601
- * refetchAttempts: 5
602
- *
603
- * // Disable refetch limit
604
- * refetchAttempts: Infinity
605
- *
606
- * // Strict limit of 1 refetch
607
- * refetchAttempts: 1
608
- * ```
609
- */
610
- refetchAttempts?: number;
611
- }
612
- type RefetchFn = (overrides?: Pick<RefetchOptions, "refetchAttempts">) => Promise<CallApiResultLoose<unknown, unknown> | null>; //#endregion
613
- //#region src/stream.d.ts
614
- type StreamProgressEvent = {
615
- /**
616
- * Current chunk of data being streamed
617
- */
618
- chunk: Uint8Array;
619
- /**
620
- * Progress in percentage
621
- */
622
- progress: number;
623
- /**
624
- * Total size of data in bytes
625
- */
626
- totalBytes: number;
627
- /**
628
- * Amount of data transferred so far
629
- */
630
- transferredBytes: number;
631
- }; //#endregion
632
- //#region src/hooks.d.ts
633
- type CallApiRequestOptionsForHooks = Omit<CallApiRequestOptions, "headers"> & {
634
- headers: Record<"Authorization" | "Content-Type" | CommonRequestHeaders, string | undefined>;
635
- };
636
- type CallApiExtraOptionsForHooks<TCallApiContext extends CallApiContext = DefaultCallApiContext> = Hooks & Omit<CallApiExtraOptions<TCallApiContext>, keyof Hooks> & {
637
- refetch: RefetchFn;
638
- };
639
- interface Hooks<TCallApiContext extends CallApiContext = DefaultCallApiContext> {
640
- /**
641
- * Hook called when any error occurs within the request/response lifecycle.
642
- *
643
- * This is a unified error handler that catches both request errors (network failures,
644
- * timeouts, etc.) and response errors (HTTP error status codes). It's essentially
645
- * a combination of `onRequestError` and `onResponseError` hooks.
646
- *
647
- * @param context - Error context containing error details, request info, and response (if available)
648
- * @returns Promise or void - Hook can be async or sync
649
- */
650
- onError?: (context: ErrorContext<TCallApiContext>) => Awaitable<unknown>;
651
- /**
652
- * Hook called before the HTTP request is sent and before any internal processing of the request object begins.
653
- *
654
- * This is the ideal place to modify request headers, add authentication,
655
- * implement request logging, or perform any setup before the network call.
656
- *
657
- * @param context - Request context with mutable request object and configuration
658
- * @returns Promise or void - Hook can be async or sync
659
- *
660
- */
661
- onRequest?: (context: RequestContext<TCallApiContext>) => Awaitable<unknown>;
662
- /**
663
- * Hook called when an error occurs during the fetch request itself.
664
- *
665
- * This handles network-level errors like connection failures, timeouts,
666
- * DNS resolution errors, or other issues that prevent getting an HTTP response.
667
- * Note that HTTP error status codes (4xx, 5xx) are handled by `onResponseError`.
668
- *
669
- * @param context - Request error context with error details and null response
670
- * @returns Promise or void - Hook can be async or sync
671
- */
672
- onRequestError?: (context: RequestErrorContext<TCallApiContext>) => Awaitable<unknown>;
673
- /**
674
- * Hook called just before the HTTP request is sent and after the request has been processed.
675
- *
676
- * @param context - Request context with mutable request object and configuration
677
- */
678
- onRequestReady?: (context: RequestContext<TCallApiContext>) => Awaitable<unknown>;
679
- /**
680
- * Hook called during upload stream progress tracking.
681
- *
682
- * This hook is triggered when uploading data (like file uploads) and provides
683
- * progress information about the upload. Useful for implementing progress bars
684
- * or upload status indicators.
685
- *
686
- * @param context - Request stream context with progress event and request instance
687
- * @returns Promise or void - Hook can be async or sync
688
- *
689
- */
690
- onRequestStream?: (context: RequestStreamContext<TCallApiContext>) => Awaitable<unknown>;
691
- /**
692
- * Hook called when any HTTP response is received from the API.
693
- *
694
- * This hook is triggered for both successful (2xx) and error (4xx, 5xx) responses.
695
- * It's useful for response logging, metrics collection, or any processing that
696
- * should happen regardless of response status.
697
- *
698
- * @param context - Response context with either success data or error information
699
- * @returns Promise or void - Hook can be async or sync
700
- *
701
- */
702
- onResponse?: (context: ResponseContext<TCallApiContext>) => Awaitable<unknown>;
703
- /**
704
- * Hook called when an HTTP error response (4xx, 5xx) is received from the API.
705
- *
706
- * This handles server-side errors where an HTTP response was successfully received
707
- * but indicates an error condition. Different from `onRequestError` which handles
708
- * network-level failures.
709
- *
710
- * @param context - Response error context with HTTP error details and response
711
- * @returns Promise or void - Hook can be async or sync
712
- */
713
- onResponseError?: (context: ResponseErrorContext<TCallApiContext>) => Awaitable<unknown>;
714
- /**
715
- * Hook called during download stream progress tracking.
716
- *
717
- * This hook is triggered when downloading data (like file downloads) and provides
718
- * progress information about the download. Useful for implementing progress bars
719
- * or download status indicators.
720
- *
721
- * @param context - Response stream context with progress event and response
722
- * @returns Promise or void - Hook can be async or sync
723
- *
724
- */
725
- onResponseStream?: (context: ResponseStreamContext<TCallApiContext>) => Awaitable<unknown>;
726
- /**
727
- * Hook called when a request is being retried.
728
- *
729
- * This hook is triggered before each retry attempt, providing information about
730
- * the previous failure and the current retry attempt number. Useful for implementing
731
- * custom retry logic, exponential backoff, or retry logging.
732
- *
733
- * @param context - Retry context with error details and retry attempt count
734
- * @returns Promise or void - Hook can be async or sync
735
- *
736
- */
737
- onRetry?: (context: RetryContext<TCallApiContext>) => Awaitable<unknown>;
738
- /**
739
- * Hook called when a successful response (2xx status) is received from the API.
740
- *
741
- * This hook is triggered only for successful responses and provides access to
742
- * the parsed response data. Ideal for success logging, caching, or post-processing
743
- * of successful API responses.
744
- *
745
- * @param context - Success context with parsed response data and response object
746
- * @returns Promise or void - Hook can be async or sync
747
- *
748
- */
749
- onSuccess?: (context: SuccessContext<TCallApiContext>) => Awaitable<unknown>;
750
- /**
751
- * Hook called when a validation error occurs.
752
- *
753
- * This hook is triggered when request or response data fails validation against
754
- * a defined schema. It provides access to the validation error details and can
755
- * be used for custom error handling, logging, or fallback behavior.
756
- *
757
- * @param context - Validation error context with error details and response (if available)
758
- * @returns Promise or void - Hook can be async or sync
759
- *
760
- */
761
- onValidationError?: (context: ValidationErrorContext<TCallApiContext>) => Awaitable<unknown>;
762
- }
763
- type HooksOrHooksArray<TCallApiContext extends NoInfer<CallApiContext> = DefaultCallApiContext> = { [Key in keyof Hooks<TCallApiContext>]: Hooks<TCallApiContext>[Key] | Array<Hooks<TCallApiContext>[Key]> };
764
- interface HookConfigOptions {
765
- /**
766
- * Controls the execution mode of all composed hooks (main + plugin hooks).
767
- *
768
- * - **"parallel"**: All hooks execute simultaneously via Promise.all() for better performance
769
- * - **"sequential"**: All hooks execute one by one in registration order via await in a loop
770
- *
771
- * This affects how ALL hooks execute together, regardless of their source (main or plugin).
772
- *
773
- * @default "parallel"
774
- */
775
- hooksExecutionMode?: "parallel" | "sequential";
776
- }
777
- type RequestContext<TCallApiContext extends Pick<CallApiContext, "InferredExtraOptions" | "Meta"> = DefaultCallApiContext> = {
778
- /**
779
- * Base configuration object passed to createFetchClient.
780
- *
781
- * Contains the foundational configuration that applies to all requests
782
- * made by this client instance, such as baseURL, default headers, and
783
- * global options.
784
- */
785
- baseConfig: Exclude<BaseCallApiConfig, AnyFunction$1>;
786
- /**
787
- * Instance-specific configuration object passed to the callApi instance.
788
- *
789
- * Contains configuration specific to this particular API call, which
790
- * can override or extend the base configuration.
791
- */
792
- config: CallApiConfig;
793
- /**
794
- * Merged options combining base config, instance config, and default options.
795
- *
796
- * This is the final resolved configuration that will be used for the request,
797
- * with proper precedence applied (instance > base > defaults).
798
- */
799
- options: CallApiExtraOptionsForHooks<TCallApiContext>;
800
- /**
801
- * Merged request object ready to be sent.
802
- *
803
- * Contains the final request configuration including URL, method, headers,
804
- * body, and other fetch options. This object can be modified in onRequest
805
- * hooks to customize the outgoing request.
806
- */
807
- request: CallApiRequestOptionsForHooks;
808
- };
809
- type SuccessContext<TCallApiContext extends Pick<CallApiContext, "Data" | "InferredExtraOptions" | "Meta"> = DefaultCallApiContext> = DistributiveOmit<CallApiResultSuccessVariant<TCallApiContext["Data"]>, "error"> & RequestContext<TCallApiContext>;
810
- type ResponseContext<TCallApiContext extends Pick<CallApiContext, "Data" | "ErrorData" | "InferredExtraOptions" | "Meta"> = DefaultCallApiContext> = RequestContext<TCallApiContext> & (Prettify<CallApiResultSuccessVariant<TCallApiContext["Data"]>> | Prettify<Extract<CallApiResultErrorVariant<TCallApiContext["ErrorData"]>, {
811
- error: PossibleHTTPError<TCallApiContext["ErrorData"]>;
812
- }>>);
813
- type RequestStreamContext<TCallApiContext extends Pick<CallApiContext, "InferredExtraOptions" | "Meta"> = DefaultCallApiContext> = RequestContext<TCallApiContext> & {
814
- event: StreamProgressEvent;
815
- requestInstance: Request;
816
- };
817
- type ResponseStreamContext<TCallApiContext extends Pick<CallApiContext, "InferredExtraOptions" | "Meta"> = DefaultCallApiContext> = RequestContext<TCallApiContext> & {
818
- event: StreamProgressEvent;
819
- response: Response;
820
- };
821
- type ErrorContext<TCallApiContext extends Pick<CallApiContext, "ErrorData" | "InferredExtraOptions" | "Meta"> = DefaultCallApiContext> = DistributiveOmit<CallApiResultErrorVariant<TCallApiContext["ErrorData"]>, "data"> & RequestContext<TCallApiContext>;
822
- type ValidationErrorContext<TCallApiContext extends Pick<CallApiContext, "InferredExtraOptions" | "Meta"> = DefaultCallApiContext> = Extract<ErrorContext<TCallApiContext>, {
823
- error: PossibleValidationError;
824
- }> & RequestContext<TCallApiContext>;
825
- type RequestErrorContext<TCallApiContext extends Pick<CallApiContext, "InferredExtraOptions" | "Meta"> = DefaultCallApiContext> = Extract<ErrorContext<TCallApiContext>, {
826
- error: PossibleJavaScriptError;
827
- }> & RequestContext<TCallApiContext>;
828
- type ResponseErrorContext<TCallApiContext extends Pick<CallApiContext, "ErrorData" | "InferredExtraOptions" | "Meta"> = DefaultCallApiContext> = Extract<ErrorContext<TCallApiContext>, {
829
- error: PossibleHTTPError<TCallApiContext["ErrorData"]>;
830
- }> & RequestContext<TCallApiContext>;
831
- type RetryContext<TCallApiContext extends Pick<CallApiContext, "ErrorData" | "InferredExtraOptions" | "Meta"> = DefaultCallApiContext> = ErrorContext<TCallApiContext> & {
832
- retryAttemptCount: number;
833
- }; //#endregion
834
- //#region src/dedupe.d.ts
835
- type DedupeStrategyUnion = UnmaskType<"cancel" | "defer" | "none">;
836
- type DedupeOptions = {
837
- /**
838
- * Controls the scope of request deduplication caching.
839
- *
840
- * - `"global"`: Shares deduplication cache across all `createFetchClient` instances with the same `dedupeCacheScopeKey`.
841
- * Useful for applications with multiple API clients that should share deduplication state.
842
- * - `"local"`: Limits deduplication to requests within the same `createFetchClient` instance.
843
- * Provides better isolation and is recommended for most use cases.
844
- *
845
- *
846
- * **Real-world Scenarios:**
847
- * - Use `"global"` when you have multiple API clients (user service, auth service, etc.) that might make overlapping requests
848
- * - Use `"local"` (default) for single-purpose clients or when you want strict isolation between different parts of your app
849
- *
850
- * @example
851
- * ```ts
852
- * // Local scope - each client has its own deduplication cache
853
- * const userClient = createFetchClient({ baseURL: "/api/users" });
854
- * const postClient = createFetchClient({ baseURL: "/api/posts" });
855
- * // These clients won't share deduplication state
856
- *
857
- * // Global scope - share cache across related clients
858
- * const userClient = createFetchClient({
859
- * baseURL: "/api/users",
860
- * dedupeCacheScope: "global",
861
- * });
862
- * const postClient = createFetchClient({
863
- * baseURL: "/api/posts",
864
- * dedupeCacheScope: "global",
865
- * });
866
- * // These clients will share deduplication state
867
- * ```
868
- *
869
- * @default "local"
870
- */
871
- dedupeCacheScope?: "global" | "local";
872
- /**
873
- * Unique namespace for the global deduplication cache when using `dedupeCacheScope: "global"`.
874
- *
875
- * This creates logical groupings of deduplication caches. All instances with the same key
876
- * will share the same cache namespace, allowing fine-grained control over which clients
877
- * share deduplication state.
878
- *
879
- * **Best Practices:**
880
- * - Use descriptive names that reflect the logical grouping (e.g., "user-service", "analytics-api")
881
- * - Keep scope keys consistent across related API clients
882
- * - Consider using different scope keys for different environments (dev, staging, prod)
883
- * - Avoid overly broad scope keys that might cause unintended cache sharing
884
- *
885
- * **Cache Management:**
886
- * - Each scope key maintains its own independent cache
887
- * - Caches are automatically cleaned up when no references remain
888
- * - Consider the memory implications of multiple global scopes
889
- *
890
- * @example
891
- * ```ts
892
- * // Group related API clients together
893
- * const userClient = createFetchClient({
894
- * baseURL: "/api/users",
895
- * dedupeCacheScope: "global",
896
- * dedupeCacheScopeKey: "user-service"
897
- * });
898
- * const profileClient = createFetchClient({
899
- * baseURL: "/api/profiles",
900
- * dedupeCacheScope: "global",
901
- * dedupeCacheScopeKey: "user-service" // Same scope - will share cache
902
- * });
903
- *
904
- * // Separate analytics client with its own cache
905
- * const analyticsClient = createFetchClient({
906
- * baseURL: "/api/analytics",
907
- * dedupeCacheScope: "global",
908
- * dedupeCacheScopeKey: "analytics-service" // Different scope
909
- * });
910
- *
911
- * // Environment-specific scoping
912
- * const apiClient = createFetchClient({
913
- * dedupeCacheScope: "global",
914
- * dedupeCacheScopeKey: `api-${process.env.NODE_ENV}` // "api-development", "api-production", etc.
915
- * });
916
- * ```
917
- *
918
- * @default "default"
919
- */
920
- dedupeCacheScopeKey?: "default" | AnyString | ((context: RequestContext) => string | undefined);
921
- /**
922
- * Custom key generator for request deduplication.
923
- *
924
- * Override the default key generation strategy to control exactly which requests
925
- * are considered duplicates. The default key combines URL, method, body, and
926
- * relevant headers (excluding volatile ones like 'Date', 'Authorization', etc.).
927
- *
928
- * **Default Key Generation:**
929
- * The auto-generated key includes:
930
- * - Full request URL (including query parameters)
931
- * - HTTP method (GET, POST, etc.)
932
- * - Request body (for POST/PUT/PATCH requests)
933
- * - Stable headers (excludes Date, Authorization, User-Agent, etc.)
934
- *
935
- * **Custom Key Best Practices:**
936
- * - Include only the parts of the request that should affect deduplication
937
- * - Avoid including volatile data (timestamps, random IDs, etc.)
938
- * - Consider performance - simpler keys are faster to compute and compare
939
- * - Ensure keys are deterministic for the same logical request
940
- * - Use consistent key formats across your application
941
- *
942
- * **Performance Considerations:**
943
- * - Function-based keys are computed on every request - keep them lightweight
944
- * - String keys are fastest but least flexible
945
- * - Consider caching expensive key computations if needed
946
- *
947
- * @example
948
- * ```ts
949
- * import { callApi } from "@zayne-labs/callapi";
950
- *
951
- * // Simple static key - useful for singleton requests
952
- * const config = callApi("/api/config", {
953
- * dedupeKey: "app-config",
954
- * dedupeStrategy: "defer" // Share the same config across all requests
955
- * });
956
- *
957
- * // URL and method only - ignore headers and body
958
- * const userData = callApi("/api/user/123", {
959
- * dedupeKey: (context) => `${context.options.method}:${context.options.fullURL}`
960
- * });
961
- *
962
- * // Include specific headers in deduplication
963
- * const apiCall = callApi("/api/data", {
964
- * dedupeKey: (context) => {
965
- * const authHeader = context.request.headers.get("Authorization");
966
- * return `${context.options.fullURL}-${authHeader}`;
967
- * }
968
- * });
969
- *
970
- * // User-specific deduplication
971
- * const userSpecificCall = callApi("/api/dashboard", {
972
- * dedupeKey: (context) => {
973
- * const userId = context.options.fullURL.match(/user\/(\d+)/)?.[1];
974
- * return `dashboard-${userId}`;
975
- * }
976
- * });
977
- *
978
- * // Ignore certain query parameters
979
- * const searchCall = callApi("/api/search?q=test&timestamp=123456", {
980
- * dedupeKey: (context) => {
981
- * const url = new URL(context.options.fullURL);
982
- * url.searchParams.delete("timestamp"); // Remove volatile param
983
- * return `search:${url.toString()}`;
984
- * }
985
- * });
986
- * ```
987
- *
988
- * @default Auto-generated from request details
989
- */
990
- dedupeKey?: string | ((context: RequestContext) => string | undefined);
991
- /**
992
- * Strategy for handling duplicate requests. Can be a static string or callback function.
993
- *
994
- * **Available Strategies:**
995
- * - `"cancel"`: Cancel previous request when new one starts (good for search)
996
- * - `"defer"`: Share response between duplicate requests (good for config loading)
997
- * - `"none"`: No deduplication, all requests execute independently
998
- *
999
- * @example
1000
- * ```ts
1001
- * // Static strategies
1002
- * const searchClient = createFetchClient({
1003
- * dedupeStrategy: "cancel" // Cancel previous searches
1004
- * });
1005
- *
1006
- * const configClient = createFetchClient({
1007
- * dedupeStrategy: "defer" // Share config across components
1008
- * });
1009
- *
1010
- * // Dynamic strategy based on request
1011
- * const smartClient = createFetchClient({
1012
- * dedupeStrategy: (context) => {
1013
- * return context.options.method === "GET" ? "defer" : "cancel";
1014
- * }
1015
- * });
1016
- *
1017
- * // Search-as-you-type with cancel strategy
1018
- * const handleSearch = async (query: string) => {
1019
- * try {
1020
- * const { data } = await callApi("/api/search", {
1021
- * method: "POST",
1022
- * body: { query },
1023
- * dedupeStrategy: "cancel",
1024
- * dedupeKey: "search" // Cancel previous searches, only latest one goes through
1025
- * });
1026
- *
1027
- * updateSearchResults(data);
1028
- * } catch (error) {
1029
- * if (error.name === "AbortError") {
1030
- * // Previous search cancelled - (expected behavior)
1031
- * return;
1032
- * }
1033
- * console.error("Search failed:", error);
1034
- * }
1035
- * };
1036
- *
1037
- * ```
1038
- *
1039
- * @default "cancel"
1040
- */
1041
- dedupeStrategy?: DedupeStrategyUnion | ((context: RequestContext) => DedupeStrategyUnion);
1042
- }; //#endregion
1043
- //#region src/middlewares.d.ts
1044
- type FetchImpl = UnmaskType<(input: string | Request | URL, init?: RequestInit) => Promise<Response>>;
1045
- type FetchMiddlewareContext<TCallApiContext extends CallApiContext> = RequestContext<TCallApiContext> & {
1046
- fetchImpl: FetchImpl;
1047
- };
1048
- interface Middlewares<TCallApiContext extends NoInfer<CallApiContext> = DefaultCallApiContext> {
1049
- /**
1050
- * Wraps the fetch implementation to intercept requests at the network layer.
1051
- *
1052
- * Takes a context object containing the current fetch function and returns a new fetch function.
1053
- * Use it to cache responses, add logging, handle offline mode, or short-circuit requests etc.
1054
- * Multiple middleware compose in order: plugins → base config → per-request.
1055
- *
1056
- * Unlike `customFetchImpl`, middleware can call through to the original fetch.
1057
- *
1058
- * @example
1059
- * ```ts
1060
- * // Cache responses
1061
- * const cache = new Map();
1062
- *
1063
- * fetchMiddleware: (ctx) => async (input, init) => {
1064
- * const key = input.toString();
1065
- *
1066
- * const cachedResponse = cache.get(key);
1067
- *
1068
- * if (cachedResponse) {
1069
- * return cachedResponse.clone();
1070
- * }
1071
- *
1072
- * const response = await ctx.fetchImpl(input, init);
1073
- * cache.set(key, response.clone());
1074
- *
1075
- * return response;
1076
- * }
1077
- *
1078
- * // Handle offline
1079
- * fetchMiddleware: (ctx) => async (...parameters) => {
1080
- * if (!navigator.onLine) {
1081
- * return new Response('{"error": "offline"}', { status: 503 });
1082
- * }
1083
- *
1084
- * return ctx.fetchImpl(...parameters);
1085
- * }
1086
- * ```
1087
- */
1088
- fetchMiddleware?: (context: FetchMiddlewareContext<TCallApiContext>) => FetchImpl;
1089
- } //#endregion
1090
- //#region src/utils/external/error.d.ts
1091
- type HTTPErrorDetails<TErrorData> = Pick<CallApiExtraOptions, "defaultHTTPErrorMessage"> & {
1092
- errorData: TErrorData;
1093
- response: Response;
1094
- };
1095
- declare class HTTPError<TErrorData = Record<string, unknown>> extends Error {
1096
- errorData: HTTPErrorDetails<TErrorData>["errorData"];
1097
- readonly httpErrorSymbol: symbol;
1098
- name: "HTTPError";
1099
- response: HTTPErrorDetails<TErrorData>["response"];
1100
- constructor(errorDetails: HTTPErrorDetails<TErrorData>, errorOptions?: ErrorOptions);
1101
- /**
1102
- * @description Checks if the given error is an instance of HTTPError
1103
- * @param error - The error to check
1104
- * @returns true if the error is an instance of HTTPError, false otherwise
1105
- */
1106
- static isError<TErrorData>(error: unknown): error is HTTPError<TErrorData>;
1107
- }
1108
- type SafeExtract<TUnion, TKey extends TUnion> = Extract<TUnion, TKey>;
1109
- type ValidationErrorDetails = {
1110
- /**
1111
- * The cause of the validation error.
1112
- *
1113
- * It's either the name the schema for which validation failed, or the name of the schema config option that led to the validation error.
1114
- */
1115
- issueCause: "toFormData" | "toQueryString" | "unknown" | `schemaConfig-(${SafeExtract<keyof CallApiSchemaConfig, "strict">})` | keyof CallApiSchema;
1116
- /**
1117
- * The issues that caused the validation error.
1118
- */
1119
- issues: readonly StandardSchemaV1.Issue[];
1120
- /**
1121
- * The response from server, if any.
1122
- */
1123
- response: Response | null;
1124
- };
1125
- declare class ValidationError extends Error {
1126
- errorData: ValidationErrorDetails["issues"];
1127
- issueCause: ValidationErrorDetails["issueCause"];
1128
- name: "ValidationError";
1129
- response: ValidationErrorDetails["response"];
1130
- readonly validationErrorSymbol: symbol;
1131
- constructor(details: ValidationErrorDetails, errorOptions?: ErrorOptions);
1132
- /**
1133
- * @description Checks if the given error is an instance of ValidationError
1134
- * @param error - The error to check
1135
- * @returns true if the error is an instance of ValidationError, false otherwise
1136
- */
1137
- static isError(error: unknown): error is ValidationError;
1138
- } //#endregion
1139
- //#region src/types/common.d.ts
1140
- interface Register {}
1141
- type GlobalMeta = Register extends {
1142
- meta?: infer TMeta extends DefaultMetaObject;
1143
- } ? TMeta : DefaultMetaObject;
1144
- interface CallApiContext {
1145
- Data?: DefaultDataType;
1146
- ErrorData?: DefaultDataType;
1147
- InferredExtraOptions?: unknown;
1148
- Meta?: DefaultMetaObject;
1149
- ResultMode?: ResultModeType;
1150
- }
1151
- type OverrideCallApiContext<TFullCallApiContext extends CallApiContext, TOverrideCallApiContext extends CallApiContext> = Omit<TFullCallApiContext, keyof TOverrideCallApiContext> & TOverrideCallApiContext;
1152
- type FetchSpecificKeysUnion = Exclude<(typeof fetchSpecificKeys)[number], "body" | "headers" | "method">;
1153
- type ModifiedRequestInit = RequestInit & {
1154
- duplex?: "half";
1155
- };
1156
- type CallApiRequestOptions = {
1157
- /**
1158
- * Body of the request, can be a object or any other supported body type.
1159
- */
1160
- body?: Body;
1161
- /**
1162
- * Headers to be used in the request.
1163
- */
1164
- headers?: HeadersOption;
1165
- /**
1166
- * HTTP method for the request.
1167
- * @default "GET"
1168
- */
1169
- method?: MethodUnion;
1170
- } & Pick<ModifiedRequestInit, FetchSpecificKeysUnion>;
1171
- type SharedExtraOptions<TCallApiContext extends CallApiContext = DefaultCallApiContext, TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeType = ResultModeType, TThrowOnError extends ThrowOnErrorBoolean = DefaultThrowOnError, TResponseType extends ResponseTypeType = ResponseTypeType, TPluginArray extends CallApiPlugin[] = DefaultPluginArray, TComputedMergedPluginExtraOptions = Partial<InferPluginExtraOptions<TPluginArray> & InferSchemaOutput<TCallApiContext["InferredExtraOptions"], TCallApiContext["InferredExtraOptions"]>>, TComputedCallApiContext extends CallApiContext = OverrideCallApiContext<TCallApiContext, {
1172
- Data: TData;
1173
- ErrorData: TErrorData;
1174
- InferredExtraOptions: TComputedMergedPluginExtraOptions;
1175
- ResultMode: TResultMode;
1176
- }>> = DedupeOptions & HookConfigOptions & HooksOrHooksArray<NoInferUnMasked<TComputedCallApiContext>> & Middlewares<NoInferUnMasked<TComputedCallApiContext>> & RefetchOptions & ResultModeOption<TErrorData, TResultMode> & RetryOptions<TErrorData> & TComputedMergedPluginExtraOptions & ThrowOnErrorOption<TErrorData, TThrowOnError> & URLOptions & {
1177
- /**
1178
- * Automatically add an Authorization header value.
1179
- *
1180
- * Supports multiple authentication patterns:
1181
- * - String: Direct authorization header value
1182
- * - Auth object: Structured authentication configuration
1183
- *
1184
- * ```
1185
- */
1186
- auth?: AuthOption;
1187
- /**
1188
- * Custom function to serialize request body objects into strings.
1189
- *
1190
- * Useful for custom serialization formats or when the default JSON
1191
- * serialization doesn't meet your needs.
1192
- *
1193
- * @example
1194
- * ```ts
1195
- * // Custom form data serialization
1196
- * bodySerializer: (data) => {
1197
- * const formData = new FormData();
1198
- * Object.entries(data).forEach(([key, value]) => {
1199
- * formData.append(key, String(value));
1200
- * });
1201
- * return formData.toString();
1202
- * }
1203
- *
1204
- * // XML serialization
1205
- * bodySerializer: (data) => {
1206
- * return `<request>${Object.entries(data)
1207
- * .map(([key, value]) => `<${key}>${value}</${key}>`)
1208
- * .join('')}</request>`;
1209
- * }
1210
- *
1211
- * // Custom JSON with specific formatting
1212
- * bodySerializer: (data) => JSON.stringify(data, null, 2)
1213
- * ```
1214
- */
1215
- bodySerializer?: (bodyData: Record<string, unknown>) => string;
1216
- /**
1217
- * Whether to clone the response so it can be read multiple times.
1218
- *
1219
- * By default, response streams can only be consumed once. Enable this when you need
1220
- * to read the response in multiple places (e.g., in hooks and main code).
1221
- *
1222
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/clone
1223
- * @default false
1224
- */
1225
- cloneResponse?: boolean;
1226
- /**
1227
- * Custom fetch implementation to replace the default fetch function.
1228
- *
1229
- * Useful for testing, adding custom behavior, or using alternative HTTP clients
1230
- * that implement the fetch API interface.
1231
- *
1232
- * @example
1233
- * ```ts
1234
- * // Use node-fetch in Node.js environments
1235
- * import fetch from 'node-fetch';
1236
- *
1237
- * // Mock fetch for testing
1238
- * customFetchImpl: async (url, init) => {
1239
- * return new Response(JSON.stringify({ mocked: true }), {
1240
- * status: 200,
1241
- * headers: { 'Content-Type': 'application/json' }
1242
- * });
1243
- * }
1244
- *
1245
- * // Add custom logging to all requests
1246
- * customFetchImpl: async (url, init) => {
1247
- * console.log(`Fetching: ${url}`);
1248
- * const response = await fetch(url, init);
1249
- * console.log(`Response: ${response.status}`);
1250
- * return response;
1251
- * }
1252
- *
1253
- * // Use with custom HTTP client
1254
- * customFetchImpl: async (url, init) => {
1255
- * // Convert to your preferred HTTP client format
1256
- * return await customHttpClient.request({
1257
- * url: url.toString(),
1258
- * method: init?.method || 'GET',
1259
- * headers: init?.headers,
1260
- * body: init?.body
1261
- * });
1262
- * }
1263
- * ```
1264
- */
1265
- customFetchImpl?: FetchImpl;
1266
- /**
1267
- * Default HTTP error message when server doesn't provide one.
1268
- *
1269
- * Can be a static string or a function that receives error context
1270
- * to generate dynamic error messages based on the response.
1271
- *
1272
- * @default "Failed to fetch data from server!"
1273
- *
1274
- * @example
1275
- * ```ts
1276
- * // Static error message
1277
- * defaultHTTPErrorMessage: "API request failed. Please try again."
1278
- *
1279
- * // Dynamic error message based on status code
1280
- * defaultHTTPErrorMessage: ({ response }) => {
1281
- * switch (response.status) {
1282
- * case 401: return "Authentication required. Please log in.";
1283
- * case 403: return "Access denied. Insufficient permissions.";
1284
- * case 404: return "Resource not found.";
1285
- * case 429: return "Too many requests. Please wait and try again.";
1286
- * case 500: return "Server error. Please contact support.";
1287
- * default: return `Request failed with status ${response.status}`;
1288
- * }
1289
- * }
1290
- *
1291
- * // Include error data in message
1292
- * defaultHTTPErrorMessage: ({ errorData, response }) => {
1293
- * const userMessage = errorData?.message || "Unknown error occurred";
1294
- * return `${userMessage} (Status: ${response.status})`;
1295
- * }
1296
- * ```
1297
- */
1298
- defaultHTTPErrorMessage?: string | ((context: Pick<HTTPError<TErrorData>, "errorData" | "response">) => string);
1299
- /**
1300
- * Forces calculation of total byte size from request body streams.
1301
- *
1302
- * Useful when the Content-Length header is missing or incorrect, and you need
1303
- * accurate size information for progress tracking.
1304
- *
1305
- * @default false
1306
- *
1307
- */
1308
- forcefullyCalculateRequestStreamSize?: boolean;
1309
- /**
1310
- * Optional metadata field for associating additional information with requests.
1311
- *
1312
- * Useful for logging, tracing, or handling specific cases in shared interceptors.
1313
- * The meta object is passed through to all hooks and can be accessed in error handlers.
1314
- *
1315
- * @example
1316
- * ```ts
1317
- * const callMainApi = callApi.create({
1318
- * baseURL: "https://main-api.com",
1319
- * onResponseError: ({ response, options }) => {
1320
- * if (options.meta?.userId) {
1321
- * console.error(`User ${options.meta.userId} made an error`);
1322
- * }
1323
- * },
1324
- * });
1325
- *
1326
- * const response = await callMainApi({
1327
- * url: "https://example.com/api/data",
1328
- * meta: { userId: "123" },
1329
- * });
1330
- *
1331
- * // Use case: Request tracking
1332
- * const result = await callMainApi({
1333
- * url: "https://example.com/api/data",
1334
- * meta: {
1335
- * requestId: generateId(),
1336
- * source: "user-dashboard",
1337
- * priority: "high"
1338
- * }
1339
- * });
1340
- *
1341
- * // Use case: Feature flags
1342
- * const client = callApi.create({
1343
- * baseURL: "https://api.example.com",
1344
- * meta: {
1345
- * features: ["newUI", "betaFeature"],
1346
- * experiment: "variantA"
1347
- * }
1348
- * });
1349
- * ```
1350
- */
1351
- meta?: TCallApiContext["Meta"] extends DefaultMetaObject ? TCallApiContext["Meta"] : DefaultCallApiContext["Meta"];
1352
- /**
1353
- * Custom function to parse response strings into actual value instead of the default response.json().
1354
- *
1355
- * Useful when you need custom parsing logic for specific response formats.
1356
- *
1357
- * @example
1358
- * ```ts
1359
- * responseParser: (text) => {
1360
- * return JSON.parse(text);
1361
- * }
1362
- *
1363
- * // Parse XML responses
1364
- * responseParser: (text) => {
1365
- * const parser = new DOMParser();
1366
- * const doc = parser.parseFromString(text, "text/xml");
1367
- * return xmlToObject(doc);
1368
- * }
1369
- *
1370
- * // Parse CSV responses
1371
- * responseParser: (text) => {
1372
- * const lines = text.split('\n');
1373
- * const headers = lines[0].split(',');
1374
- * const data = lines.slice(1).map(line => {
1375
- * const values = line.split(',');
1376
- * return headers.reduce((obj, header, index) => {
1377
- * obj[header] = values[index];
1378
- * return obj;
1379
- * }, {});
1380
- * });
1381
- * return data;
1382
- * }
1383
- *
1384
- * ```
1385
- */
1386
- responseParser?: ResponseParser<TData>;
1387
- /**
1388
- * Expected response type, determines how the response body is parsed.
1389
- *
1390
- * Different response types trigger different parsing methods:
1391
- * - **"json"**: Parses as JSON using response.json()
1392
- * - **"text"**: Returns as plain text using response.text()
1393
- * - **"blob"**: Returns as Blob using response.blob()
1394
- * - **"arrayBuffer"**: Returns as ArrayBuffer using response.arrayBuffer()
1395
- * - **"stream"**: Returns the response body stream directly
1396
- *
1397
- * @default "json"
1398
- *
1399
- * @example
1400
- * ```ts
1401
- * // JSON API responses (default)
1402
- * responseType: "json"
1403
- *
1404
- * // Plain text responses
1405
- * responseType: "text"
1406
- * // Usage: const csvData = await callApi("/export.csv", { responseType: "text" });
1407
- *
1408
- * // File downloads
1409
- * responseType: "blob"
1410
- * // Usage: const file = await callApi("/download/file.pdf", { responseType: "blob" });
1411
- *
1412
- * // Binary data
1413
- * responseType: "arrayBuffer"
1414
- * // Usage: const buffer = await callApi("/binary-data", { responseType: "arrayBuffer" });
1415
- *
1416
- * // Streaming responses
1417
- * responseType: "stream"
1418
- * // Usage: const stream = await callApi("/large-dataset", { responseType: "stream" });
1419
- * ```
1420
- */
1421
- responseType?: TResponseType;
1422
- /**
1423
- * Dictates how CallApi processes and returns the final result
1424
- *
1425
- - **"all"** (default): Returns `{ data, error, response }`. Standard lifecycle.
1426
- - **"onlyData"**: Returns only the data from the response.
1427
- - **"onlyResponse"**: Returns only the `Response` object.
1428
- - **"fetchApi"**: Also returns only the `Response` object, but also skips parsing of the response body internally and data/errorData schema validation.
1429
- - **"withoutResponse"**: Returns `{ data, error }`. Standard lifecycle, but omits the `response` property.
1430
- *
1431
- *
1432
- * **Note:**
1433
- * By default, simplified modes (`"onlyData"`, `"onlyResponse"`, `"fetchApi"`) do not throw errors.
1434
- * Success/failure should be handled via hooks or by checking the return value (e.g., `if (data)` or `if (response?.ok)`).
1435
- * To force an exception instead, set `throwOnError: true`.
1436
- *
1437
- *
1438
- * @default "all"
1439
- *
1440
- */
1441
- resultMode?: TResultMode;
1442
- /**
1443
- * Controls whether errors are thrown as exceptions or returned in the result.
1444
- *
1445
- * Can be a boolean or a function that receives the error and decides whether to throw.
1446
- * When true, errors are thrown as exceptions instead of being returned in the result object.
1447
- *
1448
- * @default false
1449
- *
1450
- * @example
1451
- * ```ts
1452
- * // Always throw errors
1453
- * throwOnError: true
1454
- * try {
1455
- * const data = await callApi("/users");
1456
- * console.log("Users:", data);
1457
- * } catch (error) {
1458
- * console.error("Request failed:", error);
1459
- * }
1460
- *
1461
- * // Never throw errors (default)
1462
- * throwOnError: false
1463
- * const { data, error } = await callApi("/users");
1464
- * if (error) {
1465
- * console.error("Request failed:", error);
1466
- * }
1467
- *
1468
- * // Conditionally throw based on error type
1469
- * throwOnError: (error) => {
1470
- * // Throw on client errors (4xx) but not server errors (5xx)
1471
- * return error.response?.status >= 400 && error.response?.status < 500;
1472
- * }
1473
- *
1474
- * // Throw only on specific status codes
1475
- * throwOnError: (error) => {
1476
- * const criticalErrors = [401, 403, 404];
1477
- * return criticalErrors.includes(error.response?.status);
1478
- * }
1479
- *
1480
- * // Throw on validation errors but not network errors
1481
- * throwOnError: (error) => {
1482
- * return error.type === "validation";
1483
- * }
1484
- * ```
1485
- */
1486
- throwOnError?: ThrowOnErrorType<TErrorData, TThrowOnError>;
1487
- /**
1488
- * Request timeout in milliseconds. Request will be aborted if it takes longer.
1489
- *
1490
- * Useful for preventing requests from hanging indefinitely and providing
1491
- * better user experience with predictable response times.
1492
- *
1493
- * @example
1494
- * ```ts
1495
- * // 5 second timeout
1496
- * timeout: 5000
1497
- *
1498
- * // Different timeouts for different endpoints
1499
- * const quickApi = createFetchClient({ timeout: 3000 }); // 3s for fast endpoints
1500
- * const slowApi = createFetchClient({ timeout: 30000 }); // 30s for slow operations
1501
- *
1502
- * // Per-request timeout override
1503
- * await callApi("/quick-data", { timeout: 1000 });
1504
- * await callApi("/slow-report", { timeout: 60000 });
1505
- *
1506
- * // No timeout (use with caution)
1507
- * timeout: 0
1508
- * ```
1509
- */
1510
- timeout?: number;
1511
- };
1512
- type BaseCallApiExtraOptions<TBaseCallApiContext extends CallApiContext = DefaultCallApiContext, TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeType = ResultModeType, TBaseThrowOnError extends ThrowOnErrorBoolean = DefaultThrowOnError, TBaseResponseType extends ResponseTypeType = ResponseTypeType, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TBaseSchemaAndConfig extends BaseCallApiSchemaAndConfig = BaseCallApiSchemaAndConfig> = SharedExtraOptions<TBaseCallApiContext, TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBasePluginArray> & {
1513
- /**
1514
- * Array of base CallApi plugins to extend library functionality.
1515
- *
1516
- * Base plugins are applied to all instances created from this base configuration
1517
- * and provide foundational functionality like authentication, logging, or caching.
1518
- *
1519
- * @example
1520
- * ```ts
1521
- * // Add logging plugin
1522
- *
1523
- * // Create base client with common plugins
1524
- * const callApi = createFetchClient({
1525
- * baseURL: "https://api.example.com",
1526
- * plugins: [loggerPlugin({ enabled: true })]
1527
- * });
1528
- *
1529
- * // All requests inherit base plugins
1530
- * await callApi("/users");
1531
- * await callApi("/posts");
1532
- *
1533
- * ```
1534
- */
1535
- plugins?: TBasePluginArray;
1536
- /**
1537
- * Base validation schemas for the client configuration.
1538
- *
1539
- * Defines validation rules for requests and responses that apply to all
1540
- * instances created from this base configuration. Provides type safety
1541
- * and runtime validation for API interactions.
1542
- */
1543
- schema?: TBaseSchemaAndConfig;
1544
- /**
1545
- * Controls which configuration parts skip automatic merging between base and instance configs.
1546
- *
1547
- * By default, CallApi automatically merges base configuration with instance configuration.
1548
- * This option allows you to disable automatic merging for specific parts when you need
1549
- * manual control over how configurations are combined.
1550
- *
1551
- * @enum
1552
- * - **"all"**: Disables automatic merging for both request options and extra options
1553
- * - **"options"**: Disables automatic merging of extra options only (hooks, plugins, etc.)
1554
- * - **"request"**: Disables automatic merging of request options only (headers, body, etc.)
1555
- *
1556
- * @example
1557
- * ```ts
1558
- * // Skip all automatic merging - full manual control
1559
- * const client = callApi.create((ctx) => ({
1560
- * skipAutoMergeFor: "all",
1561
- *
1562
- * // Manually decide what to merge
1563
- * baseURL: ctx.options.baseURL, // Keep base URL
1564
- * timeout: 5000, // Override timeout
1565
- * headers: {
1566
- * ...ctx.request.headers, // Merge headers manually
1567
- * "X-Custom": "value" // Add custom header
1568
- * }
1569
- * }));
1570
- *
1571
- * // Skip options merging - manual plugin/hook control
1572
- * const client = callApi.create((ctx) => ({
1573
- * skipAutoMergeFor: "options",
1574
- *
1575
- * // Manually control which plugins to use
1576
- * plugins: [
1577
- * ...ctx.options.plugins?.filter(p => p.name !== "unwanted") || [],
1578
- * customPlugin
1579
- * ],
1580
- *
1581
- * // Request options still auto-merge
1582
- * method: "POST"
1583
- * }));
1584
- *
1585
- * // Skip request merging - manual request control
1586
- * const client = callApi.create((ctx) => ({
1587
- * skipAutoMergeFor: "request",
1588
- *
1589
- * // Extra options still auto-merge (plugins, hooks, etc.)
1590
- *
1591
- * // Manually control request options
1592
- * headers: {
1593
- * "Content-Type": "application/json",
1594
- * // Don't merge base headers
1595
- * },
1596
- * method: ctx.request.method || "GET"
1597
- * }));
1598
- *
1599
- * // Use case: Conditional merging based on request
1600
- * const client = createFetchClient((ctx) => ({
1601
- * skipAutoMergeFor: "options",
1602
- *
1603
- * // Only use auth plugin for protected routes
1604
- * plugins: ctx.initURL.includes("/protected/")
1605
- * ? [...(ctx.options.plugins || []), authPlugin]
1606
- * : ctx.options.plugins?.filter(p => p.name !== "auth") || []
1607
- * }));
1608
- * ```
1609
- */
1610
- skipAutoMergeFor?: "all" | "options" | "request";
1611
- };
1612
- type InferExtendSchemaContext<TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey extends string> = {
1613
- baseSchemaRoutes: TBaseSchemaRoutes;
1614
- currentRouteSchema: GetCurrentRouteSchema<TBaseSchemaRoutes, TCurrentRouteSchemaKey>;
1615
- currentRouteSchemaKey: TCurrentRouteSchemaKey;
1616
- };
1617
- type GetExtendSchemaConfigContext<TBaseSchemaConfig extends CallApiSchemaConfig> = {
1618
- baseSchemaConfig: TBaseSchemaConfig;
1619
- };
1620
- type InferExtendPluginContext<TBasePluginArray extends CallApiPlugin[]> = {
1621
- basePlugins: TBasePluginArray;
1622
- };
1623
- type CallApiExtraOptions<TCallApiContext extends CallApiContext = DefaultCallApiContext, TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeType = ResultModeType, TThrowOnError extends ThrowOnErrorBoolean = DefaultThrowOnError, TResponseType extends ResponseTypeType = ResponseTypeType, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TPluginArray extends CallApiPlugin[] = DefaultPluginArray, TBaseSchemaRoutes extends BaseCallApiSchemaRoutes = BaseCallApiSchemaRoutes, TSchema extends CallApiSchema = CallApiSchema, TBaseSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TCurrentRouteSchemaKey extends string = string> = SharedExtraOptions<TCallApiContext, TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TPluginArray> & {
1624
- /**
1625
- * Array of instance-specific CallApi plugins or a function to configure plugins.
1626
- *
1627
- * Instance plugins are added to the base plugins and provide functionality
1628
- * specific to this particular API instance. Can be a static array or a function
1629
- * that receives base plugins and returns the instance plugins.
1630
- *
1631
- */
1632
- plugins?: TPluginArray | ((context: InferExtendPluginContext<TBasePluginArray>) => TPluginArray);
1633
- /**
1634
- * For instance-specific validation schemas
1635
- *
1636
- * Defines validation rules specific to this API instance, extending or overriding the base schema.
1637
- *
1638
- * Can be a static schema object or a function that receives base schema context and returns instance schemas.
1639
- *
1640
- */
1641
- schema?: TSchema | ((context: InferExtendSchemaContext<TBaseSchemaRoutes, TCurrentRouteSchemaKey>) => TSchema);
1642
- /**
1643
- * Instance-specific schema configuration or a function to configure schema behavior.
1644
- *
1645
- * Controls how validation schemas are applied and behave for this specific API instance.
1646
- * Can override base schema configuration or extend it with instance-specific validation rules.
1647
- *
1648
- */
1649
- schemaConfig?: TSchemaConfig | ((context: GetExtendSchemaConfigContext<TBaseSchemaConfig>) => TSchemaConfig);
1650
- };
1651
- type InstanceContext = {
1652
- initURL: string;
1653
- options: CallApiExtraOptions;
1654
- request: CallApiRequestOptions;
1655
- };
1656
- type BaseCallApiConfig<TBaseCallApiContext extends CallApiContext = DefaultCallApiContext, TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeType = ResultModeType, TBaseThrowOnError extends ThrowOnErrorBoolean = DefaultThrowOnError, TBaseResponseType extends ResponseTypeType = ResponseTypeType, TBaseSchemaAndConfig extends BaseCallApiSchemaAndConfig = BaseCallApiSchemaAndConfig, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TComputedBaseConfig = BaseCallApiExtraOptions<TBaseCallApiContext, TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBasePluginArray, TBaseSchemaAndConfig>> = (CallApiRequestOptions & TComputedBaseConfig) | ((context: InstanceContext) => CallApiRequestOptions & TComputedBaseConfig);
1657
- type CallApiConfig<TCallApiContext extends CallApiContext = DefaultCallApiContext, TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeType = ResultModeType, TThrowOnError extends ThrowOnErrorBoolean = DefaultThrowOnError, TResponseType extends ResponseTypeType = ResponseTypeType, TBaseSchemaRoutes extends BaseCallApiSchemaRoutes = BaseCallApiSchemaRoutes, TSchema extends CallApiSchema = CallApiSchema, TBaseSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TInitURL extends InitURLOrURLObject = InitURLOrURLObject, TCurrentRouteSchemaKey extends string = string, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TPluginArray extends CallApiPlugin[] = DefaultPluginArray> = InferExtraOptions<TSchema, TBaseSchemaRoutes, TCurrentRouteSchemaKey, TCallApiContext> & InferRequestOptions<TSchema, TInitURL> & Omit<CallApiExtraOptions<TCallApiContext, TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TBasePluginArray, TPluginArray, TBaseSchemaRoutes, TSchema, TBaseSchemaConfig, TSchemaConfig, TCurrentRouteSchemaKey>, keyof InferExtraOptions<CallApiSchema, BaseCallApiSchemaRoutes, string, CallApiContext>> & Omit<CallApiRequestOptions, keyof InferRequestOptions<CallApiSchema, string>>;
1658
- type CallApiResultLoose<TData, TErrorData, TResultMode extends ResultModeType = ResultModeType, TThrowOnError extends ThrowOnErrorBoolean = ThrowOnErrorBoolean> = InferCallApiResult<TData, TErrorData, TResultMode, TThrowOnError>; //#endregion
1659
- //#region src/result.d.ts
1660
- type ResponseParser<TData> = (text: string) => Awaitable<TData>;
1661
- declare const getResponseType: <TData>(response: Response, responseParser: ResponseParser<TData>) => {
1662
- arrayBuffer: () => Promise<ArrayBuffer>;
1663
- blob: () => Promise<Blob>;
1664
- formData: () => Promise<FormData>;
1665
- json: () => Promise<TData>;
1666
- stream: () => ReadableStream<Uint8Array<ArrayBuffer>> | null;
1667
- text: () => Promise<string>;
1668
- };
1669
- type InitResponseTypeMap<TData = unknown> = ReturnType<typeof getResponseType<TData>>;
1670
- type ResponseTypeUnion = keyof InitResponseTypeMap;
1671
- type ResponseTypePlaceholder = null;
1672
- type ResponseTypeType = ResponseTypePlaceholder | ResponseTypeUnion;
1673
- type CallApiResultSuccessVariant<TData> = {
1674
- data: NoInferUnMasked<TData>;
1675
- error: null;
1676
- response: Response;
1677
- };
1678
- type PossibleJavaScriptError = UnmaskType<{
1679
- errorData: false;
1680
- message: string;
1681
- name: "AbortError" | "Error" | "SyntaxError" | "TimeoutError" | "TypeError" | AnyString;
1682
- originalError: DOMException | Error | SyntaxError | TypeError;
1683
- }>;
1684
- type PossibleHTTPError<TErrorData> = UnmaskType<{
1685
- errorData: NoInferUnMasked<TErrorData>;
1686
- message: string;
1687
- name: "HTTPError";
1688
- originalError: HTTPError;
1689
- }>;
1690
- type PossibleValidationError = UnmaskType<{
1691
- errorData: ValidationError["errorData"];
1692
- issueCause: ValidationError["issueCause"];
1693
- message: string;
1694
- name: "ValidationError";
1695
- originalError: ValidationError;
1696
- }>;
1697
- type CallApiResultErrorVariant<TErrorData> = {
1698
- data: null;
1699
- error: PossibleHTTPError<TErrorData>;
1700
- response: Response;
1701
- } | {
1702
- data: null;
1703
- error: PossibleJavaScriptError;
1704
- response: Response | null;
1705
- } | {
1706
- data: null;
1707
- error: PossibleValidationError;
1708
- response: Response | null;
1709
- };
1710
- type CallApiResultSuccessOrErrorVariant<TData, TError> = CallApiResultErrorVariant<TError> | CallApiResultSuccessVariant<TData>;
1711
- type GetCallApiResult<TThrowOnError extends ThrowOnErrorBoolean, TResultWithException extends CallApiResultSuccessVariant<unknown>, TResultWithoutException extends CallApiResultSuccessOrErrorVariant<unknown, unknown>> = TThrowOnError extends true ? TResultWithException : TResultWithoutException;
1712
- type ResultModeMap<TData = DefaultDataType, TErrorData = DefaultDataType, TThrowOnError extends ThrowOnErrorBoolean = DefaultThrowOnError, TComputedResult extends GetCallApiResult<TThrowOnError, CallApiResultSuccessVariant<TData>, CallApiResultSuccessOrErrorVariant<TData, TErrorData>> = GetCallApiResult<TThrowOnError, CallApiResultSuccessVariant<TData>, CallApiResultSuccessOrErrorVariant<TData, TErrorData>>> = UnmaskType<{
1713
- all: TComputedResult;
1714
- fetchApi: TComputedResult["response"];
1715
- onlyData: TComputedResult["data"];
1716
- onlyResponse: TComputedResult["response"];
1717
- withoutResponse: Prettify<DistributiveOmit<TComputedResult, "response">>;
1718
- }>;
1719
- type ResultModePlaceholder = null;
1720
- type ResultModeUnion = keyof ResultModeMap;
1721
- type ResultModeType = ResultModePlaceholder | ResultModeUnion;
1722
- type InferCallApiResult<TData, TErrorData, TResultMode extends ResultModeType, TThrowOnError extends ThrowOnErrorBoolean, TComputedResultModeMapWithException extends ResultModeMap<TData, TErrorData, true> = ResultModeMap<TData, TErrorData, true>, TComputedResultModeMapWithoutException extends ResultModeMap<TData, TErrorData, TThrowOnError> = ResultModeMap<TData, TErrorData, TThrowOnError>> = TErrorData extends false ? TComputedResultModeMapWithException["onlyData"] : TErrorData extends false | undefined ? TComputedResultModeMapWithException["onlyData"] : ResultModePlaceholder extends TResultMode ? TComputedResultModeMapWithoutException["all"] : TResultMode extends ResultModeUnion ? TComputedResultModeMapWithoutException[TResultMode] : never; //#endregion
1723
- //#region src/plugins.d.ts
1724
- type PluginSetupContext<TCallApiContext extends CallApiContext = DefaultCallApiContext> = RequestContext<TCallApiContext> & {
1725
- initURL: string;
1726
- };
1727
- type PluginInitResult<TCallApiContext extends CallApiContext = DefaultCallApiContext> = Partial<Omit<PluginSetupContext<TCallApiContext>, "initURL" | "request"> & {
1728
- initURL: InitURLOrURLObject;
1729
- request: CallApiRequestOptions;
1730
- }>;
1731
- type GetDefaultDataTypeForPlugins<TData> = DefaultDataType extends TData ? never : TData;
1732
- type PluginHooks<TCallApiContext extends CallApiContext = DefaultCallApiContext> = HooksOrHooksArray<OverrideCallApiContext<TCallApiContext, {
1733
- Data: GetDefaultDataTypeForPlugins<TCallApiContext["Data"]>;
1734
- ErrorData: GetDefaultDataTypeForPlugins<TCallApiContext["ErrorData"]>;
1735
- }>>;
1736
- type PluginMiddlewares<TCallApiContext extends CallApiContext = DefaultCallApiContext> = Middlewares<OverrideCallApiContext<TCallApiContext, {
1737
- Data: GetDefaultDataTypeForPlugins<TCallApiContext["Data"]>;
1738
- ErrorData: GetDefaultDataTypeForPlugins<TCallApiContext["ErrorData"]>;
1739
- }>>;
1740
- interface CallApiPlugin<TCallApiContext extends CallApiContext = DefaultCallApiContext> {
1741
- /**
1742
- * Defines additional options that can be passed to callApi
1743
- */
1744
- defineExtraOptions?: () => TCallApiContext["InferredExtraOptions"];
1745
- /**
1746
- * A description for the plugin
1747
- */
1748
- description?: string;
1749
- /**
1750
- * Hooks for the plugin
1751
- */
1752
- hooks?: PluginHooks<TCallApiContext> | ((context: PluginSetupContext<TCallApiContext>) => Awaitable<PluginHooks<TCallApiContext>> | Awaitable<void>);
1753
- /**
1754
- * A unique id for the plugin
1755
- */
1756
- id: string;
1757
- /**
1758
- * Middlewares that for the plugin
1759
- */
1760
- middlewares?: PluginMiddlewares<TCallApiContext> | ((context: PluginSetupContext<TCallApiContext>) => Awaitable<PluginMiddlewares<TCallApiContext>> | Awaitable<void>);
1761
- /**
1762
- * A name for the plugin
1763
- */
1764
- name: string;
1765
- /**
1766
- * Base schema for the client.
1767
- */
1768
- schema?: BaseCallApiSchemaAndConfig;
1769
- /**
1770
- * A function that will be called when the plugin is initialized. This will be called before the any of the other internal functions.
1771
- */
1772
- setup?: (context: PluginSetupContext<TCallApiContext>) => Awaitable<PluginInitResult<TCallApiContext>> | Awaitable<void>;
1773
- /**
1774
- * A version for the plugin
1775
- */
1776
- version?: string;
1777
- }
1778
- type InferPluginExtraOptions<TPluginArray extends CallApiPlugin[]> = UnionToIntersection<TPluginArray extends Array<infer TPlugin> ? TPlugin extends CallApiPlugin ? TPlugin["defineExtraOptions"] extends AnyFunction$1<infer TResult> ? InferSchemaOutput<TResult, TResult> : never : never : never>; //#endregion
1779
- //#region src/types/default-types.d.ts
1780
- type DefaultDataType = unknown;
1781
- type DefaultPluginArray = CallApiPlugin[];
1782
- type DefaultThrowOnError = boolean;
1783
- type DefaultMetaObject = Record<string, unknown>;
1784
- type DefaultCallApiContext = Prettify<OverrideCallApiContext<Required<CallApiContext>, {
1785
- Meta: GlobalMeta;
1786
- }>>; //#endregion
1787
- //#endregion
1788
- //#region src/plugins/logger/logger.d.ts
1789
- type ConsoleLikeObject = {
1790
- error: AnyFunction<void>;
1791
- fail?: AnyFunction<void>;
1792
- log: AnyFunction<void>;
1793
- success?: AnyFunction<void>;
1794
- warn?: AnyFunction<void>;
1795
- };
1796
- type LoggerOptions = {
1797
- /**
1798
- * Custom console object
1799
- */
1800
- consoleObject?: ConsoleLikeObject;
1801
- /**
1802
- * Enable or disable the logger
1803
- * @default true
1804
- */
1805
- enabled?: boolean | {
1806
- onError?: boolean;
1807
- onRequest?: boolean;
1808
- onRequestError?: boolean;
1809
- onResponse?: boolean;
1810
- onResponseError?: boolean;
1811
- onRetry?: boolean;
1812
- onSuccess?: boolean;
1813
- onValidationError?: boolean;
1814
- };
1815
- /**
1816
- * Enable or disable verbose mode
1817
- */
1818
- mode?: "basic" | "verbose";
1819
- };
1820
- declare const defaultConsoleObject: ConsoleLikeObject;
1821
- declare const loggerPlugin: (options?: LoggerOptions) => {
1822
- id: "logger";
1823
- name: "Logger";
1824
- version: "1.1.0";
1825
- hooks: {
1826
- onRequest: (ctx: RequestContext<Omit<{
1827
- Data: DefaultDataType;
1828
- ErrorData: DefaultDataType;
1829
- InferredExtraOptions: unknown;
1830
- ResultMode: ResultModeType;
1831
- Meta: GlobalMeta;
1832
- }, "Data" | "ErrorData"> & {
1833
- Data: never;
1834
- ErrorData: never;
1835
- }>) => void;
1836
- onRequestError: (ctx: (Omit<{
1837
- data: null;
1838
- error: PossibleJavaScriptError;
1839
- response: Response | null;
1840
- }, "data"> & RequestContext<Omit<{
1841
- Data: DefaultDataType;
1842
- ErrorData: DefaultDataType;
1843
- InferredExtraOptions: unknown;
1844
- ResultMode: ResultModeType;
1845
- Meta: GlobalMeta;
1846
- }, "Data" | "ErrorData"> & {
1847
- Data: never;
1848
- ErrorData: never;
1849
- }>) | (Omit<{
1850
- data: null;
1851
- error: {
1852
- errorData: never;
1853
- message: string;
1854
- name: "HTTPError";
1855
- originalError: _zayne_labs_callapi_utils0.HTTPError;
1856
- };
1857
- response: Response;
1858
- }, "data"> & RequestContext<Omit<{
1859
- Data: DefaultDataType;
1860
- ErrorData: DefaultDataType;
1861
- InferredExtraOptions: unknown;
1862
- ResultMode: ResultModeType;
1863
- Meta: GlobalMeta;
1864
- }, "Data" | "ErrorData"> & {
1865
- Data: never;
1866
- ErrorData: never;
1867
- }>)) => void;
1868
- onResponseError: (ctx: ResponseErrorContext<Omit<{
1869
- Data: DefaultDataType;
1870
- ErrorData: DefaultDataType;
1871
- InferredExtraOptions: unknown;
1872
- ResultMode: ResultModeType;
1873
- Meta: GlobalMeta;
1874
- }, "Data" | "ErrorData"> & {
1875
- Data: never;
1876
- ErrorData: never;
1877
- }>) => void;
1878
- onRetry: (ctx: ErrorContext<Omit<{
1879
- Data: DefaultDataType;
1880
- ErrorData: DefaultDataType;
1881
- InferredExtraOptions: unknown;
1882
- ResultMode: ResultModeType;
1883
- Meta: GlobalMeta;
1884
- }, "Data" | "ErrorData"> & {
1885
- Data: never;
1886
- ErrorData: never;
1887
- }> & {
1888
- retryAttemptCount: number;
1889
- }) => void;
1890
- onSuccess: (ctx: SuccessContext<Omit<{
1891
- Data: DefaultDataType;
1892
- ErrorData: DefaultDataType;
1893
- InferredExtraOptions: unknown;
1894
- ResultMode: ResultModeType;
1895
- Meta: GlobalMeta;
1896
- }, "Data" | "ErrorData"> & {
1897
- Data: never;
1898
- ErrorData: never;
1899
- }>) => void;
1900
- onValidationError: (ctx: Omit<{
1901
- data: null;
1902
- error: PossibleValidationError;
1903
- response: Response | null;
1904
- }, "data"> & RequestContext<Omit<{
1905
- Data: DefaultDataType;
1906
- ErrorData: DefaultDataType;
1907
- InferredExtraOptions: unknown;
1908
- ResultMode: ResultModeType;
1909
- Meta: GlobalMeta;
1910
- }, "Data" | "ErrorData"> & {
1911
- Data: never;
1912
- ErrorData: never;
1913
- }>) => void;
1914
- };
1915
- };
1916
- //#endregion
1917
- export { defaultConsoleObject as n, loggerPlugin as r, LoggerOptions as t };
1918
- //# sourceMappingURL=index-BfWbLAGF.d.ts.map