create-request 0.0.1-beta.2 → 0.0.1-beta.20

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,15 +1,81 @@
1
1
  import { type HttpMethod, type RedirectMode, type RequestMode, type RequestPriority, CredentialsPolicy } from "./enums";
2
+ import type { RequestOptions, RetryCallback, CookiesRecord, CookieOptions } from "./types";
2
3
  import { type ResponsePromise } from "./ResponseWrapper";
3
- import type { RequestOptions, RetryCallback } from "./types";
4
+ import type { CacheOptions } from "./types/cache";
5
+ import { CacheManager } from "./utils/CacheManager";
6
+ /**
7
+ * Base class with common functionality for all request types
8
+ * Provides the core request building and execution capabilities.
9
+ */
4
10
  export declare abstract class BaseRequest {
5
11
  protected abstract method: HttpMethod;
6
12
  protected requestOptions: RequestOptions;
7
13
  protected abortController?: AbortController;
8
14
  protected queryParams: URLSearchParams;
15
+ protected autoApplyCsrfProtection: boolean;
16
+ protected cacheManager?: CacheManager;
17
+ protected cacheEnabled: boolean;
9
18
  constructor();
19
+ /**
20
+ * Add multiple HTTP headers to the request
21
+ *
22
+ * @param headers - Key-value pairs of header names and values
23
+ * @returns The request instance for chaining
24
+ *
25
+ * @example
26
+ * request.withHeaders({
27
+ * 'Accept': 'application/json',
28
+ * 'X-Custom-Header': 'value'
29
+ * });
30
+ */
10
31
  withHeaders(headers: Record<string, string>): this;
32
+ /**
33
+ * Add a single HTTP header to the request
34
+ *
35
+ * @param key - The header name
36
+ * @param value - The header value
37
+ * @returns The request instance for chaining
38
+ *
39
+ * @example
40
+ * request.withHeader('Accept', 'application/json');
41
+ */
42
+ withHeader(key: string, value: string): this;
43
+ /**
44
+ * Set a timeout for the request
45
+ * If the request takes longer than the specified timeout, it will be aborted.
46
+ *
47
+ * @param timeout - The timeout in milliseconds
48
+ * @returns The request instance for chaining
49
+ * @throws Error if timeout is not a positive number
50
+ *
51
+ * @example
52
+ * request.withTimeout(5000); // 5 seconds timeout
53
+ */
11
54
  withTimeout(timeout: number): this;
55
+ /**
56
+ * Configure automatic retry behavior for failed requests
57
+ *
58
+ * @param retries - Number of retry attempts before failing
59
+ * @returns The request instance for chaining
60
+ * @throws Error if retries is not a non-negative integer
61
+ *
62
+ * @example
63
+ * request.withRetries(3); // Retry up to 3 times
64
+ */
12
65
  withRetries(retries: number): this;
66
+ /**
67
+ * Set a callback to be invoked before each retry attempt
68
+ * Useful for implementing backoff strategies or logging retry attempts.
69
+ *
70
+ * @param callback - Function to call before retrying
71
+ * @returns The request instance for chaining
72
+ *
73
+ * @example
74
+ * request.onRetry(({ attempt, error }) => {
75
+ * console.log(`Retry attempt ${attempt} after error: ${error.message}`);
76
+ * return new Promise(resolve => setTimeout(resolve, attempt * 1000));
77
+ * });
78
+ */
13
79
  onRetry(callback: RetryCallback): this;
14
80
  /**
15
81
  * Sets the credentials policy for the request
@@ -29,6 +95,12 @@ export declare abstract class BaseRequest {
29
95
  * @returns The instance for chaining
30
96
  */
31
97
  withReferrer(referrer: string): this;
98
+ /**
99
+ * Sets the referrer policy for the request
100
+ * @param policy - The referrer policy to use
101
+ * @returns The instance for chaining
102
+ */
103
+ withReferrerPolicy(policy: ReferrerPolicy): this;
32
104
  /**
33
105
  * Sets the redirect policy for the request
34
106
  * @param redirect - Can be 'follow', 'error', or 'manual'
@@ -56,10 +128,10 @@ export declare abstract class BaseRequest {
56
128
  /**
57
129
  * Adds a single query parameter
58
130
  * @param key - The parameter name
59
- * @param value - The parameter value
131
+ * @param value - The parameter value, can be a single value or array of values
60
132
  * @returns The instance for chaining
61
133
  */
62
- withQueryParam(key: string, value: string | number | boolean | null | undefined): this;
134
+ withQueryParam(key: string, value: string | string[] | number | boolean | null | undefined): this;
63
135
  /**
64
136
  * Sets the mode of the request
65
137
  * @param mode - The mode for the request (cors, no-cors, same-origin, navigate)
@@ -85,21 +157,80 @@ export declare abstract class BaseRequest {
85
157
  * @returns The instance for chaining
86
158
  */
87
159
  withBasicAuth(username: string, password: string): this;
160
+ /**
161
+ * Cross-environment base64 encoding
162
+ * Works in both browser and Node.js environments
163
+ */
164
+ private encodeBase64;
88
165
  /**
89
166
  * Sets the bearer token for authentication
90
167
  * @param token - The bearer token
91
168
  * @returns The instance for chaining
92
169
  */
93
170
  withBearerToken(token: string): this;
171
+ /**
172
+ * Helper function to check for header presence in a case-insensitive way
173
+ * @param headers Headers object
174
+ * @param headerName Header name to check
175
+ * @returns Boolean indicating if the header exists (case-insensitive)
176
+ */
177
+ private hasHeader;
94
178
  /**
95
179
  * Sets cookies for the request
96
- * @param cookies - An object containing cookie name-value pairs
180
+ * @param cookies Object containing cookie name-value pairs or cookie options
97
181
  * @returns The instance for chaining
98
182
  */
99
- withCookies(cookies: Record<string, string>): this;
183
+ withCookies(cookies: CookiesRecord): this;
184
+ /**
185
+ * Set a single cookie
186
+ * @param name Cookie name
187
+ * @param value Cookie value or options object
188
+ * @returns The instance for chaining
189
+ */
190
+ withCookie(name: string, value: string | CookieOptions): this;
191
+ /**
192
+ * Sets a CSRF token in the request headers
193
+ * @param token The CSRF token
194
+ * @param headerName The name of the header to use (default: X-CSRF-Token)
195
+ * @returns The instance for chaining
196
+ */
197
+ withCsrfToken(token: string, headerName?: string): this;
198
+ /**
199
+ * Disables automatic anti-CSRF protection.
200
+ * By default, X-Requested-With: XMLHttpRequest header is sent with all requests.
201
+ * @returns The instance for chaining
202
+ */
203
+ withoutCsrfProtection(): this;
204
+ /**
205
+ * Sets common security headers to help prevent CSRF attacks
206
+ * @returns The instance for chaining
207
+ */
208
+ withAntiCsrfHeaders(): this;
209
+ /**
210
+ * Configure request caching behavior
211
+ * When enabled, responses will be cached and reused for subsequent identical requests.
212
+ *
213
+ * @param options - Cache configuration options
214
+ * @returns The request instance for chaining
215
+ *
216
+ * @example
217
+ * request.withCache({
218
+ * ttl: 60000, // Cache for 1 minute
219
+ * maxEntries: 100,
220
+ * storage: localStorage
221
+ * });
222
+ */
223
+ withCache(options?: CacheOptions): this;
100
224
  /**
101
225
  * Send the request to the specified URL
102
- * @param url The URL to send the request to
226
+ * This is the final method in the chain that executes the request.
227
+ *
228
+ * @param url - The URL to send the request to
229
+ * @returns A promise with additional methods for processing the response
230
+ *
231
+ * @example
232
+ * const response = await request.sendTo('/api/users');
233
+ * const data = await response.getJson();
103
234
  */
104
235
  sendTo(url: string): ResponsePromise;
105
236
  /**
@@ -113,7 +244,15 @@ export declare abstract class BaseRequest {
113
244
  * @param url The formatted URL to send the request to
114
245
  * @param fetchOptions The fetch options to use
115
246
  * @returns A wrapped response object
247
+ * @throws RequestError if the request fails after all retries
116
248
  */
117
249
  private executeWithRetries;
118
250
  private executeRequest;
251
+ /**
252
+ * Executes a request using cache when possible
253
+ * @param url The formatted URL to send the request to
254
+ * @param fetchOptions The fetch options to use
255
+ * @param cacheKey The cache key for this request
256
+ */
257
+ private executeWithCache;
119
258
  }
@@ -1,8 +1,20 @@
1
1
  import { BaseRequest } from "./BaseRequest";
2
2
  import type { Body } from "./types";
3
+ /**
4
+ * Base class for requests that can have a body (POST, PUT, PATCH)
5
+ */
3
6
  export declare abstract class BodyRequest extends BaseRequest {
7
+ protected body?: Body;
8
+ private bodyType?;
4
9
  /**
5
- * Sets the request body with appropriate content type handling
10
+ * Sets the body of the request
11
+ * @param body - The request body
6
12
  */
7
13
  withBody(body: Body): this;
14
+ private setContentTypeIfNeeded;
15
+ /**
16
+ * Send the request to the specified URL
17
+ * Overrides the base implementation to add body handling
18
+ */
19
+ sendTo(url: string): ReturnType<BaseRequest["sendTo"]>;
8
20
  }
@@ -1,54 +1,93 @@
1
1
  /**
2
2
  * Wrapper for HTTP responses with methods to transform the response data
3
+ * Provides caching and conversion between different response formats.
3
4
  */
4
5
  export declare class ResponseWrapper {
5
- readonly ok: boolean;
6
- private response;
6
+ private readonly response;
7
+ private textCache;
8
+ private jsonCache;
9
+ private blobCache;
10
+ private arrayBufferCache;
11
+ private bodyUsed;
7
12
  constructor(response: Response);
8
- /**
9
- * Get the raw Response object
10
- */
11
- get raw(): Response;
12
- /**
13
- * Get the HTTP status code
14
- */
15
13
  get status(): number;
16
- /**
17
- * Get the HTTP status text
18
- */
19
14
  get statusText(): string;
20
- /**
21
- * Get response headers
22
- */
23
15
  get headers(): Headers;
16
+ get ok(): boolean;
17
+ get raw(): Response;
24
18
  /**
25
- * Parse response as JSON
19
+ * Parse the response body as JSON
20
+ * Caches the result for subsequent calls.
21
+ *
22
+ * @returns The parsed JSON data
23
+ * @throws Error if the response has already been consumed in a different format
24
+ *
25
+ * @example
26
+ * const data = await response.getJson();
27
+ * console.log(data.items);
26
28
  */
27
- json<T = unknown>(): Promise<T>;
29
+ getJson<T = unknown>(): Promise<T>;
28
30
  /**
29
- * Get response as text
31
+ * Get the response body as text
32
+ * Caches the result for subsequent calls. Attempts to convert from JSON or Blob
33
+ * if the body has already been consumed in those formats.
34
+ *
35
+ * @returns The response text
36
+ * @throws Error if the response has already been consumed in an incompatible format
37
+ *
38
+ * @example
39
+ * const text = await response.getText();
30
40
  */
31
- text(): Promise<string>;
41
+ getText(): Promise<string>;
32
42
  /**
33
- * Get response as Blob
43
+ * Get the response body as a Blob
44
+ * Caches the result for subsequent calls. Attempts to convert from text
45
+ * if the body has already been consumed as text.
46
+ *
47
+ * @returns The response as a Blob
48
+ * @throws Error if the response has already been consumed in an incompatible format
49
+ *
50
+ * @example
51
+ * const blob = await response.getBlob();
52
+ * const url = URL.createObjectURL(blob);
34
53
  */
35
- blob(): Promise<Blob>;
54
+ getBlob(): Promise<Blob>;
36
55
  /**
37
- * Get response as ArrayBuffer
56
+ * Get the response body as an ArrayBuffer
57
+ * Caches the result for subsequent calls. Attempts to convert from text or Blob
58
+ * if the body has already been consumed in those formats.
59
+ *
60
+ * @returns The response as an ArrayBuffer
61
+ * @throws Error if the response has already been consumed in an incompatible format
62
+ *
63
+ * @example
64
+ * const buffer = await response.getArrayBuffer();
38
65
  */
39
- arrayBuffer(): Promise<ArrayBuffer>;
66
+ getArrayBuffer(): Promise<ArrayBuffer>;
40
67
  /**
41
- * Get response as ReadableStream
68
+ * Get the raw response body as a ReadableStream
69
+ * This method consumes the body and should only be called once.
70
+ *
71
+ * @returns The response body as a ReadableStream or null
72
+ * @throws Error if the response body has already been consumed
73
+ *
74
+ * @example
75
+ * const stream = response.getBody();
76
+ * if (stream) {
77
+ * const reader = stream.getReader();
78
+ * // Process the stream
79
+ * }
42
80
  */
43
- body(): ReadableStream<Uint8Array> | null;
81
+ getBody(): ReadableStream<Uint8Array> | null;
44
82
  }
45
83
  /**
46
84
  * Type for Promise with response data transformation methods
47
85
  */
48
86
  export interface ResponsePromise<T = ResponseWrapper> extends Promise<T> {
49
- json<R = unknown>(): Promise<R>;
50
- text(): Promise<string>;
51
- blob(): Promise<Blob>;
52
- arrayBuffer(): Promise<ArrayBuffer>;
53
- body(): Promise<ReadableStream<Uint8Array> | null>;
87
+ getJson<R = unknown>(): Promise<R>;
88
+ getText(): Promise<string>;
89
+ getBlob(): Promise<Blob>;
90
+ getArrayBuffer(): Promise<ArrayBuffer>;
91
+ getBody(): Promise<ReadableStream<Uint8Array> | null>;
92
+ getData<T = unknown, R = T>(selector?: (data: T) => R): Promise<T | R>;
54
93
  }
@@ -3,28 +3,28 @@
3
3
  */
4
4
  export declare enum HttpMethod {
5
5
  GET = "GET",
6
- POST = "POST",
7
6
  PUT = "PUT",
8
- DELETE = "DELETE",
9
- PATCH = "PATCH",
7
+ POST = "POST",
10
8
  HEAD = "HEAD",
9
+ PATCH = "PATCH",
10
+ DELETE = "DELETE",
11
11
  OPTIONS = "OPTIONS"
12
12
  }
13
13
  /**
14
14
  * Enum for request priorities
15
15
  */
16
16
  export declare enum RequestPriority {
17
- HIGH = "high",
18
17
  LOW = "low",
18
+ HIGH = "high",
19
19
  AUTO = "auto"
20
20
  }
21
21
  /**
22
22
  * Enum for credentials policies
23
23
  */
24
24
  export declare enum CredentialsPolicy {
25
+ OMIT = "omit",
25
26
  INCLUDE = "include",
26
- SAME_ORIGIN = "same-origin",
27
- OMIT = "omit"
27
+ SAME_ORIGIN = "same-origin"
28
28
  }
29
29
  /**
30
30
  * Enum for request modes
@@ -39,8 +39,8 @@ export declare enum RequestMode {
39
39
  * Enum for redirect modes
40
40
  */
41
41
  export declare enum RedirectMode {
42
- FOLLOW = "follow",
43
42
  ERROR = "error",
43
+ FOLLOW = "follow",
44
44
  MANUAL = "manual"
45
45
  }
46
46
  /**
@@ -48,9 +48,38 @@ export declare enum RedirectMode {
48
48
  */
49
49
  export declare enum CacheMode {
50
50
  DEFAULT = "default",
51
- NO_STORE = "no-store",
52
51
  RELOAD = "reload",
52
+ NO_STORE = "no-store",
53
53
  NO_CACHE = "no-cache",
54
54
  FORCE_CACHE = "force-cache",
55
55
  ONLY_IF_CACHED = "only-if-cached"
56
56
  }
57
+ /**
58
+ * Enum for cookie SameSite policies
59
+ */
60
+ export declare enum SameSitePolicy {
61
+ LAX = "Lax",
62
+ NONE = "None",
63
+ STRICT = "Strict"
64
+ }
65
+ /**
66
+ * Enum for body types
67
+ */
68
+ export declare enum BodyType {
69
+ JSON = "json",
70
+ STRING = "string",
71
+ BINARY = "binary"
72
+ }
73
+ /**
74
+ * Referrer policies for fetch requests
75
+ */
76
+ export declare enum ReferrerPolicy {
77
+ ORIGIN = "origin",
78
+ UNSAFE_URL = "unsafe-url",
79
+ SAME_ORIGIN = "same-origin",
80
+ NO_REFERRER = "no-referrer",
81
+ STRICT_ORIGIN = "strict-origin",
82
+ ORIGIN_WHEN_CROSS_ORIGIN = "origin-when-cross-origin",
83
+ NO_REFERRER_WHEN_DOWNGRADE = "no-referrer-when-downgrade",
84
+ STRICT_ORIGIN_WHEN_CROSS_ORIGIN = "strict-origin-when-cross-origin"
85
+ }
@@ -1,9 +1,19 @@
1
1
  import { get, put, head, post, patch, del, options } from "./requestFactories";
2
- export { HttpMethod, RequestPriority, CredentialsPolicy, RequestMode, RedirectMode, CacheMode, } from "./enums";
3
- export type { RetryCallback, RequestOptions } from "./types";
4
- export { RequestError } from "./RequestError";
2
+ import { Config } from "./utils/Config";
3
+ export { HttpMethod, RequestPriority, CredentialsPolicy, RequestMode, RedirectMode, CacheMode, SameSitePolicy, ReferrerPolicy } from "./enums";
4
+ export type { RetryCallback, RequestOptions, CookiesRecord, CookieOptions } from "./types";
5
+ export type { StorageProvider } from "./utils/StorageProvider";
6
+ export type { CacheOptions } from "./types/cache";
5
7
  export { ResponseWrapper } from "./ResponseWrapper";
6
- export { GetRequest, PostRequest, PutRequest, DeleteRequest, PatchRequest, HeadRequest, OptionsRequest, } from "./requestMethods";
8
+ export { CookieUtils } from "./utils/CookieUtils";
9
+ export { RequestError } from "./RequestError";
10
+ export { GetRequest, PostRequest, PutRequest, DeleteRequest, PatchRequest, HeadRequest, OptionsRequest } from "./requestMethods";
11
+ export { createMemoryStorage, createLocalStorageStorage, createSessionStorageStorage } from "./utils/CacheStorage";
12
+ export { CacheManager } from "./utils/CacheManager";
13
+ /**
14
+ * Main API object for creating HTTP requests
15
+ * Provides factory methods for all HTTP methods and access to global configuration.
16
+ */
7
17
  declare const create: {
8
18
  readonly get: typeof get;
9
19
  readonly post: typeof post;
@@ -12,5 +22,6 @@ declare const create: {
12
22
  readonly patch: typeof patch;
13
23
  readonly head: typeof head;
14
24
  readonly options: typeof options;
25
+ readonly config: Config;
15
26
  };
16
27
  export default create;