@alessiofrittoli/fetcher 1.0.0 → 2.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.
- package/README.md +83 -48
- package/dist/error/index.cjs +1 -0
- package/dist/error/index.d.cts +2 -0
- package/dist/error/index.d.mts +2 -0
- package/dist/error/index.mjs +1 -0
- package/dist/getErrorFromResponse-CIppVMTN.mjs +1 -0
- package/dist/getErrorFromResponse-D3OARgUA.cjs +1 -0
- package/dist/globals/index.d.cts +15 -0
- package/dist/globals/index.d.mts +15 -0
- package/dist/globals/index.mjs +1 -0
- package/dist/index-B8rmZCit.d.mts +398 -0
- package/dist/index-CQSGH5s-.d.cts +25 -0
- package/dist/index-CQSGH5s-.d.mts +25 -0
- package/dist/index-D-vZzzH1.d.cts +398 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +17 -0
- package/dist/index.d.mts +16 -11
- package/dist/index.mjs +1 -0
- package/dist/ping/index.cjs +1 -0
- package/dist/ping/index.d.cts +9 -0
- package/dist/ping/index.d.mts +9 -0
- package/dist/ping/index.mjs +1 -0
- package/dist/types/index.cjs +0 -0
- package/dist/types/index.d.cts +2 -0
- package/dist/types/index.d.mts +2 -0
- package/dist/types/index.mjs +1 -0
- package/dist/xhr/index.cjs +1 -0
- package/dist/xhr/index.d.cts +2 -0
- package/dist/xhr/index.d.mts +2 -8
- package/dist/xhr/index.mjs +1 -1
- package/package.json +127 -155
- package/dist/chunk-HNNMLJIA.js +0 -1
- package/dist/chunk-LOWOZ6LK.mjs +0 -1
- package/dist/error.d.mts +0 -13
- package/dist/error.d.ts +0 -13
- package/dist/error.js +0 -1
- package/dist/error.mjs +0 -1
- package/dist/fetch.d.mts +0 -23
- package/dist/fetch.d.ts +0 -23
- package/dist/fetch.js +0 -1
- package/dist/fetch.mjs +0 -1
- package/dist/getErrorFromResponse-7V2YFS4F.js +0 -1
- package/dist/getErrorFromResponse-IJTUOFPH.mjs +0 -1
- package/dist/index.d.ts +0 -12
- package/dist/index.js +0 -1
- package/dist/logReadyStateChange-2QWX5XIU.mjs +0 -1
- package/dist/logReadyStateChange-MSYI3OBQ.js +0 -1
- package/dist/ping.d.mts +0 -8
- package/dist/ping.d.ts +0 -8
- package/dist/ping.js +0 -1
- package/dist/ping.mjs +0 -1
- package/dist/types-CVc-rxXe.d.ts +0 -227
- package/dist/types-DuGUXaTD.d.mts +0 -227
- package/dist/types.d.mts +0 -8
- package/dist/types.d.ts +0 -8
- package/dist/types.js +0 -1
- package/dist/xhr/index.d.ts +0 -8
- package/dist/xhr/index.js +0 -1
- package/scripts/postinstall/index.js +0 -16
- package/scripts/postinstall/ts-setup.js +0 -15
- /package/dist/{types.mjs → globals/index.cjs} +0 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { ValueOf } from "@alessiofrittoli/type-utils";
|
|
2
|
+
//#region src/error/index.d.ts
|
|
3
|
+
declare const Request: {
|
|
4
|
+
readonly XHR_NOT_AVAILABLE: "ERR:XHRNOTAVAILABLE";
|
|
5
|
+
readonly XHR_INVALID_STATE: "ERR:XHRINVALIDSTATE";
|
|
6
|
+
readonly XHR_DESTROYED: "ERR:XHRDESTROYED";
|
|
7
|
+
};
|
|
8
|
+
declare const ErrorCode: {
|
|
9
|
+
readonly XHR_NOT_AVAILABLE: "ERR:XHRNOTAVAILABLE";
|
|
10
|
+
readonly XHR_INVALID_STATE: "ERR:XHRINVALIDSTATE";
|
|
11
|
+
readonly XHR_DESTROYED: "ERR:XHRDESTROYED";
|
|
12
|
+
readonly UNKNOWN: "ERR:UNKNOWN";
|
|
13
|
+
readonly ABORT: "ERR:ABORT";
|
|
14
|
+
readonly EMPTY_VALUE: "ERR:EMPTYVALUE";
|
|
15
|
+
readonly WRONG_VALUE: "ERR:WRONGVALUE";
|
|
16
|
+
readonly EXPIRED: "ERR:EXPIRED";
|
|
17
|
+
readonly TOO_EARLY: "ERR:TOOEARLY";
|
|
18
|
+
readonly TOO_MANY: "ERR:TOOMANY";
|
|
19
|
+
readonly QUOTA_REACHED: "ERR:QUOTAREACHED";
|
|
20
|
+
readonly NOT_FOUND: "ERR:NOTFOUND";
|
|
21
|
+
readonly OFFLINE: "ERR:INTERNETDISCONNECTED";
|
|
22
|
+
};
|
|
23
|
+
type ErrorCode = ValueOf<typeof ErrorCode>;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { Request as n, ErrorCode as t };
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
import { t as ErrorCode } from "./index-CQSGH5s-.cjs";
|
|
2
|
+
import { AbortController } from "@alessiofrittoli/abort-controller";
|
|
3
|
+
import { Exception } from "@alessiofrittoli/exception";
|
|
4
|
+
import { EventEmitter, Listener } from "@alessiofrittoli/event-emitter";
|
|
5
|
+
import { AbortError, AbortErrorOptions } from "@alessiofrittoli/exception/abort";
|
|
6
|
+
import { UrlInput } from "@alessiofrittoli/url-utils";
|
|
7
|
+
import { UUID } from "@alessiofrittoli/math-utils";
|
|
8
|
+
//#region src/fetch/types.d.ts
|
|
9
|
+
declare namespace Fetch {
|
|
10
|
+
type Method = RequestMethod;
|
|
11
|
+
type Result<T> = {
|
|
12
|
+
/**
|
|
13
|
+
* The received Response.
|
|
14
|
+
*
|
|
15
|
+
*/
|
|
16
|
+
response: Response | null;
|
|
17
|
+
/**
|
|
18
|
+
* The received Response Headers.
|
|
19
|
+
*
|
|
20
|
+
*/
|
|
21
|
+
headers: Headers | null;
|
|
22
|
+
} & ({
|
|
23
|
+
/** The parsed data. */
|
|
24
|
+
data: T;
|
|
25
|
+
error: null;
|
|
26
|
+
} | {
|
|
27
|
+
/** The parsed error. */
|
|
28
|
+
error: Exception;
|
|
29
|
+
data: null;
|
|
30
|
+
});
|
|
31
|
+
type ReturnDataType<T, U extends RequestInit = RequestInit> = T extends undefined ? U['responseType'] extends 'blob' ? Blob : U['responseType'] extends 'formdata' ? FormData : U['responseType'] extends 'arraybuffer' ? ArrayBuffer : string : T;
|
|
32
|
+
type OnFulfilledCallback<V> = (response: Response) => Fetch.Result<V> | PromiseLike<Fetch.Result<V>>;
|
|
33
|
+
}
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/xhr/index.d.ts
|
|
36
|
+
declare class Xhr<TReturn = unknown> extends EventEmitter<XHR.Event.Map<TReturn>> {
|
|
37
|
+
/**
|
|
38
|
+
* The XMLHttpRequest instance.
|
|
39
|
+
*
|
|
40
|
+
*/
|
|
41
|
+
readonly request: XMLHttpRequest;
|
|
42
|
+
/**
|
|
43
|
+
* The current request UUID.
|
|
44
|
+
*
|
|
45
|
+
*/
|
|
46
|
+
protected _requestId: UUID;
|
|
47
|
+
/**
|
|
48
|
+
* The current request UUID.
|
|
49
|
+
*
|
|
50
|
+
*/
|
|
51
|
+
get requestId(): typeof this._requestId;
|
|
52
|
+
protected set requestId(value: typeof this._requestId);
|
|
53
|
+
/**
|
|
54
|
+
* Enables debug logging.
|
|
55
|
+
*
|
|
56
|
+
* @default false
|
|
57
|
+
*/
|
|
58
|
+
protected _debug: boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Enables debug logging.
|
|
61
|
+
*
|
|
62
|
+
* @default false
|
|
63
|
+
*/
|
|
64
|
+
get debug(): typeof this._debug;
|
|
65
|
+
protected set debug(value: typeof this._debug);
|
|
66
|
+
/**
|
|
67
|
+
* The AbortController used to cancel network activities.
|
|
68
|
+
*
|
|
69
|
+
*/
|
|
70
|
+
protected _controller?: AbortController<ErrorCode>;
|
|
71
|
+
/**
|
|
72
|
+
* The AbortController used to cancel network activities.
|
|
73
|
+
*
|
|
74
|
+
*/
|
|
75
|
+
get controller(): typeof this._controller;
|
|
76
|
+
protected set controller(value: typeof this._controller);
|
|
77
|
+
/**
|
|
78
|
+
* The Xhr.timeout property is an unsigned long representing the number of milliseconds a request can take before
|
|
79
|
+
* automatically being terminated. The default value is 0, which means there is no timeout.
|
|
80
|
+
* When a timeout happens, a timeout event is fired.
|
|
81
|
+
*
|
|
82
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/timeout)
|
|
83
|
+
*
|
|
84
|
+
* @default 0
|
|
85
|
+
*/
|
|
86
|
+
protected _timeout: number | null;
|
|
87
|
+
/**
|
|
88
|
+
* The Xhr.timeout property is an unsigned long representing the number of milliseconds a request can take before
|
|
89
|
+
* automatically being terminated. The default value is 0, which means there is no timeout.
|
|
90
|
+
* When a timeout happens, a timeout event is fired.
|
|
91
|
+
*
|
|
92
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/timeout)
|
|
93
|
+
*
|
|
94
|
+
* @default 0
|
|
95
|
+
*/
|
|
96
|
+
get timeout(): typeof this._timeout;
|
|
97
|
+
protected set timeout(value: typeof this._timeout);
|
|
98
|
+
/**
|
|
99
|
+
* An object with `username` and `password` to send along with the request.
|
|
100
|
+
*
|
|
101
|
+
*/
|
|
102
|
+
protected _credentials?: XHR.Credentials | null;
|
|
103
|
+
/**
|
|
104
|
+
* An object with `username` and `password` to send along with the request.
|
|
105
|
+
*
|
|
106
|
+
*/
|
|
107
|
+
get credentials(): typeof this._credentials;
|
|
108
|
+
protected set credentials(value: typeof this._credentials);
|
|
109
|
+
/**
|
|
110
|
+
* The Xhr.withCredentials property is a boolean value that indicates whether or not cross-site Access-Control
|
|
111
|
+
* requests should be made using credentials such as cookies, authentication headers
|
|
112
|
+
* or TLS client certificates. Setting `withCredentials` has no effect on same-origin requests.
|
|
113
|
+
*
|
|
114
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/withCredentials)
|
|
115
|
+
*
|
|
116
|
+
* @default false
|
|
117
|
+
*/
|
|
118
|
+
protected _withCredentials: boolean | null;
|
|
119
|
+
/**
|
|
120
|
+
* The Xhr.withCredentials property is a boolean value that indicates whether or not cross-site Access-Control
|
|
121
|
+
* requests should be made using credentials such as cookies, authentication headers
|
|
122
|
+
* or TLS client certificates. Setting `withCredentials` has no effect on same-origin requests.
|
|
123
|
+
*
|
|
124
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/withCredentials)
|
|
125
|
+
*
|
|
126
|
+
* @default false
|
|
127
|
+
*/
|
|
128
|
+
get withCredentials(): typeof this._withCredentials;
|
|
129
|
+
protected set withCredentials(value: typeof this._withCredentials);
|
|
130
|
+
/**
|
|
131
|
+
* Indicates whether to automatically set the XHR response type based on the Response Content-Type Header.
|
|
132
|
+
*
|
|
133
|
+
*/
|
|
134
|
+
private autoResponseType;
|
|
135
|
+
/**
|
|
136
|
+
* Indicates whther event listeners have been registered.
|
|
137
|
+
*
|
|
138
|
+
*/
|
|
139
|
+
private listenersRegistered;
|
|
140
|
+
/** XHR progress events. */
|
|
141
|
+
static readonly ProgressEvents: XHR.Event.Progress[];
|
|
142
|
+
private static MapReadyStateToXhrEvent;
|
|
143
|
+
/**
|
|
144
|
+
* Construct a new instance of Xhr.
|
|
145
|
+
*
|
|
146
|
+
* @param options Required options for a proper initialization.
|
|
147
|
+
*/
|
|
148
|
+
constructor(options?: XHR.ConstructOptions);
|
|
149
|
+
/**
|
|
150
|
+
* Initialise XMLHttpRequest.
|
|
151
|
+
*
|
|
152
|
+
* @returns The current `Xhr` instance for chaining purposes.
|
|
153
|
+
*/
|
|
154
|
+
private init;
|
|
155
|
+
/**
|
|
156
|
+
* Send XMLHttpRequest.
|
|
157
|
+
*
|
|
158
|
+
* @returns The current `Xhr` instance for chaining purposes.
|
|
159
|
+
*/
|
|
160
|
+
send<T = TReturn>(options: XHR.Options): Xhr<T>;
|
|
161
|
+
/**
|
|
162
|
+
* Upload files via XMLHttpRequest.
|
|
163
|
+
*
|
|
164
|
+
* Use `Xhr.request.upload` to listen upload events.
|
|
165
|
+
*
|
|
166
|
+
* @returns The current `Xhr` instance for chaining purposes.
|
|
167
|
+
*/
|
|
168
|
+
upload<T = TReturn>(options: XHR.UploadOptions): Xhr<T>;
|
|
169
|
+
/**
|
|
170
|
+
* Get formatted response.
|
|
171
|
+
*
|
|
172
|
+
* @returns The response text or an object from a json response.
|
|
173
|
+
*/
|
|
174
|
+
getResponse<T = TReturn>(): T | null | undefined;
|
|
175
|
+
/**
|
|
176
|
+
* Cancels any network activity.
|
|
177
|
+
*
|
|
178
|
+
* @returns The current `Xhr` instance for chaining purposes.
|
|
179
|
+
*/
|
|
180
|
+
abort<T = ErrorCode, U = TReturn>(reason?: string, options?: AbortErrorOptions<T>): Xhr<U>;
|
|
181
|
+
/**
|
|
182
|
+
* Set the request headers.
|
|
183
|
+
*
|
|
184
|
+
* @returns The current `Xhr` instance for chaining purposes.
|
|
185
|
+
*/
|
|
186
|
+
setRequestHeaders<T = TReturn>(headers: Headers | HeadersInit): Xhr<T>;
|
|
187
|
+
/**
|
|
188
|
+
* Get Response Header.
|
|
189
|
+
*
|
|
190
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/getResponseHeader)
|
|
191
|
+
*
|
|
192
|
+
* @param name The Header name.
|
|
193
|
+
* @returns The Response Header value, `null` if none has been found.
|
|
194
|
+
*/
|
|
195
|
+
getResponseHeader<T = TReturn>(name: string): string | null;
|
|
196
|
+
/**
|
|
197
|
+
* Cancel any network activity an unregister all listeners.
|
|
198
|
+
*
|
|
199
|
+
* @returns The current `Xhr` instance for chaining purposes.
|
|
200
|
+
*/
|
|
201
|
+
destroy<T = TReturn>(): Xhr<T>;
|
|
202
|
+
/**
|
|
203
|
+
* Prints to `stdout` with newline.
|
|
204
|
+
*
|
|
205
|
+
* @param data The data print out.
|
|
206
|
+
* @returns The current `Xhr` instance for chaining purposes.
|
|
207
|
+
*/
|
|
208
|
+
log<T = TReturn>(...data: any[]): Xhr<T>;
|
|
209
|
+
/**
|
|
210
|
+
* On success functions.
|
|
211
|
+
*
|
|
212
|
+
* @returns The current `Xhr` instance for chaining purposes.
|
|
213
|
+
*/
|
|
214
|
+
private success;
|
|
215
|
+
/**
|
|
216
|
+
* On error functions.
|
|
217
|
+
*
|
|
218
|
+
* @returns The current `Xhr` instance for chaining purposes.
|
|
219
|
+
*/
|
|
220
|
+
private error;
|
|
221
|
+
/**
|
|
222
|
+
* Get XMLHttpRequest not available error.
|
|
223
|
+
*
|
|
224
|
+
* @returns The newly created error with `ErrorCode.XHR_NOT_AVAILABLE` code.
|
|
225
|
+
*/
|
|
226
|
+
private getXhrNotAvailableError;
|
|
227
|
+
private setupAbortController;
|
|
228
|
+
/**
|
|
229
|
+
* Automatically set `XMLHttpRequestResponseType` based on the received Response `Content-Type` Header.
|
|
230
|
+
*
|
|
231
|
+
* @returns The current `Xhr` instance for chaining purposes.
|
|
232
|
+
*/
|
|
233
|
+
private setResponseTypeFromResponseHeaders;
|
|
234
|
+
/**
|
|
235
|
+
* Convert MIME `Content-Type` to `XMLHttpRequestResponseType`.
|
|
236
|
+
*
|
|
237
|
+
* @param contentType (Optional) The MIME `Content-Type`. Default: `Content-Type` Response Header.
|
|
238
|
+
* @returns The `XMLHttpRequestResponseType` based on the given MIME `Content-Type`.
|
|
239
|
+
*/
|
|
240
|
+
private contentTypeToResponseType;
|
|
241
|
+
/**
|
|
242
|
+
* Get `Content-Type` Response Header.
|
|
243
|
+
*
|
|
244
|
+
* @returns The Response Header value, `null` if none has been found.
|
|
245
|
+
*/
|
|
246
|
+
getResponseContentType(): string | null;
|
|
247
|
+
/**
|
|
248
|
+
* Handle `readystatechange` events.
|
|
249
|
+
*
|
|
250
|
+
* @param event The Event interface.
|
|
251
|
+
*/
|
|
252
|
+
private onReadyStateChange;
|
|
253
|
+
/**
|
|
254
|
+
* Handle and emit progress events.
|
|
255
|
+
*
|
|
256
|
+
* @param event The ProgressEvent interface.
|
|
257
|
+
*/
|
|
258
|
+
private onProgressChange;
|
|
259
|
+
/**
|
|
260
|
+
* Executed when `Xhr.controller` get aborted through `Xhr.abort()` or `Xhr.controller.abort()` methods.
|
|
261
|
+
*
|
|
262
|
+
*/
|
|
263
|
+
private onControllerSignalAbort;
|
|
264
|
+
/**
|
|
265
|
+
* Emit ReadyStateChange events.
|
|
266
|
+
*
|
|
267
|
+
*/
|
|
268
|
+
private emitReadyStateEvent;
|
|
269
|
+
/**
|
|
270
|
+
* Add listeners to the XMLHttpRequest instance.
|
|
271
|
+
*
|
|
272
|
+
* @returns The current `Xhr` instance for chaining purposes.
|
|
273
|
+
*/
|
|
274
|
+
private registerListeners;
|
|
275
|
+
/**
|
|
276
|
+
* Remove listeners attached to the XMLHttpRequest instance.
|
|
277
|
+
*
|
|
278
|
+
* @returns The current `Xhr` instance for chaining purposes.
|
|
279
|
+
*/
|
|
280
|
+
private unregisterListeners;
|
|
281
|
+
}
|
|
282
|
+
//#endregion
|
|
283
|
+
//#region src/xhr/types.d.ts
|
|
284
|
+
declare namespace XHR {
|
|
285
|
+
type Method = RequestMethod;
|
|
286
|
+
type ReadyState = typeof XMLHttpRequest.UNSENT | typeof XMLHttpRequest.OPENED | typeof XMLHttpRequest.HEADERS_RECEIVED | typeof XMLHttpRequest.LOADING | typeof XMLHttpRequest.DONE;
|
|
287
|
+
type Credentials = {
|
|
288
|
+
/**
|
|
289
|
+
* The optional user name to use for authentication purposes.
|
|
290
|
+
*
|
|
291
|
+
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open#user)
|
|
292
|
+
*/
|
|
293
|
+
username?: string | null;
|
|
294
|
+
/**
|
|
295
|
+
* The optional user password to use for authentication purposes.
|
|
296
|
+
*
|
|
297
|
+
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open#password)
|
|
298
|
+
*/
|
|
299
|
+
password?: string | null;
|
|
300
|
+
};
|
|
301
|
+
namespace Event {
|
|
302
|
+
type Progress = keyof XMLHttpRequestEventTargetEventMap;
|
|
303
|
+
type ReadyStateChange = 'readystatechange' | 'unsent' | 'opened' | 'headers' | 'loading' | 'done';
|
|
304
|
+
type Map<TReturn = unknown> = {
|
|
305
|
+
init: [xhr: Xhr<TReturn>];
|
|
306
|
+
send: [xhr: Xhr<TReturn>];
|
|
307
|
+
success: [response: TReturn | null | undefined, xhr: Xhr<TReturn>];
|
|
308
|
+
error: [error: Exception<ErrorCode>, xhr: Xhr<TReturn>];
|
|
309
|
+
abort: [reason: AbortError<ErrorCode>, event: ProgressEvent<XMLHttpRequestEventTarget>, xhr: Xhr<TReturn>];
|
|
310
|
+
} & { [event in ReadyStateChange]: [event: Event, xhr: Xhr<TReturn>]; } & { [event in Exclude<XHR.Event.Progress, 'abort' | 'error'>]: [event: ProgressEvent<XMLHttpRequestEventTarget>, xhr: Xhr<TReturn>]; };
|
|
311
|
+
type Listener<TEvent extends keyof XHR.Event.Map<TReturn>, TReturn = unknown> = Listener<XHR.Event.Map<TReturn>, TEvent>;
|
|
312
|
+
}
|
|
313
|
+
interface ConstructOptions {
|
|
314
|
+
/**
|
|
315
|
+
* Enables debug logging.
|
|
316
|
+
*
|
|
317
|
+
* @default false
|
|
318
|
+
*/
|
|
319
|
+
debug?: boolean;
|
|
320
|
+
/**
|
|
321
|
+
* Automatically set the `responseType` from Response Content-Type Header if set to `true` and `responseType` hasn't been set.
|
|
322
|
+
*
|
|
323
|
+
* @default true
|
|
324
|
+
*/
|
|
325
|
+
autoResponseType?: boolean;
|
|
326
|
+
/**
|
|
327
|
+
* The Xhr.withCredentials property is a boolean value that indicates whether or not cross-site Access-Control
|
|
328
|
+
* requests should be made using credentials such as cookies, authentication headers
|
|
329
|
+
* or TLS client certificates. Setting `withCredentials` has no effect on same-origin requests.
|
|
330
|
+
*
|
|
331
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/withCredentials)
|
|
332
|
+
*
|
|
333
|
+
* @default false
|
|
334
|
+
*/
|
|
335
|
+
withCredentials?: XMLHttpRequest['withCredentials'] | null;
|
|
336
|
+
/**
|
|
337
|
+
* An object with `username` and `password` to send along with the request.
|
|
338
|
+
*
|
|
339
|
+
*/
|
|
340
|
+
credentials?: XHR.Credentials | null;
|
|
341
|
+
/**
|
|
342
|
+
* Can be set to a time in milliseconds. When set to a non-zero value will cause fetching to terminate after the given time has passed. When the time has passed, the request has not yet completed, and this's synchronous flag is unset, a timeout event will then be dispatched, or a "TimeoutError" DOMException will be thrown otherwise (for the send() method).
|
|
343
|
+
*
|
|
344
|
+
* When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object.
|
|
345
|
+
*
|
|
346
|
+
* @default 0
|
|
347
|
+
*/
|
|
348
|
+
timeout?: XMLHttpRequest['timeout'] | null;
|
|
349
|
+
}
|
|
350
|
+
interface InitOptions extends XHR.ConstructOptions {
|
|
351
|
+
/**
|
|
352
|
+
* The URL string or URL object the request is made to.
|
|
353
|
+
*
|
|
354
|
+
*/
|
|
355
|
+
url: UrlInput;
|
|
356
|
+
/**
|
|
357
|
+
* The request method.
|
|
358
|
+
*
|
|
359
|
+
* @default 'GET'
|
|
360
|
+
*/
|
|
361
|
+
method?: RequestMethod;
|
|
362
|
+
/**
|
|
363
|
+
* The request HeadersInit object.
|
|
364
|
+
*
|
|
365
|
+
*/
|
|
366
|
+
headers?: Headers | HeadersInit;
|
|
367
|
+
/**
|
|
368
|
+
* A custom controller object that allows you to abort one or more DOM requests as and when desired.
|
|
369
|
+
*
|
|
370
|
+
*/
|
|
371
|
+
controller?: AbortController<ErrorCode>;
|
|
372
|
+
/**
|
|
373
|
+
* The expected Response Type.
|
|
374
|
+
*
|
|
375
|
+
*/
|
|
376
|
+
responseType?: XMLHttpRequestResponseType;
|
|
377
|
+
}
|
|
378
|
+
interface Options extends Omit<XHR.InitOptions, 'eventsTarget'> {
|
|
379
|
+
/**
|
|
380
|
+
* The body object to send.
|
|
381
|
+
*
|
|
382
|
+
*/
|
|
383
|
+
body?: Document | XMLHttpRequestBodyInit;
|
|
384
|
+
}
|
|
385
|
+
interface UploadOptions extends Omit<XHR.Options, 'body'> {
|
|
386
|
+
/**
|
|
387
|
+
* The HTMLInputElement `FileList` or an array of `File` to upload.
|
|
388
|
+
*
|
|
389
|
+
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/files)
|
|
390
|
+
*/
|
|
391
|
+
files: File[] | FileList;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
//#endregion
|
|
395
|
+
//#region src/types/index.d.ts
|
|
396
|
+
type RequestMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';
|
|
397
|
+
//#endregion
|
|
398
|
+
export { Fetch as i, XHR as n, Xhr as r, RequestMethod as t };
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./error/index.cjs");let t=require("@alessiofrittoli/exception");const n=(n,r,i)=>globalThis.fetch(n,r).then(async n=>{let a=n.headers,o=a.get(`Content-Type`),s=o?.includes(`application/json`)||r?.responseType===`json`,c=o?.includes(`form-data`)||r?.responseType===`formdata`,l={response:n,headers:a,data:null,error:null};if(n.ok)return i?i(n):s?(l.data=await n.json(),l):c?(l.data=await n.formData(),l):r?.responseType===`arraybuffer`?(l.data=await n.arrayBuffer(),l):r?.responseType===`blob`?(l.data=await n.blob(),l):(l.data=await n.text(),l);if(s)throw await n.json();return l.error=new t.Exception({message:await n.text()||n.statusText,code:e.ErrorCode.UNKNOWN}),l}).catch(n=>({data:null,headers:null,response:null,error:t.Exception.isException(n)?new t.Exception(n):new t.Exception({...n,name:n.name,message:n.message,code:e.ErrorCode.UNKNOWN,cause:n})}));exports.fetch=n;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { i as Fetch } from "./index-D-vZzzH1.cjs";
|
|
2
|
+
import { AbortSignal } from "@alessiofrittoli/abort-controller";
|
|
3
|
+
//#region src/index.d.ts
|
|
4
|
+
interface RequestInit extends globalThis.RequestInit {
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* An extended version of the global fetch API.
|
|
9
|
+
*
|
|
10
|
+
* @param input The RequestInfo | URL.
|
|
11
|
+
* @param init The RequestInit.
|
|
12
|
+
* @param onfulfilled (Optional) A callback to run on Request fulfill. This could be used to alter the returned result.
|
|
13
|
+
* @returns An object with the parsed Request data, Request error, Request Response instance and Request Headers.
|
|
14
|
+
*/
|
|
15
|
+
export declare const fetch: <T, U extends RequestInit = RequestInit, V = Fetch.ReturnDataType<T, U>>(input: RequestInfo | URL, init?: U, onfulfilled?: Fetch.OnFulfilledCallback<V>) => Promise<Fetch.Result<V>>;
|
|
16
|
+
//#endregion
|
|
17
|
+
export {};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
interface ProgressEvent {
|
|
7
|
-
readonly type: keyof XMLHttpRequestEventTargetEventMap;
|
|
8
|
-
}
|
|
1
|
+
import { i as Fetch } from "./index-B8rmZCit.mjs";
|
|
2
|
+
import { AbortSignal } from "@alessiofrittoli/abort-controller";
|
|
3
|
+
//#region src/index.d.ts
|
|
4
|
+
interface RequestInit extends globalThis.RequestInit {
|
|
5
|
+
signal?: AbortSignal;
|
|
9
6
|
}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
7
|
+
/**
|
|
8
|
+
* An extended version of the global fetch API.
|
|
9
|
+
*
|
|
10
|
+
* @param input The RequestInfo | URL.
|
|
11
|
+
* @param init The RequestInit.
|
|
12
|
+
* @param onfulfilled (Optional) A callback to run on Request fulfill. This could be used to alter the returned result.
|
|
13
|
+
* @returns An object with the parsed Request data, Request error, Request Response instance and Request Headers.
|
|
14
|
+
*/
|
|
15
|
+
export declare const fetch: <T, U extends RequestInit = RequestInit, V = Fetch.ReturnDataType<T, U>>(input: RequestInfo | URL, init?: U, onfulfilled?: Fetch.OnFulfilledCallback<V>) => Promise<Fetch.Result<V>>;
|
|
16
|
+
//#endregion
|
|
17
|
+
export {};
|
package/dist/index.mjs
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ErrorCode as e}from"./error/index.mjs";import{Exception as t}from"@alessiofrittoli/exception";const n=(n,r,i)=>globalThis.fetch(n,r).then(async n=>{let a=n.headers,o=a.get(`Content-Type`),s=o?.includes(`application/json`)||r?.responseType===`json`,c=o?.includes(`form-data`)||r?.responseType===`formdata`,l={response:n,headers:a,data:null,error:null};if(n.ok)return i?i(n):s?(l.data=await n.json(),l):c?(l.data=await n.formData(),l):r?.responseType===`arraybuffer`?(l.data=await n.arrayBuffer(),l):r?.responseType===`blob`?(l.data=await n.blob(),l):(l.data=await n.text(),l);if(s)throw await n.json();return l.error=new t({message:await n.text()||n.statusText,code:e.UNKNOWN}),l}).catch(n=>({data:null,headers:null,response:null,error:t.isException(n)?new t(n):new t({...n,name:n.name,message:n.message,code:e.UNKNOWN,cause:n})}));export{n as fetch};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@alessiofrittoli/url-utils");const t=(t,n)=>navigator.sendBeacon(e.Url.format(t),n);exports.ping=t;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { UrlInput } from "@alessiofrittoli/url-utils";
|
|
2
|
+
//#region src/ping/index.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Asynchronously sends an HTTP POST request containing a small amount of data to a web server.
|
|
5
|
+
*
|
|
6
|
+
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon)
|
|
7
|
+
*/
|
|
8
|
+
export declare const ping: (url: UrlInput, data?: BodyInit | null) => boolean;
|
|
9
|
+
//#endregion
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { UrlInput } from "@alessiofrittoli/url-utils";
|
|
2
|
+
//#region src/ping/index.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Asynchronously sends an HTTP POST request containing a small amount of data to a web server.
|
|
5
|
+
*
|
|
6
|
+
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon)
|
|
7
|
+
*/
|
|
8
|
+
export declare const ping: (url: UrlInput, data?: BodyInit | null) => boolean;
|
|
9
|
+
//#endregion
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Url as e}from"@alessiofrittoli/url-utils";const t=(t,n)=>navigator.sendBeacon(e.format(t),n);export{t as ping};
|
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../error/index.cjs");let t=require("@alessiofrittoli/exception"),n=require("@alessiofrittoli/url-utils"),r=require("@alessiofrittoli/exception/abort"),i=require("@alessiofrittoli/abort-controller"),a=require("@alessiofrittoli/math-utils"),o=require("@alessiofrittoli/event-emitter");var s=class s extends o.EventEmitter{request;_requestId=(0,a.randomUUID)();get requestId(){return this._requestId}set requestId(e){this._requestId=e}_debug;get debug(){return this._debug}set debug(e){this._debug=e}_controller;get controller(){return this._controller}set controller(e){this._controller=e}_timeout;get timeout(){return this._timeout}set timeout(e){this._timeout=e}_credentials;get credentials(){return this._credentials}set credentials(e){this._credentials=e}_withCredentials;get withCredentials(){return this._withCredentials}set withCredentials(e){this._withCredentials=e}autoResponseType=!1;listenersRegistered=!1;static ProgressEvents=[`abort`,`timeout`,`error`,`loadstart`,`progress`,`load`,`loadend`];static MapReadyStateToXhrEvent={0:`unsent`,1:`opened`,2:`headers`,3:`loading`,4:`done`};constructor(e={}){super({captureRejections:!0}),this.request=typeof XMLHttpRequest<`u`?new XMLHttpRequest:null;let{credentials:t,withCredentials:n=!1,timeout:r=0,autoResponseType:i=!0,debug:a=!1}=e;this._debug=a,this._timeout=r,this._withCredentials=n,this._credentials=t,this.autoResponseType=i}init(e){if(!this.request)return this.error(this.getXhrNotAvailableError());let{url:t,method:r=`GET`,headers:i,controller:o,debug:s=this.debug,timeout:c=this.timeout,withCredentials:l=this.withCredentials,credentials:u=this.credentials,responseType:d,autoResponseType:f=this.autoResponseType}=e;return this.autoResponseType=f,this.requestId=(0,a.randomUUID)(),this.debug=s,this.request.open(r,n.Url.format(t),!0,u?.username,u?.password),this.request.timeout=c===null?0:c,this.request.withCredentials=l!==null&&l,d!==void 0&&(this.autoResponseType=!1,this.request.responseType=d),i&&this.setRequestHeaders(i),this.setupAbortController(o).registerListeners().emit(`init`,this),this.log(`Xhr initialized.`),this}send(n){if(!this.request)return this.error(this.getXhrNotAvailableError());this.request.readyState!==XMLHttpRequest.OPENED&&this.init(n);let{body:r}=n;try{return this.emit(`send`,this),this.request.send(r),this}catch(n){let r=n,i=r.name===t.ExceptionName.InvalidStateError?e.ErrorCode.XHR_INVALID_STATE:e.ErrorCode.UNKNOWN;return this.error(new t.Exception({...r,name:r.name,message:r.message,code:i,cause:r,isCritical:!0}))}}upload(e){let{files:t}=e,n=new FormData;return Array.from(t).forEach(e=>{n.append(e.name,e,e.name)}),this.send({...e,body:n})}getResponse(){if(!this.request)this.error(this.getXhrNotAvailableError());else return this.request.response}abort(e,t){return this.request?(this.controller?.abort(e,t),this):this.error(this.getXhrNotAvailableError())}setRequestHeaders(e){if(!this.request)return this.error(this.getXhrNotAvailableError());let t=new Headers(e);return Array.from(t.entries()).forEach(([e,t])=>{this.request.setRequestHeader(e,t)}),this}getResponseHeader(e){return this.request?this.request.getResponseHeader(e):(this.error(this.getXhrNotAvailableError()),null)}destroy(){return this.log({message:`Xhr destroyed.`}).abort(`Xhr has been destroyed.`,{code:e.ErrorCode.XHR_DESTROYED}).unregisterListeners().removeAllListeners()}log(...e){return this.debug&&console.log({class:`Xhr`,requestId:this.requestId},...e),this}success(e){return this.emit(`success`,e,this),this}error(e){if(this.listenerCount(`error`)===0)throw e;return this.emit(`error`,e,this),this}getXhrNotAvailableError(){return new t.Exception({message:`XMLHttpRequest not available.`,code:e.ErrorCode.XHR_NOT_AVAILABLE,isCritical:!0})}setupAbortController(e){let t=this.controller;return e&&(this.controller=e),(!this.controller||this.controller.signal.aborted)&&(this.controller=new i.AbortController,this.log({method:`.init()`},`new AbortController created.`)),t!==this.controller&&(this.log({method:`.init()`},`Register AbortSignal "abort" event listener.`),t?.signal.removeEventListener(`abort`,this.onControllerSignalAbort),this.controller.signal.addEventListener(`abort`,this.onControllerSignalAbort)),this}setResponseTypeFromResponseHeaders(){let e=this.getResponseContentType();return this.request.responseType=this.contentTypeToResponseType(e),this.log({method:`.setResponseTypeFromResponseHeaders()`,contentType:e,XhrResponseType:this.request.responseType},`Set XMLHttpRequest.responseType from Content-Type Response Headers.`),this}contentTypeToResponseType(e=this.getResponseContentType()){let t=e?.toLowerCase()||!1;return!t||t.includes(`text/plain`)?`text`:t.includes(`text/html`)||t.includes(`application/xml`)?`document`:t.includes(`application/json`)?`json`:t.startsWith(`image/`)||t.startsWith(`video/`)?`blob`:`arraybuffer`}getResponseContentType(){return this.getResponseHeader(`Content-Type`)}onReadyStateChange=async n=>{let{readyState:r,status:i}=this.request;if(this.log({event:`readystatechange`,readyState:r,status:this.request.status,data:n}),this.autoResponseType&&r===XMLHttpRequest.HEADERS_RECEIVED&&this.setResponseTypeFromResponseHeaders(),this.emit(`readystatechange`,n,this),r!==XMLHttpRequest.DONE||i<=0)return this.emitReadyStateEvent({readyState:r,event:n});let a=this.getResponse();if(i<100||i>=400){let{responseType:o}=this.request,{getErrorFromResponse:s}=await Promise.resolve().then(()=>require("../getErrorFromResponse-D3OARgUA.cjs")),c=await s({response:a,responseType:o});return this.emitReadyStateEvent({readyState:r,event:n}),c?this.error(c):this.error(new t.Exception({message:`Error from the server.`,code:e.ErrorCode.UNKNOWN,status:i,cause:a,isCritical:!0}))}return this.emitReadyStateEvent({readyState:r,event:n}),this.success(a)};onProgressChange=n=>{let{type:i}=n;if(this.log({event:i,data:n,progress:n.loaded/n.total*100},`${n.loaded} bytes transferred.`),i===`abort`){let t=this.controller?.signal.reason||new r.AbortError({message:`signal is aborted without reason`,code:e.ErrorCode.ABORT});return this.emit(`abort`,t,n,this)}if(i===`error`)return this.error(new t.Exception({message:`ProgressEvent Error`,code:e.ErrorCode.UNKNOWN,cause:n,isCritical:!0}));this.emit(i,n,this)};onControllerSignalAbort=()=>{this.log({method:`.onControllerSignalAbort()`,reason:this.controller?.signal.reason},`Abort XHR request.`),this.controller?.signal.removeEventListener(`abort`,this.onControllerSignalAbort),this.request.abort()};emitReadyStateEvent({readyState:e,event:t}){let n=s.MapReadyStateToXhrEvent[e];return this.emit(n,t,this),this.log({event:`readystatechange:${n}`,readyState:e,status:this.request.status,data:t}),this}registerListeners(){return this.request?(this.listenersRegistered||=(this.log({method:`.registerListeners()`},`Register "readystatechange" event listener.`),this.request.addEventListener(`readystatechange`,this.onReadyStateChange),s.ProgressEvents.map(e=>{this.log({method:`.registerListeners()`},`Register "${e}" event listener.`),this.request.addEventListener(e,this.onProgressChange)}),!0),this):this.error(this.getXhrNotAvailableError())}unregisterListeners(){return this.request?(this.listenersRegistered&&(this.listenersRegistered=!1,this.log({method:`.unregisterListeners()`},`Unregister "readystatechange" event listener.`),this.request.removeEventListener(`readystatechange`,this.onReadyStateChange),s.ProgressEvents.map(e=>{this.log({method:`.unregisterListeners()`},`Unregister "${e}" event listener.`),this.request.removeEventListener(e,this.onProgressChange)})),this):this.error(this.getXhrNotAvailableError())}};exports.Xhr=s;
|
package/dist/xhr/index.d.mts
CHANGED
|
@@ -1,8 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
import '@alessiofrittoli/event-emitter';
|
|
4
|
-
import '@alessiofrittoli/exception/abort';
|
|
5
|
-
import '@alessiofrittoli/abort-controller';
|
|
6
|
-
import '../error.mjs';
|
|
7
|
-
import '@alessiofrittoli/exception';
|
|
8
|
-
import '@alessiofrittoli/exception/code';
|
|
1
|
+
import { r as Xhr } from "../index-B8rmZCit.mjs";
|
|
2
|
+
export { Xhr };
|
package/dist/xhr/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ErrorCode as e}from"../error/index.mjs";import{Exception as t,ExceptionName as n}from"@alessiofrittoli/exception";import{Url as r}from"@alessiofrittoli/url-utils";import{AbortError as i}from"@alessiofrittoli/exception/abort";import{AbortController as a}from"@alessiofrittoli/abort-controller";import{randomUUID as o}from"@alessiofrittoli/math-utils";import{EventEmitter as s}from"@alessiofrittoli/event-emitter";var c=class c extends s{request;_requestId=o();get requestId(){return this._requestId}set requestId(e){this._requestId=e}_debug;get debug(){return this._debug}set debug(e){this._debug=e}_controller;get controller(){return this._controller}set controller(e){this._controller=e}_timeout;get timeout(){return this._timeout}set timeout(e){this._timeout=e}_credentials;get credentials(){return this._credentials}set credentials(e){this._credentials=e}_withCredentials;get withCredentials(){return this._withCredentials}set withCredentials(e){this._withCredentials=e}autoResponseType=!1;listenersRegistered=!1;static ProgressEvents=[`abort`,`timeout`,`error`,`loadstart`,`progress`,`load`,`loadend`];static MapReadyStateToXhrEvent={0:`unsent`,1:`opened`,2:`headers`,3:`loading`,4:`done`};constructor(e={}){super({captureRejections:!0}),this.request=typeof XMLHttpRequest<`u`?new XMLHttpRequest:null;let{credentials:t,withCredentials:n=!1,timeout:r=0,autoResponseType:i=!0,debug:a=!1}=e;this._debug=a,this._timeout=r,this._withCredentials=n,this._credentials=t,this.autoResponseType=i}init(e){if(!this.request)return this.error(this.getXhrNotAvailableError());let{url:t,method:n=`GET`,headers:i,controller:a,debug:s=this.debug,timeout:c=this.timeout,withCredentials:l=this.withCredentials,credentials:u=this.credentials,responseType:d,autoResponseType:f=this.autoResponseType}=e;return this.autoResponseType=f,this.requestId=o(),this.debug=s,this.request.open(n,r.format(t),!0,u?.username,u?.password),this.request.timeout=c===null?0:c,this.request.withCredentials=l!==null&&l,d!==void 0&&(this.autoResponseType=!1,this.request.responseType=d),i&&this.setRequestHeaders(i),this.setupAbortController(a).registerListeners().emit(`init`,this),this.log(`Xhr initialized.`),this}send(r){if(!this.request)return this.error(this.getXhrNotAvailableError());this.request.readyState!==XMLHttpRequest.OPENED&&this.init(r);let{body:i}=r;try{return this.emit(`send`,this),this.request.send(i),this}catch(r){let i=r,a=i.name===n.InvalidStateError?e.XHR_INVALID_STATE:e.UNKNOWN;return this.error(new t({...i,name:i.name,message:i.message,code:a,cause:i,isCritical:!0}))}}upload(e){let{files:t}=e,n=new FormData;return Array.from(t).forEach(e=>{n.append(e.name,e,e.name)}),this.send({...e,body:n})}getResponse(){if(!this.request)this.error(this.getXhrNotAvailableError());else return this.request.response}abort(e,t){return this.request?(this.controller?.abort(e,t),this):this.error(this.getXhrNotAvailableError())}setRequestHeaders(e){if(!this.request)return this.error(this.getXhrNotAvailableError());let t=new Headers(e);return Array.from(t.entries()).forEach(([e,t])=>{this.request.setRequestHeader(e,t)}),this}getResponseHeader(e){return this.request?this.request.getResponseHeader(e):(this.error(this.getXhrNotAvailableError()),null)}destroy(){return this.log({message:`Xhr destroyed.`}).abort(`Xhr has been destroyed.`,{code:e.XHR_DESTROYED}).unregisterListeners().removeAllListeners()}log(...e){return this.debug&&console.log({class:`Xhr`,requestId:this.requestId},...e),this}success(e){return this.emit(`success`,e,this),this}error(e){if(this.listenerCount(`error`)===0)throw e;return this.emit(`error`,e,this),this}getXhrNotAvailableError(){return new t({message:`XMLHttpRequest not available.`,code:e.XHR_NOT_AVAILABLE,isCritical:!0})}setupAbortController(e){let t=this.controller;return e&&(this.controller=e),(!this.controller||this.controller.signal.aborted)&&(this.controller=new a,this.log({method:`.init()`},`new AbortController created.`)),t!==this.controller&&(this.log({method:`.init()`},`Register AbortSignal "abort" event listener.`),t?.signal.removeEventListener(`abort`,this.onControllerSignalAbort),this.controller.signal.addEventListener(`abort`,this.onControllerSignalAbort)),this}setResponseTypeFromResponseHeaders(){let e=this.getResponseContentType();return this.request.responseType=this.contentTypeToResponseType(e),this.log({method:`.setResponseTypeFromResponseHeaders()`,contentType:e,XhrResponseType:this.request.responseType},`Set XMLHttpRequest.responseType from Content-Type Response Headers.`),this}contentTypeToResponseType(e=this.getResponseContentType()){let t=e?.toLowerCase()||!1;return!t||t.includes(`text/plain`)?`text`:t.includes(`text/html`)||t.includes(`application/xml`)?`document`:t.includes(`application/json`)?`json`:t.startsWith(`image/`)||t.startsWith(`video/`)?`blob`:`arraybuffer`}getResponseContentType(){return this.getResponseHeader(`Content-Type`)}onReadyStateChange=async n=>{let{readyState:r,status:i}=this.request;if(this.log({event:`readystatechange`,readyState:r,status:this.request.status,data:n}),this.autoResponseType&&r===XMLHttpRequest.HEADERS_RECEIVED&&this.setResponseTypeFromResponseHeaders(),this.emit(`readystatechange`,n,this),r!==XMLHttpRequest.DONE||i<=0)return this.emitReadyStateEvent({readyState:r,event:n});let a=this.getResponse();if(i<100||i>=400){let{responseType:o}=this.request,{getErrorFromResponse:s}=await import(`../getErrorFromResponse-CIppVMTN.mjs`),c=await s({response:a,responseType:o});return this.emitReadyStateEvent({readyState:r,event:n}),c?this.error(c):this.error(new t({message:`Error from the server.`,code:e.UNKNOWN,status:i,cause:a,isCritical:!0}))}return this.emitReadyStateEvent({readyState:r,event:n}),this.success(a)};onProgressChange=n=>{let{type:r}=n;if(this.log({event:r,data:n,progress:n.loaded/n.total*100},`${n.loaded} bytes transferred.`),r===`abort`){let t=this.controller?.signal.reason||new i({message:`signal is aborted without reason`,code:e.ABORT});return this.emit(`abort`,t,n,this)}if(r===`error`)return this.error(new t({message:`ProgressEvent Error`,code:e.UNKNOWN,cause:n,isCritical:!0}));this.emit(r,n,this)};onControllerSignalAbort=()=>{this.log({method:`.onControllerSignalAbort()`,reason:this.controller?.signal.reason},`Abort XHR request.`),this.controller?.signal.removeEventListener(`abort`,this.onControllerSignalAbort),this.request.abort()};emitReadyStateEvent({readyState:e,event:t}){let n=c.MapReadyStateToXhrEvent[e];return this.emit(n,t,this),this.log({event:`readystatechange:${n}`,readyState:e,status:this.request.status,data:t}),this}registerListeners(){return this.request?(this.listenersRegistered||=(this.log({method:`.registerListeners()`},`Register "readystatechange" event listener.`),this.request.addEventListener(`readystatechange`,this.onReadyStateChange),c.ProgressEvents.map(e=>{this.log({method:`.registerListeners()`},`Register "${e}" event listener.`),this.request.addEventListener(e,this.onProgressChange)}),!0),this):this.error(this.getXhrNotAvailableError())}unregisterListeners(){return this.request?(this.listenersRegistered&&(this.listenersRegistered=!1,this.log({method:`.unregisterListeners()`},`Unregister "readystatechange" event listener.`),this.request.removeEventListener(`readystatechange`,this.onReadyStateChange),c.ProgressEvents.map(e=>{this.log({method:`.unregisterListeners()`},`Unregister "${e}" event listener.`),this.request.removeEventListener(e,this.onProgressChange)})),this):this.error(this.getXhrNotAvailableError())}};export{c as Xhr};
|