@oxog/requestkit 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,570 @@
1
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
2
+ type ResponseType = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'stream' | 'raw';
3
+ type ErrorCode = 'ERR_NETWORK' | 'ERR_TIMEOUT' | 'ERR_CANCELED' | 'ERR_BAD_REQUEST' | 'ERR_BAD_RESPONSE';
4
+ interface Progress {
5
+ loaded: number;
6
+ total: number;
7
+ percent: number;
8
+ }
9
+ type ProgressCallback = (progress: Progress) => void;
10
+ interface ParamsSerializer {
11
+ encode?: (params: Record<string, unknown>) => string;
12
+ arrayFormat?: 'indices' | 'brackets' | 'repeat' | 'comma';
13
+ }
14
+ type TransformFn = (data: unknown, headers?: Headers) => unknown;
15
+ type RequestHook = (config: InternalRequestConfig) => InternalRequestConfig | Promise<InternalRequestConfig>;
16
+ type ResponseHook = (response: Response) => Response | Promise<Response>;
17
+ type ErrorHook = (error: RequestError) => unknown;
18
+ interface RetryConfig {
19
+ /** Max retry attempts */
20
+ limit: number;
21
+ /** Methods to retry (default: GET, HEAD, OPTIONS, PUT, DELETE) */
22
+ methods?: HttpMethod[];
23
+ /** Status codes to retry (default: 408, 429, 500, 502, 503, 504) */
24
+ statusCodes?: number[];
25
+ /** Initial delay in ms (default: 1000) */
26
+ delay?: number;
27
+ /** Backoff strategy (default: exponential) */
28
+ backoff?: 'linear' | 'exponential';
29
+ /** Max delay in ms (default: 30000) */
30
+ maxDelay?: number;
31
+ /** Custom retry condition */
32
+ retryCondition?: (error: RequestError) => boolean;
33
+ /** Retry callback */
34
+ onRetry?: (attempt: number, error: RequestError, config: InternalRequestConfig) => void;
35
+ }
36
+ interface ClientConfig {
37
+ /** Base URL for all requests */
38
+ baseURL?: string;
39
+ /** Default headers */
40
+ headers?: HeadersInit | Record<string, string>;
41
+ /** Timeout in ms (0 = no timeout) */
42
+ timeout?: number;
43
+ /** Retry config or number of retries */
44
+ retry?: number | RetryConfig;
45
+ /** Response type (default: json) */
46
+ responseType?: ResponseType;
47
+ /** Credentials mode */
48
+ credentials?: RequestCredentials;
49
+ /** Cache mode */
50
+ cache?: RequestCache;
51
+ /** Request mode */
52
+ mode?: RequestMode;
53
+ /** Query params serialization */
54
+ paramsSerializer?: ParamsSerializer;
55
+ /** Status validation (default: 200-299) */
56
+ validateStatus?: (status: number) => boolean;
57
+ /** Transform request data */
58
+ transformRequest?: TransformFn | TransformFn[];
59
+ /** Transform response data */
60
+ transformResponse?: TransformFn | TransformFn[];
61
+ /** Request hook */
62
+ onRequest?: RequestHook;
63
+ /** Response hook */
64
+ onResponse?: ResponseHook;
65
+ /** Error hook */
66
+ onError?: ErrorHook;
67
+ }
68
+ interface RequestOptions extends Omit<ClientConfig, 'baseURL'> {
69
+ /** HTTP method */
70
+ method?: HttpMethod;
71
+ /** URL params (query string) */
72
+ params?: Record<string, unknown> | URLSearchParams;
73
+ /** Request body */
74
+ body?: BodyInit | Record<string, unknown>;
75
+ /** JSON body (auto-serialized) */
76
+ json?: Record<string, unknown>;
77
+ /** Form body (FormData or URLSearchParams) */
78
+ form?: Record<string, unknown> | FormData;
79
+ /** Abort signal */
80
+ signal?: AbortSignal;
81
+ /** Upload progress callback */
82
+ onUploadProgress?: ProgressCallback;
83
+ /** Download progress callback */
84
+ onDownloadProgress?: ProgressCallback;
85
+ /** Return cancelable request */
86
+ cancelable?: boolean;
87
+ /** Return raw response with metadata */
88
+ raw?: boolean;
89
+ }
90
+ interface InternalRequestConfig extends RequestOptions {
91
+ url: string;
92
+ method: HttpMethod;
93
+ headers: Headers;
94
+ baseURL?: string;
95
+ /** Internal: retry attempt tracking */
96
+ _retry?: boolean;
97
+ /** Internal: current retry count */
98
+ _retryCount?: number;
99
+ }
100
+ interface RequestResponse<T = unknown> {
101
+ data: T;
102
+ status: number;
103
+ statusText: string;
104
+ headers: Headers;
105
+ config: InternalRequestConfig;
106
+ request?: Request;
107
+ ok: boolean;
108
+ }
109
+ interface RequestError extends Error {
110
+ name: 'RequestError';
111
+ message: string;
112
+ status?: number;
113
+ statusText?: string;
114
+ data?: unknown;
115
+ config: InternalRequestConfig;
116
+ request?: Request;
117
+ response?: Response;
118
+ code?: ErrorCode;
119
+ }
120
+ interface InterceptorHandler<T> {
121
+ fulfilled?: (value: T) => T | Promise<T>;
122
+ rejected?: (error: RequestError) => unknown;
123
+ }
124
+ interface InterceptorManager<T> {
125
+ /**
126
+ * Add an interceptor
127
+ * @returns Interceptor ID for removal
128
+ */
129
+ use(onFulfilled?: (value: T) => T | Promise<T>, onRejected?: (error: RequestError) => unknown): number;
130
+ /**
131
+ * Remove an interceptor by ID
132
+ */
133
+ eject(id: number): void;
134
+ /**
135
+ * Clear all interceptors
136
+ */
137
+ clear(): void;
138
+ }
139
+ interface Interceptors {
140
+ request: InterceptorManager<InternalRequestConfig>;
141
+ response: InterceptorManager<Response>;
142
+ }
143
+ interface CancelableRequest<T> {
144
+ data: Promise<T>;
145
+ cancel: () => void;
146
+ }
147
+ interface CancelToken$1 {
148
+ promise: Promise<Cancel>;
149
+ reason?: Cancel;
150
+ throwIfRequested(): void;
151
+ }
152
+ interface CancelTokenSource {
153
+ token: CancelToken$1;
154
+ cancel: (message?: string) => void;
155
+ }
156
+ interface Cancel {
157
+ message?: string;
158
+ }
159
+ interface RequestClient {
160
+ get<T = unknown>(url: string, options?: RequestOptions): Promise<T>;
161
+ post<T = unknown>(url: string, body?: unknown, options?: RequestOptions): Promise<T>;
162
+ put<T = unknown>(url: string, body?: unknown, options?: RequestOptions): Promise<T>;
163
+ patch<T = unknown>(url: string, body?: unknown, options?: RequestOptions): Promise<T>;
164
+ delete<T = unknown>(url: string, options?: RequestOptions): Promise<T>;
165
+ head(url: string, options?: RequestOptions): Promise<void>;
166
+ options(url: string, options?: RequestOptions): Promise<void>;
167
+ request<T = unknown>(url: string, options?: RequestOptions): Promise<T>;
168
+ request<T = unknown>(options: RequestOptions & {
169
+ url: string;
170
+ }): Promise<T>;
171
+ interceptors: Interceptors;
172
+ defaults: ClientConfig;
173
+ extend(config: ClientConfig): RequestClient;
174
+ clone(): RequestClient;
175
+ }
176
+ interface UseRequestOptions<T> {
177
+ /** Don't fetch on mount */
178
+ manual?: boolean;
179
+ /** Success callback */
180
+ onSuccess?: (data: T) => void;
181
+ /** Error callback */
182
+ onError?: (error: RequestError) => void;
183
+ }
184
+ interface UseRequestResult<T> {
185
+ data: T | undefined;
186
+ loading: boolean;
187
+ error: RequestError | null;
188
+ execute: (options?: RequestOptions) => Promise<T>;
189
+ reset: () => void;
190
+ }
191
+ interface UseQueryOptions<T> {
192
+ /** Enable/disable query */
193
+ enabled?: boolean;
194
+ /** Time until data is stale (ms) */
195
+ staleTime?: number;
196
+ /** Time to keep in cache (ms) */
197
+ cacheTime?: number;
198
+ /** Refetch on window focus */
199
+ refetchOnWindowFocus?: boolean;
200
+ /** Refetch on reconnect */
201
+ refetchOnReconnect?: boolean;
202
+ /** Polling interval (ms) */
203
+ refetchInterval?: number;
204
+ /** Retry failed requests */
205
+ retry?: number | boolean;
206
+ /** Success callback */
207
+ onSuccess?: (data: T) => void;
208
+ /** Error callback */
209
+ onError?: (error: RequestError) => void;
210
+ }
211
+ interface UseQueryResult<T> {
212
+ data: T | undefined;
213
+ loading: boolean;
214
+ error: RequestError | null;
215
+ isStale: boolean;
216
+ isFetching: boolean;
217
+ refetch: () => Promise<void>;
218
+ }
219
+ interface UseMutationOptions<T, V> {
220
+ /** Success callback */
221
+ onSuccess?: (data: T, variables: V) => void;
222
+ /** Error callback */
223
+ onError?: (error: RequestError, variables: V) => void;
224
+ /** Settled callback (always called) */
225
+ onSettled?: (data: T | undefined, error: RequestError | null, variables: V) => void;
226
+ }
227
+ interface UseMutationResult<T, V> {
228
+ data: T | undefined;
229
+ loading: boolean;
230
+ error: RequestError | null;
231
+ mutate: (variables: V) => void;
232
+ mutateAsync: (variables: V) => Promise<T>;
233
+ reset: () => void;
234
+ }
235
+ interface UseInfiniteQueryOptions<T> {
236
+ /** Get next page param from last page */
237
+ getNextPageParam: (lastPage: T, pages: T[]) => unknown | undefined;
238
+ /** Get previous page param from first page */
239
+ getPreviousPageParam?: (firstPage: T, pages: T[]) => unknown | undefined;
240
+ /** Enable/disable query */
241
+ enabled?: boolean;
242
+ /** Time until data is stale (ms) */
243
+ staleTime?: number;
244
+ /** Success callback */
245
+ onSuccess?: (data: T[]) => void;
246
+ /** Error callback */
247
+ onError?: (error: RequestError) => void;
248
+ }
249
+ interface UseInfiniteQueryResult<T> {
250
+ data: T[] | undefined;
251
+ loading: boolean;
252
+ error: RequestError | null;
253
+ isFetchingNextPage: boolean;
254
+ isFetchingPreviousPage: boolean;
255
+ hasNextPage: boolean;
256
+ hasPreviousPage: boolean;
257
+ fetchNextPage: () => Promise<void>;
258
+ fetchPreviousPage: () => Promise<void>;
259
+ refetch: () => Promise<void>;
260
+ }
261
+
262
+ /**
263
+ * RequestKit Client Factory
264
+ */
265
+
266
+ /**
267
+ * Create a new RequestKit client
268
+ */
269
+ declare function createClient(config?: ClientConfig): RequestClient;
270
+
271
+ /**
272
+ * Error handling utilities
273
+ */
274
+
275
+ /**
276
+ * Create a RequestError from various inputs
277
+ */
278
+ declare function createError(message: string, config: InternalRequestConfig, code?: ErrorCode, request?: Request, response?: Response, data?: unknown): RequestError;
279
+ /**
280
+ * Type guard to check if error is a RequestError
281
+ */
282
+ declare function isRequestError(error: unknown): error is RequestError;
283
+ /**
284
+ * Check if error is a network error
285
+ */
286
+ declare function isNetworkError(error: unknown): boolean;
287
+ /**
288
+ * Check if error is a timeout error
289
+ */
290
+ declare function isTimeoutError(error: unknown): boolean;
291
+ /**
292
+ * Check if error is a cancel/abort error
293
+ */
294
+ declare function isCancelError(error: unknown): boolean;
295
+ /**
296
+ * Check if error is a client error (4xx)
297
+ */
298
+ declare function isClientError(error: unknown): boolean;
299
+ /**
300
+ * Check if error is a server error (5xx)
301
+ */
302
+ declare function isServerError(error: unknown): boolean;
303
+
304
+ /**
305
+ * URL manipulation utilities
306
+ */
307
+ /**
308
+ * Check if a URL is absolute (has protocol)
309
+ */
310
+ declare function isAbsoluteURL(url: string): boolean;
311
+ /**
312
+ * Combine base URL with relative URL
313
+ * Handles trailing/leading slashes correctly
314
+ */
315
+ declare function combineURLs(baseURL: string, relativeURL: string): string;
316
+ /**
317
+ * Build URL with query parameters
318
+ */
319
+ declare function buildURL(url: string, params?: Record<string, unknown> | URLSearchParams | string): string;
320
+ /**
321
+ * Parse URL into components
322
+ */
323
+ declare function parseURL(url: string): {
324
+ protocol: string;
325
+ host: string;
326
+ pathname: string;
327
+ search: string;
328
+ hash: string;
329
+ };
330
+ /**
331
+ * Get the origin from a URL
332
+ */
333
+ declare function getOrigin(url: string): string;
334
+ /**
335
+ * Check if two URLs have the same origin
336
+ */
337
+ declare function isSameOrigin(url1: string, url2: string): boolean;
338
+
339
+ /**
340
+ * Query parameter serialization utilities
341
+ */
342
+
343
+ type ArrayFormat = 'indices' | 'brackets' | 'repeat' | 'comma';
344
+ interface SerializeOptions {
345
+ arrayFormat?: ArrayFormat;
346
+ encode?: boolean;
347
+ }
348
+ /**
349
+ * Serialize params object to query string
350
+ */
351
+ declare function serializeParams(params: Record<string, unknown>, options?: SerializeOptions): string;
352
+ /**
353
+ * Parse query string to params object
354
+ */
355
+ declare function parseParams(query: string): Record<string, unknown>;
356
+ /**
357
+ * Create a params serializer with custom options
358
+ */
359
+ declare function createParamsSerializer(options?: SerializeOptions): ParamsSerializer;
360
+
361
+ /**
362
+ * Headers utilities
363
+ */
364
+ /**
365
+ * Normalize various header input types to Headers object
366
+ */
367
+ declare function normalizeHeaders(headers?: HeadersInit | Record<string, string>): Headers;
368
+ /**
369
+ * Merge multiple header sources
370
+ * Later sources override earlier ones
371
+ */
372
+ declare function mergeHeaders(...sources: Array<HeadersInit | Record<string, string> | undefined>): Headers;
373
+ /**
374
+ * Convert Headers to plain object
375
+ */
376
+ declare function parseHeaders(headers: Headers): Record<string, string>;
377
+ /**
378
+ * Get header value (case-insensitive)
379
+ */
380
+ declare function getHeader(headers: Headers | HeadersInit | Record<string, string> | undefined, key: string): string | undefined;
381
+ /**
382
+ * Check if header exists (case-insensitive)
383
+ */
384
+ declare function hasHeader(headers: Headers | HeadersInit | Record<string, string> | undefined, key: string): boolean;
385
+ /**
386
+ * Common content type constants
387
+ */
388
+ declare const ContentTypes: {
389
+ readonly JSON: "application/json";
390
+ readonly FORM: "application/x-www-form-urlencoded";
391
+ readonly MULTIPART: "multipart/form-data";
392
+ readonly TEXT: "text/plain";
393
+ readonly HTML: "text/html";
394
+ readonly XML: "application/xml";
395
+ readonly OCTET_STREAM: "application/octet-stream";
396
+ };
397
+ /**
398
+ * Check if content type is JSON
399
+ */
400
+ declare function isJSONContentType(contentType?: string | null): boolean;
401
+ /**
402
+ * Check if content type is text-based
403
+ */
404
+ declare function isTextContentType(contentType?: string | null): boolean;
405
+
406
+ /**
407
+ * Request body serialization utilities
408
+ */
409
+
410
+ /**
411
+ * Serialize form data from object
412
+ */
413
+ declare function objectToFormData(obj: Record<string, unknown>, formData?: FormData, parentKey?: string): FormData;
414
+ /**
415
+ * Serialize object to URLSearchParams
416
+ */
417
+ declare function objectToURLSearchParams(obj: Record<string, unknown>): URLSearchParams;
418
+ /**
419
+ * Get content type for a body value
420
+ */
421
+ declare function getContentType(body: unknown): string | undefined;
422
+
423
+ /**
424
+ * Type guard utilities for runtime type checking
425
+ */
426
+ /**
427
+ * Check if value is FormData
428
+ */
429
+ declare function isFormData(value: unknown): value is FormData;
430
+ /**
431
+ * Check if value is Blob
432
+ */
433
+ declare function isBlob(value: unknown): value is Blob;
434
+ /**
435
+ * Check if value is File
436
+ */
437
+ declare function isFile(value: unknown): value is File;
438
+ /**
439
+ * Check if value is ArrayBuffer
440
+ */
441
+ declare function isArrayBuffer(value: unknown): value is ArrayBuffer;
442
+ /**
443
+ * Check if value is ArrayBufferView (TypedArray or DataView)
444
+ */
445
+ declare function isArrayBufferView(value: unknown): value is ArrayBufferView;
446
+ /**
447
+ * Check if value is URLSearchParams
448
+ */
449
+ declare function isURLSearchParams(value: unknown): value is URLSearchParams;
450
+ /**
451
+ * Check if value is a ReadableStream
452
+ */
453
+ declare function isStream(value: unknown): value is ReadableStream;
454
+ /**
455
+ * Check if value is a plain object (not null, array, or class instance)
456
+ */
457
+ declare function isPlainObject(value: unknown): value is Record<string, unknown>;
458
+ /**
459
+ * Check if value is a function
460
+ */
461
+ declare function isFunction(value: unknown): value is (...args: unknown[]) => unknown;
462
+ /**
463
+ * Check if value is a string
464
+ */
465
+ declare function isString(value: unknown): value is string;
466
+ /**
467
+ * Check if value is a number
468
+ */
469
+ declare function isNumber(value: unknown): value is number;
470
+ /**
471
+ * Check if value is undefined
472
+ */
473
+ declare function isUndefined(value: unknown): value is undefined;
474
+ /**
475
+ * Check if value is null or undefined
476
+ */
477
+ declare function isNullOrUndefined(value: unknown): value is null | undefined;
478
+ /**
479
+ * Check if value is a Date
480
+ */
481
+ declare function isDate(value: unknown): value is Date;
482
+ /**
483
+ * Check if value is a boolean
484
+ */
485
+ declare function isBoolean(value: unknown): value is boolean;
486
+ /**
487
+ * Check if value is an array
488
+ */
489
+ declare function isArray(value: unknown): value is unknown[];
490
+ /**
491
+ * Check if value is an object (including arrays and null)
492
+ */
493
+ declare function isObject(value: unknown): value is object;
494
+ /**
495
+ * Check if value is a Headers instance
496
+ */
497
+ declare function isHeaders(value: unknown): value is Headers;
498
+ /**
499
+ * Check if value is a Request instance
500
+ */
501
+ declare function isRequest(value: unknown): value is Request;
502
+ /**
503
+ * Check if value is a Response instance
504
+ */
505
+ declare function isResponse(value: unknown): value is Response;
506
+ /**
507
+ * Check if value is an AbortSignal
508
+ */
509
+ declare function isAbortSignal(value: unknown): value is AbortSignal;
510
+
511
+ /**
512
+ * Request cancellation utilities
513
+ */
514
+
515
+ /**
516
+ * CancelToken factory
517
+ */
518
+ declare const CancelToken: {
519
+ /**
520
+ * Create a new CancelToken source
521
+ * Returns an object with token and cancel function
522
+ */
523
+ source(): CancelTokenSource;
524
+ };
525
+ /**
526
+ * Check if a value is a Cancel error
527
+ */
528
+ declare function isCancel(value: unknown): value is Cancel;
529
+
530
+ /**
531
+ * Deep merge utilities
532
+ */
533
+ /**
534
+ * Deep merge multiple objects
535
+ * Later sources override earlier ones
536
+ * Arrays are replaced, not merged
537
+ */
538
+ declare function deepMerge<T>(...sources: Array<Partial<T> | undefined>): T;
539
+ /**
540
+ * Shallow merge multiple objects
541
+ * Later sources override earlier ones
542
+ */
543
+ declare function shallowMerge<T extends Record<string, unknown>>(...sources: Array<Partial<T> | undefined>): T;
544
+ /**
545
+ * Clone an object deeply
546
+ */
547
+ declare function deepClone<T>(value: T): T;
548
+ /**
549
+ * Pick specific keys from an object
550
+ */
551
+ declare function pick<T extends Record<string, unknown>, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>;
552
+ /**
553
+ * Omit specific keys from an object
554
+ */
555
+ declare function omit<T extends Record<string, unknown>, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>;
556
+
557
+ /**
558
+ * Async delay utilities
559
+ */
560
+ /**
561
+ * Create a promise that resolves after specified milliseconds
562
+ */
563
+ declare function delay(ms: number): Promise<void>;
564
+ /**
565
+ * Create an abortable delay
566
+ * Returns a promise that resolves after ms, or rejects if signal is aborted
567
+ */
568
+ declare function abortableDelay(ms: number, signal?: AbortSignal): Promise<void>;
569
+
570
+ export { type Cancel, CancelToken, type CancelToken$1 as CancelTokenInterface, type CancelTokenSource, type CancelableRequest, type ClientConfig, ContentTypes, type ErrorCode, type ErrorHook, type HttpMethod, type InterceptorHandler, type InterceptorManager, type Interceptors, type InternalRequestConfig, type ParamsSerializer, type Progress, type ProgressCallback, type RequestClient, type RequestError, type RequestHook, type RequestOptions, type RequestResponse, type ResponseHook, type ResponseType, type RetryConfig, type TransformFn, type UseInfiniteQueryOptions, type UseInfiniteQueryResult, type UseMutationOptions, type UseMutationResult, type UseQueryOptions, type UseQueryResult, type UseRequestOptions, type UseRequestResult, abortableDelay, buildURL, combineURLs, createClient, createError, createParamsSerializer, deepClone, deepMerge, delay, getContentType, getHeader, getOrigin, hasHeader, isAbortSignal, isAbsoluteURL, isArray, isArrayBuffer, isArrayBufferView, isBlob, isBoolean, isCancel, isCancelError, isClientError, isDate, isFile, isFormData, isFunction, isHeaders, isJSONContentType, isNetworkError, isNullOrUndefined, isNumber, isObject, isPlainObject, isRequest, isRequestError, isResponse, isSameOrigin, isServerError, isStream, isString, isTextContentType, isTimeoutError, isURLSearchParams, isUndefined, mergeHeaders, normalizeHeaders, objectToFormData, objectToURLSearchParams, omit, parseHeaders, parseParams, parseURL, pick, serializeParams, shallowMerge };