@hyper-fetch/core 10.4.1 → 10.5.1
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/__tests__/features/request/request.exec.spec.ts +129 -0
- package/__tests__/features/request/request.signal.spec.ts +243 -0
- package/__tests__/features/request/request.throw-on-error.spec.ts +219 -0
- package/__tests__/features/request/request.typescript.spec.ts +46 -0
- package/dist/index.mjs +1529 -1394
- package/dist/index.mjs.map +1 -1
- package/dist/infinite/infinite.d.ts.map +1 -1
- package/dist/request/request.d.ts +10 -2
- package/dist/request/request.d.ts.map +1 -1
- package/dist/request/request.types.d.ts +15 -0
- package/dist/request/request.types.d.ts.map +1 -1
- package/dist/request/request.utils.d.ts +19 -1
- package/dist/request/request.utils.d.ts.map +1 -1
- package/dist/sdk/sdk.d.ts +1 -0
- package/dist/sdk/sdk.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/infinite/infinite.ts +2 -1
- package/src/request/request.ts +95 -26
- package/src/request/request.types.ts +15 -0
- package/src/request/request.utils.ts +148 -46
- package/src/sdk/sdk.ts +4 -0
package/dist/index.mjs
CHANGED
|
@@ -173,1427 +173,1427 @@ var Time = /* @__PURE__ */ function(Time) {
|
|
|
173
173
|
return Time;
|
|
174
174
|
}({});
|
|
175
175
|
//#endregion
|
|
176
|
-
//#region src/
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
function createRequestHooks(initial) {
|
|
188
|
-
const listeners = {
|
|
189
|
-
onBeforeSent: [],
|
|
190
|
-
onRequestStart: [],
|
|
191
|
-
onResponseStart: [],
|
|
192
|
-
onUploadProgress: [],
|
|
193
|
-
onDownloadProgress: [],
|
|
194
|
-
onResponse: [],
|
|
195
|
-
onRetry: [],
|
|
196
|
-
onRemove: []
|
|
197
|
-
};
|
|
198
|
-
if (initial) HOOK_NAMES.forEach((name) => {
|
|
199
|
-
listeners[name] = [...initial[name]];
|
|
176
|
+
//#region src/utils/error.utils.ts
|
|
177
|
+
/**
|
|
178
|
+
* Callbacks, listeners, plugins and optimistic handlers are the code of the user running inside of the request
|
|
179
|
+
* lifecycle. Their error can't break it, and it can't get lost either - it is thrown from a timer, outside of the
|
|
180
|
+
* lifecycle, so it reaches the error handlers of the environment (`window.onerror`, `uncaughtException`).
|
|
181
|
+
* @internal
|
|
182
|
+
* @param error value thrown by the user code
|
|
183
|
+
*/
|
|
184
|
+
var throwOutsideLifecycle = (error) => {
|
|
185
|
+
setTimeout(() => {
|
|
186
|
+
throw error;
|
|
200
187
|
});
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
188
|
+
};
|
|
189
|
+
/**
|
|
190
|
+
* Runs the code of the user in the middle of the request lifecycle. When it throws, the lifecycle goes on
|
|
191
|
+
* and the error is thrown outside of it.
|
|
192
|
+
* @internal
|
|
193
|
+
* @param callback code of the user to run
|
|
194
|
+
* @returns `true` when the callback finished, `false` when it threw
|
|
195
|
+
*/
|
|
196
|
+
var runUserCode = (callback) => {
|
|
197
|
+
try {
|
|
198
|
+
callback();
|
|
199
|
+
return true;
|
|
200
|
+
} catch (error) {
|
|
201
|
+
throwOutsideLifecycle(error);
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
//#endregion
|
|
206
|
+
//#region src/utils/uuid.utils.ts
|
|
207
|
+
var getUniqueRequestId = (request) => {
|
|
208
|
+
return `${request.queryKey}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;
|
|
209
|
+
};
|
|
210
|
+
//#endregion
|
|
211
|
+
//#region src/utils/emitter.utils.ts
|
|
212
|
+
var import_events = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
213
|
+
var R = typeof Reflect === "object" ? Reflect : null;
|
|
214
|
+
var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply(target, receiver, args) {
|
|
215
|
+
return Function.prototype.apply.call(target, receiver, args);
|
|
209
216
|
};
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
217
|
+
var ReflectOwnKeys;
|
|
218
|
+
if (R && typeof R.ownKeys === "function") ReflectOwnKeys = R.ownKeys;
|
|
219
|
+
else if (Object.getOwnPropertySymbols) ReflectOwnKeys = function ReflectOwnKeys(target) {
|
|
220
|
+
return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));
|
|
221
|
+
};
|
|
222
|
+
else ReflectOwnKeys = function ReflectOwnKeys(target) {
|
|
223
|
+
return Object.getOwnPropertyNames(target);
|
|
224
|
+
};
|
|
225
|
+
function ProcessEmitWarning(warning) {
|
|
226
|
+
if (console && console.warn) console.warn(warning);
|
|
227
|
+
}
|
|
228
|
+
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
|
|
229
|
+
return value !== value;
|
|
230
|
+
};
|
|
231
|
+
function EventEmitter() {
|
|
232
|
+
EventEmitter.init.call(this);
|
|
233
|
+
}
|
|
234
|
+
module.exports = EventEmitter;
|
|
235
|
+
module.exports.once = once;
|
|
236
|
+
EventEmitter.EventEmitter = EventEmitter;
|
|
237
|
+
EventEmitter.prototype._events = void 0;
|
|
238
|
+
EventEmitter.prototype._eventsCount = 0;
|
|
239
|
+
EventEmitter.prototype._maxListeners = void 0;
|
|
240
|
+
var defaultMaxListeners = 10;
|
|
241
|
+
function checkListener(listener) {
|
|
242
|
+
if (typeof listener !== "function") throw new TypeError("The \"listener\" argument must be of type Function. Received type " + typeof listener);
|
|
243
|
+
}
|
|
244
|
+
Object.defineProperty(EventEmitter, "defaultMaxListeners", {
|
|
245
|
+
enumerable: true,
|
|
246
|
+
get: function() {
|
|
247
|
+
return defaultMaxListeners;
|
|
223
248
|
},
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
snap[name] = [...listeners[name]];
|
|
228
|
-
});
|
|
229
|
-
return snap;
|
|
249
|
+
set: function(arg) {
|
|
250
|
+
if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) throw new RangeError("The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received " + arg + ".");
|
|
251
|
+
defaultMaxListeners = arg;
|
|
230
252
|
}
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
//#endregion
|
|
234
|
-
//#region src/mocker/mocker.ts
|
|
235
|
-
var mocker = async ({ request, requestId, onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, onResponseProgress, onRequestProgress, onResponseStart, onBeforeRequest, onRequestStart, onSuccess, adapter }) => {
|
|
236
|
-
if (!request.unstable_mock) throw new RequestProcessingError("Mock should be defined when calling mocker");
|
|
237
|
-
let thrown = false;
|
|
238
|
-
const { requestTime = 20, responseTime = 20, totalUploaded = 1e3, totalDownloaded = 1e3, timeout } = request.unstable_mock.config;
|
|
239
|
-
const result = await request.unstable_mock.fn({
|
|
240
|
-
request,
|
|
241
|
-
requestId
|
|
242
253
|
});
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
status: adapter.systemErrorStatus,
|
|
248
|
-
extra: adapter.systemErrorExtra,
|
|
249
|
-
onAbort: () => {
|
|
250
|
-
thrown = true;
|
|
254
|
+
EventEmitter.init = function() {
|
|
255
|
+
if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) {
|
|
256
|
+
this._events = Object.create(null);
|
|
257
|
+
this._eventsCount = 0;
|
|
251
258
|
}
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
+
this._maxListeners = this._maxListeners || void 0;
|
|
260
|
+
};
|
|
261
|
+
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
|
|
262
|
+
if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) throw new RangeError("The value of \"n\" is out of range. It must be a non-negative number. Received " + n + ".");
|
|
263
|
+
this._maxListeners = n;
|
|
264
|
+
return this;
|
|
265
|
+
};
|
|
266
|
+
function _getMaxListeners(that) {
|
|
267
|
+
if (that._maxListeners === void 0) return EventEmitter.defaultMaxListeners;
|
|
268
|
+
return that._maxListeners;
|
|
269
|
+
}
|
|
270
|
+
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
|
|
271
|
+
return _getMaxListeners(this);
|
|
272
|
+
};
|
|
273
|
+
EventEmitter.prototype.emit = function emit(type) {
|
|
274
|
+
var args = [];
|
|
275
|
+
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
|
|
276
|
+
var doError = type === "error";
|
|
277
|
+
var events = this._events;
|
|
278
|
+
if (events !== void 0) doError = doError && events.error === void 0;
|
|
279
|
+
else if (!doError) return false;
|
|
280
|
+
if (doError) {
|
|
281
|
+
var er;
|
|
282
|
+
if (args.length > 0) er = args[0];
|
|
283
|
+
if (er instanceof Error) throw er;
|
|
284
|
+
var err = /* @__PURE__ */ new Error("Unhandled error." + (er ? " (" + er.message + ")" : ""));
|
|
285
|
+
err.context = er;
|
|
286
|
+
throw err;
|
|
259
287
|
}
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
288
|
+
var handler = events[type];
|
|
289
|
+
if (handler === void 0) return false;
|
|
290
|
+
if (typeof handler === "function") ReflectApply(handler, this, args);
|
|
291
|
+
else {
|
|
292
|
+
var len = handler.length;
|
|
293
|
+
var listeners = arrayClone(handler, len);
|
|
294
|
+
for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args);
|
|
295
|
+
}
|
|
296
|
+
return true;
|
|
297
|
+
};
|
|
298
|
+
function _addListener(target, type, listener, prepend) {
|
|
299
|
+
var m;
|
|
300
|
+
var events;
|
|
301
|
+
var existing;
|
|
302
|
+
checkListener(listener);
|
|
303
|
+
events = target._events;
|
|
304
|
+
if (events === void 0) {
|
|
305
|
+
events = target._events = Object.create(null);
|
|
306
|
+
target._eventsCount = 0;
|
|
307
|
+
} else {
|
|
308
|
+
if (events.newListener !== void 0) {
|
|
309
|
+
target.emit("newListener", type, listener.listener ? listener.listener : listener);
|
|
310
|
+
events = target._events;
|
|
270
311
|
}
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
if (
|
|
278
|
-
|
|
279
|
-
|
|
312
|
+
existing = events[type];
|
|
313
|
+
}
|
|
314
|
+
if (existing === void 0) {
|
|
315
|
+
existing = events[type] = listener;
|
|
316
|
+
++target._eventsCount;
|
|
317
|
+
} else {
|
|
318
|
+
if (typeof existing === "function") existing = events[type] = prepend ? [listener, existing] : [existing, listener];
|
|
319
|
+
else if (prepend) existing.unshift(listener);
|
|
320
|
+
else existing.push(listener);
|
|
321
|
+
m = _getMaxListeners(target);
|
|
322
|
+
if (m > 0 && existing.length > m && !existing.warned) {
|
|
323
|
+
existing.warned = true;
|
|
324
|
+
var w = /* @__PURE__ */ new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit");
|
|
325
|
+
w.name = "MaxListenersExceededWarning";
|
|
326
|
+
w.emitter = target;
|
|
327
|
+
w.type = type;
|
|
328
|
+
w.count = existing.length;
|
|
329
|
+
ProcessEmitWarning(w);
|
|
280
330
|
}
|
|
281
|
-
}, interval);
|
|
282
|
-
});
|
|
283
|
-
let timeoutId;
|
|
284
|
-
if (typeof timeout === "number") timeoutId = setTimeout(() => {
|
|
285
|
-
thrown = true;
|
|
286
|
-
onTimeoutError({
|
|
287
|
-
status: 0,
|
|
288
|
-
extra
|
|
289
|
-
});
|
|
290
|
-
}, timeout);
|
|
291
|
-
if (!thrown) await progress(requestTime, totalUploaded, onRequestProgress);
|
|
292
|
-
if (!thrown) {
|
|
293
|
-
onRequestEnd();
|
|
294
|
-
onResponseStart();
|
|
295
|
-
}
|
|
296
|
-
if (!thrown) await progress(responseTime, totalDownloaded, onResponseProgress);
|
|
297
|
-
clearTimeout(timeoutId);
|
|
298
|
-
if (thrown) return;
|
|
299
|
-
if (success || error && data) onSuccess({
|
|
300
|
-
data,
|
|
301
|
-
error,
|
|
302
|
-
status,
|
|
303
|
-
extra
|
|
304
|
-
});
|
|
305
|
-
else onError({
|
|
306
|
-
error,
|
|
307
|
-
status,
|
|
308
|
-
extra
|
|
309
|
-
});
|
|
310
|
-
onResponseEnd();
|
|
311
|
-
};
|
|
312
|
-
//#endregion
|
|
313
|
-
//#region src/adapter/adapter.bindings.ts
|
|
314
|
-
var getAdapterBindings = async ({ request: baseRequest, requestId, resolve, onStartTime, internalErrorMapping }) => {
|
|
315
|
-
const { requestManager, loggerManager } = baseRequest.client;
|
|
316
|
-
const { unstable_payloadMapper } = baseRequest.client.adapter;
|
|
317
|
-
const logger = loggerManager.initialize(baseRequest.client, "Adapter");
|
|
318
|
-
let requestStartTimestamp = null;
|
|
319
|
-
let responseStartTimestamp = null;
|
|
320
|
-
let request = baseRequest;
|
|
321
|
-
let requestTotal = 1;
|
|
322
|
-
let responseTotal = 1;
|
|
323
|
-
let previousRequestProgress = null;
|
|
324
|
-
let previousResponseProgress = null;
|
|
325
|
-
const isSameProgress = (previous, next) => !!previous && previous.total === next.total && previous.loaded === next.loaded;
|
|
326
|
-
logger.debug({
|
|
327
|
-
title: `Running middleware callbacks`,
|
|
328
|
-
type: "request",
|
|
329
|
-
extra: {
|
|
330
|
-
request,
|
|
331
|
-
requestId
|
|
332
331
|
}
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
const { client, abortKey } = request;
|
|
338
|
-
const scopedAbortKey = scopeKey(abortKey, request.scope);
|
|
339
|
-
let payload = request.payload;
|
|
340
|
-
if (request.unstable_payloadMapper) payload = await request.unstable_payloadMapper(request.payload);
|
|
341
|
-
else if (unstable_payloadMapper) payload = await unstable_payloadMapper(payload);
|
|
342
|
-
const adapterDefaults = client.adapter.unstable_getAdapterDefaults?.(request);
|
|
343
|
-
const adapterOptions = adapterDefaults ? {
|
|
344
|
-
...adapterDefaults,
|
|
345
|
-
...request.options
|
|
346
|
-
} : request.options;
|
|
347
|
-
const startTime = Date.now();
|
|
348
|
-
onStartTime(startTime);
|
|
349
|
-
const getRequestStartTimestamp = () => {
|
|
350
|
-
return requestStartTimestamp;
|
|
351
|
-
};
|
|
352
|
-
const getResponseStartTimestamp = () => {
|
|
353
|
-
return responseStartTimestamp;
|
|
332
|
+
return target;
|
|
333
|
+
}
|
|
334
|
+
EventEmitter.prototype.addListener = function addListener(type, listener) {
|
|
335
|
+
return _addListener(this, type, listener, false);
|
|
354
336
|
};
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
const loaded = Number(progress.loaded || 0);
|
|
359
|
-
return Math.max(total, loaded, previousTotal);
|
|
337
|
+
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
|
|
338
|
+
EventEmitter.prototype.prependListener = function prependListener(type, listener) {
|
|
339
|
+
return _addListener(this, type, listener, true);
|
|
360
340
|
};
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
};
|
|
368
|
-
requestManager.events.emitUploadProgress({
|
|
369
|
-
...progress,
|
|
370
|
-
requestId,
|
|
371
|
-
request
|
|
372
|
-
});
|
|
341
|
+
function onceWrapper() {
|
|
342
|
+
if (!this.fired) {
|
|
343
|
+
this.target.removeListener(this.type, this.wrapFn);
|
|
344
|
+
this.fired = true;
|
|
345
|
+
if (arguments.length === 0) return this.listener.call(this.target);
|
|
346
|
+
return this.listener.apply(this.target, arguments);
|
|
373
347
|
}
|
|
348
|
+
}
|
|
349
|
+
function _onceWrap(target, type, listener) {
|
|
350
|
+
var state = {
|
|
351
|
+
fired: false,
|
|
352
|
+
wrapFn: void 0,
|
|
353
|
+
target,
|
|
354
|
+
type,
|
|
355
|
+
listener
|
|
356
|
+
};
|
|
357
|
+
var wrapped = onceWrapper.bind(state);
|
|
358
|
+
wrapped.listener = listener;
|
|
359
|
+
state.wrapFn = wrapped;
|
|
360
|
+
return wrapped;
|
|
361
|
+
}
|
|
362
|
+
EventEmitter.prototype.once = function once(type, listener) {
|
|
363
|
+
checkListener(listener);
|
|
364
|
+
this.on(type, _onceWrap(this, type, listener));
|
|
365
|
+
return this;
|
|
374
366
|
};
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
total: progress.total,
|
|
380
|
-
loaded: progress.loaded
|
|
381
|
-
};
|
|
382
|
-
requestManager.events.emitDownloadProgress({
|
|
383
|
-
...progress,
|
|
384
|
-
requestId,
|
|
385
|
-
request
|
|
386
|
-
});
|
|
387
|
-
}
|
|
367
|
+
EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) {
|
|
368
|
+
checkListener(listener);
|
|
369
|
+
this.prependListener(type, _onceWrap(this, type, listener));
|
|
370
|
+
return this;
|
|
388
371
|
};
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
372
|
+
EventEmitter.prototype.removeListener = function removeListener(type, listener) {
|
|
373
|
+
var list, events, position, i, originalListener;
|
|
374
|
+
checkListener(listener);
|
|
375
|
+
events = this._events;
|
|
376
|
+
if (events === void 0) return this;
|
|
377
|
+
list = events[type];
|
|
378
|
+
if (list === void 0) return this;
|
|
379
|
+
if (list === listener || list.listener === listener) if (--this._eventsCount === 0) this._events = Object.create(null);
|
|
380
|
+
else {
|
|
381
|
+
delete events[type];
|
|
382
|
+
if (events.removeListener) this.emit("removeListener", type, list.listener || listener);
|
|
383
|
+
}
|
|
384
|
+
else if (typeof list !== "function") {
|
|
385
|
+
position = -1;
|
|
386
|
+
for (i = list.length - 1; i >= 0; i--) if (list[i] === listener || list[i].listener === listener) {
|
|
387
|
+
originalListener = list[i].listener;
|
|
388
|
+
position = i;
|
|
389
|
+
break;
|
|
396
390
|
}
|
|
397
|
-
|
|
398
|
-
|
|
391
|
+
if (position < 0) return this;
|
|
392
|
+
if (position === 0) list.shift();
|
|
393
|
+
else spliceOne(list, position);
|
|
394
|
+
if (list.length === 1) events[type] = list[0];
|
|
395
|
+
if (events.removeListener !== void 0) this.emit("removeListener", type, originalListener || listener);
|
|
396
|
+
}
|
|
397
|
+
return this;
|
|
399
398
|
};
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
399
|
+
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
|
|
400
|
+
EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) {
|
|
401
|
+
var listeners, events = this._events, i;
|
|
402
|
+
if (events === void 0) return this;
|
|
403
|
+
if (events.removeListener === void 0) {
|
|
404
|
+
if (arguments.length === 0) {
|
|
405
|
+
this._events = Object.create(null);
|
|
406
|
+
this._eventsCount = 0;
|
|
407
|
+
} else if (events[type] !== void 0) if (--this._eventsCount === 0) this._events = Object.create(null);
|
|
408
|
+
else delete events[type];
|
|
409
|
+
return this;
|
|
410
|
+
}
|
|
411
|
+
if (arguments.length === 0) {
|
|
412
|
+
var keys = Object.keys(events);
|
|
413
|
+
var key;
|
|
414
|
+
for (i = 0; i < keys.length; ++i) {
|
|
415
|
+
key = keys[i];
|
|
416
|
+
if (key === "removeListener") continue;
|
|
417
|
+
this.removeAllListeners(key);
|
|
407
418
|
}
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
requestManager.events.emitRequestStart({
|
|
418
|
-
requestId,
|
|
419
|
-
request
|
|
420
|
-
});
|
|
421
|
-
return requestStartTimestamp;
|
|
419
|
+
this.removeAllListeners("removeListener");
|
|
420
|
+
this._events = Object.create(null);
|
|
421
|
+
this._eventsCount = 0;
|
|
422
|
+
return this;
|
|
423
|
+
}
|
|
424
|
+
listeners = events[type];
|
|
425
|
+
if (typeof listeners === "function") this.removeListener(type, listeners);
|
|
426
|
+
else if (listeners !== void 0) for (i = listeners.length - 1; i >= 0; i--) this.removeListener(type, listeners[i]);
|
|
427
|
+
return this;
|
|
422
428
|
};
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
429
|
+
function _listeners(target, type, unwrap) {
|
|
430
|
+
var events = target._events;
|
|
431
|
+
if (events === void 0) return [];
|
|
432
|
+
var evlistener = events[type];
|
|
433
|
+
if (evlistener === void 0) return [];
|
|
434
|
+
if (typeof evlistener === "function") return unwrap ? [evlistener.listener || evlistener] : [evlistener];
|
|
435
|
+
return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
|
|
436
|
+
}
|
|
437
|
+
EventEmitter.prototype.listeners = function listeners(type) {
|
|
438
|
+
return _listeners(this, type, true);
|
|
432
439
|
};
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
const progressTimestamp = Date.now();
|
|
436
|
-
handleRequestProgress(requestStartTimestamp, progressTimestamp, {
|
|
437
|
-
total: requestTotal,
|
|
438
|
-
loaded: requestTotal
|
|
439
|
-
});
|
|
440
|
-
return progressTimestamp;
|
|
440
|
+
EventEmitter.prototype.rawListeners = function rawListeners(type) {
|
|
441
|
+
return _listeners(this, type, false);
|
|
441
442
|
};
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
const initialPayload = {
|
|
446
|
-
total: responseTotal,
|
|
447
|
-
loaded: progress?.loaded || 0
|
|
448
|
-
};
|
|
449
|
-
handleResponseProgress(responseStartTimestamp, responseStartTimestamp, initialPayload);
|
|
450
|
-
requestManager.events.emitResponseStart({
|
|
451
|
-
requestId,
|
|
452
|
-
request
|
|
453
|
-
});
|
|
454
|
-
return responseStartTimestamp;
|
|
443
|
+
EventEmitter.listenerCount = function(emitter, type) {
|
|
444
|
+
if (typeof emitter.listenerCount === "function") return emitter.listenerCount(type);
|
|
445
|
+
else return listenerCount.call(emitter, type);
|
|
455
446
|
};
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
});
|
|
464
|
-
return progressTimestamp;
|
|
465
|
-
};
|
|
466
|
-
const onResponseEnd = () => {
|
|
467
|
-
if (!responseStartTimestamp) responseStartTimestamp = Date.now();
|
|
468
|
-
const progressTimestamp = Date.now();
|
|
469
|
-
handleResponseProgress(responseStartTimestamp, progressTimestamp, {
|
|
470
|
-
total: responseTotal,
|
|
471
|
-
loaded: responseTotal
|
|
472
|
-
});
|
|
473
|
-
return progressTimestamp;
|
|
474
|
-
};
|
|
475
|
-
const onSuccess = async ({ data, error, status, extra }) => {
|
|
476
|
-
let response = {
|
|
477
|
-
data,
|
|
478
|
-
error: error ?? null,
|
|
479
|
-
success: true,
|
|
480
|
-
status,
|
|
481
|
-
extra,
|
|
482
|
-
requestTimestamp: startTime,
|
|
483
|
-
responseTimestamp: Date.now()
|
|
484
|
-
};
|
|
485
|
-
try {
|
|
486
|
-
response = await request.client.unstable_modifyResponse?.(response, request);
|
|
487
|
-
response = await request.client.unstable_modifySuccessResponse?.(response, request);
|
|
488
|
-
client.triggerPlugins("onRequestSuccess", {
|
|
489
|
-
response,
|
|
490
|
-
request
|
|
491
|
-
});
|
|
492
|
-
client.triggerPlugins("onRequestFinished", {
|
|
493
|
-
response,
|
|
494
|
-
request
|
|
495
|
-
});
|
|
496
|
-
} catch (interceptorError) {
|
|
497
|
-
response = {
|
|
498
|
-
data: null,
|
|
499
|
-
error: internalErrorMapping(interceptorError),
|
|
500
|
-
success: false,
|
|
501
|
-
status,
|
|
502
|
-
extra,
|
|
503
|
-
requestTimestamp: startTime,
|
|
504
|
-
responseTimestamp: Date.now()
|
|
505
|
-
};
|
|
447
|
+
EventEmitter.prototype.listenerCount = listenerCount;
|
|
448
|
+
function listenerCount(type) {
|
|
449
|
+
var events = this._events;
|
|
450
|
+
if (events !== void 0) {
|
|
451
|
+
var evlistener = events[type];
|
|
452
|
+
if (typeof evlistener === "function") return 1;
|
|
453
|
+
else if (evlistener !== void 0) return evlistener.length;
|
|
506
454
|
}
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
extra: {
|
|
512
|
-
request,
|
|
513
|
-
requestId,
|
|
514
|
-
response
|
|
515
|
-
}
|
|
516
|
-
});
|
|
517
|
-
return response;
|
|
455
|
+
return 0;
|
|
456
|
+
}
|
|
457
|
+
EventEmitter.prototype.eventNames = function eventNames() {
|
|
458
|
+
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
|
|
518
459
|
};
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
460
|
+
function arrayClone(arr, n) {
|
|
461
|
+
var copy = new Array(n);
|
|
462
|
+
for (var i = 0; i < n; ++i) copy[i] = arr[i];
|
|
463
|
+
return copy;
|
|
464
|
+
}
|
|
465
|
+
function spliceOne(list, index) {
|
|
466
|
+
for (; index + 1 < list.length; index++) list[index] = list[index + 1];
|
|
467
|
+
list.pop();
|
|
468
|
+
}
|
|
469
|
+
function unwrapListeners(arr) {
|
|
470
|
+
var ret = new Array(arr.length);
|
|
471
|
+
for (var i = 0; i < ret.length; ++i) ret[i] = arr[i].listener || arr[i];
|
|
472
|
+
return ret;
|
|
473
|
+
}
|
|
474
|
+
function once(emitter, name) {
|
|
475
|
+
return new Promise(function(resolve, reject) {
|
|
476
|
+
function errorListener(err) {
|
|
477
|
+
emitter.removeListener(name, resolver);
|
|
478
|
+
reject(err);
|
|
533
479
|
}
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
status,
|
|
538
|
-
extra
|
|
539
|
-
});
|
|
540
|
-
};
|
|
541
|
-
const onTimeoutError = ({ status, extra }) => {
|
|
542
|
-
logger.error({
|
|
543
|
-
title: `Timeout error`,
|
|
544
|
-
type: "request",
|
|
545
|
-
extra: {
|
|
546
|
-
request,
|
|
547
|
-
requestId
|
|
480
|
+
function resolver() {
|
|
481
|
+
if (typeof emitter.removeListener === "function") emitter.removeListener("error", errorListener);
|
|
482
|
+
resolve([].slice.call(arguments));
|
|
548
483
|
}
|
|
484
|
+
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
|
|
485
|
+
if (name !== "error") addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
|
|
549
486
|
});
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
487
|
+
}
|
|
488
|
+
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
|
|
489
|
+
if (typeof emitter.on === "function") eventTargetAgnosticAddListener(emitter, "error", handler, flags);
|
|
490
|
+
}
|
|
491
|
+
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
|
|
492
|
+
if (typeof emitter.on === "function") if (flags.once) emitter.once(name, listener);
|
|
493
|
+
else emitter.on(name, listener);
|
|
494
|
+
else if (typeof emitter.addEventListener === "function") emitter.addEventListener(name, function wrapListener(arg) {
|
|
495
|
+
if (flags.once) emitter.removeEventListener(name, wrapListener);
|
|
496
|
+
listener(arg);
|
|
554
497
|
});
|
|
498
|
+
else throw new TypeError("The \"emitter\" argument must be of type EventEmitter. Received type " + typeof emitter);
|
|
499
|
+
}
|
|
500
|
+
})))());
|
|
501
|
+
var getListenName = (event) => `listen_${String(event)}`;
|
|
502
|
+
var EventEmitter = class extends import_events.default {
|
|
503
|
+
emitCallbacks = [];
|
|
504
|
+
constructor(options) {
|
|
505
|
+
super(options);
|
|
506
|
+
}
|
|
507
|
+
emit(type, data, isTriggeredExternally) {
|
|
508
|
+
const params = [type, data];
|
|
509
|
+
if (isTriggeredExternally) params.push(isTriggeredExternally);
|
|
510
|
+
this.emitCallbacks?.forEach((callback) => runUserCode(() => callback(...params)));
|
|
511
|
+
const listeners = this.rawListeners(type);
|
|
512
|
+
listeners.forEach((listener) => runUserCode(() => listener.call(this, ...params.slice(1))));
|
|
513
|
+
return listeners.length > 0;
|
|
514
|
+
}
|
|
515
|
+
onEmit = (callback) => {
|
|
516
|
+
this.emitCallbacks?.push(callback);
|
|
517
|
+
return () => {
|
|
518
|
+
this.emitCallbacks = this.emitCallbacks?.filter((cb) => cb !== callback);
|
|
519
|
+
};
|
|
555
520
|
};
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
request,
|
|
562
|
-
requestId
|
|
563
|
-
}
|
|
564
|
-
});
|
|
565
|
-
return onError({
|
|
566
|
-
error: internalErrorMapping(getErrorMessage()),
|
|
567
|
-
status,
|
|
568
|
-
extra
|
|
569
|
-
});
|
|
521
|
+
onListener = (event, listener) => {
|
|
522
|
+
super.on(getListenName(event), listener);
|
|
523
|
+
return () => {
|
|
524
|
+
super.off(getListenName(event), listener);
|
|
525
|
+
};
|
|
570
526
|
};
|
|
571
|
-
|
|
572
|
-
|
|
527
|
+
on = (event, listener) => {
|
|
528
|
+
super.on(event, listener);
|
|
529
|
+
super.emit(getListenName(event), super.listeners(event).length);
|
|
530
|
+
return this;
|
|
573
531
|
};
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
onAbortError({
|
|
579
|
-
status,
|
|
580
|
-
extra
|
|
581
|
-
});
|
|
582
|
-
onAbort();
|
|
583
|
-
requestManager.events.emitAbort({
|
|
584
|
-
requestId,
|
|
585
|
-
request
|
|
586
|
-
});
|
|
587
|
-
};
|
|
588
|
-
if (controller.signal.aborted) abort();
|
|
589
|
-
controller.signal.addEventListener("abort", abort);
|
|
590
|
-
return () => controller.signal.removeEventListener("abort", abort);
|
|
532
|
+
off = (event, listener) => {
|
|
533
|
+
super.off(event, listener);
|
|
534
|
+
super.emit(getListenName(event), super.listeners(event).length);
|
|
535
|
+
return this;
|
|
591
536
|
};
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
537
|
+
addListener = this.on;
|
|
538
|
+
removeListener = this.off;
|
|
539
|
+
};
|
|
540
|
+
//#endregion
|
|
541
|
+
//#region src/request/request.hooks.ts
|
|
542
|
+
var HOOK_NAMES = [
|
|
543
|
+
"onBeforeSent",
|
|
544
|
+
"onRequestStart",
|
|
545
|
+
"onResponseStart",
|
|
546
|
+
"onUploadProgress",
|
|
547
|
+
"onDownloadProgress",
|
|
548
|
+
"onResponse",
|
|
549
|
+
"onRetry",
|
|
550
|
+
"onRemove"
|
|
551
|
+
];
|
|
552
|
+
function createRequestHooks(initial) {
|
|
553
|
+
const listeners = {
|
|
554
|
+
onBeforeSent: [],
|
|
555
|
+
onRequestStart: [],
|
|
556
|
+
onResponseStart: [],
|
|
557
|
+
onUploadProgress: [],
|
|
558
|
+
onDownloadProgress: [],
|
|
559
|
+
onResponse: [],
|
|
560
|
+
onRetry: [],
|
|
561
|
+
onRemove: []
|
|
562
|
+
};
|
|
563
|
+
if (initial) HOOK_NAMES.forEach((name) => {
|
|
564
|
+
listeners[name] = [...initial[name]];
|
|
601
565
|
});
|
|
602
|
-
const
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
566
|
+
const subscribe = (name) => {
|
|
567
|
+
return (cb) => {
|
|
568
|
+
listeners[name].push(cb);
|
|
569
|
+
return () => {
|
|
570
|
+
const idx = listeners[name].indexOf(cb);
|
|
571
|
+
if (idx !== -1) listeners[name].splice(idx, 1);
|
|
572
|
+
};
|
|
573
|
+
};
|
|
574
|
+
};
|
|
606
575
|
return {
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
onSuccess,
|
|
628
|
-
onAbortError,
|
|
629
|
-
onTimeoutError,
|
|
630
|
-
onUnexpectedError,
|
|
631
|
-
onError
|
|
576
|
+
onBeforeSent: subscribe("onBeforeSent"),
|
|
577
|
+
onRequestStart: subscribe("onRequestStart"),
|
|
578
|
+
onResponseStart: subscribe("onResponseStart"),
|
|
579
|
+
onUploadProgress: subscribe("onUploadProgress"),
|
|
580
|
+
onDownloadProgress: subscribe("onDownloadProgress"),
|
|
581
|
+
onResponse: subscribe("onResponse"),
|
|
582
|
+
onRetry: subscribe("onRetry"),
|
|
583
|
+
onRemove: subscribe("onRemove"),
|
|
584
|
+
__emit(name, data) {
|
|
585
|
+
listeners[name].forEach((cb) => {
|
|
586
|
+
cb(data);
|
|
587
|
+
});
|
|
588
|
+
},
|
|
589
|
+
__snapshot() {
|
|
590
|
+
const snap = {};
|
|
591
|
+
HOOK_NAMES.forEach((name) => {
|
|
592
|
+
snap[name] = [...listeners[name]];
|
|
593
|
+
});
|
|
594
|
+
return snap;
|
|
595
|
+
}
|
|
632
596
|
};
|
|
597
|
+
}
|
|
598
|
+
//#endregion
|
|
599
|
+
//#region src/mocker/mocker.ts
|
|
600
|
+
var mocker = async ({ request, requestId, onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, onResponseProgress, onRequestProgress, onResponseStart, onBeforeRequest, onRequestStart, onSuccess, adapter }) => {
|
|
601
|
+
if (!request.unstable_mock) throw new RequestProcessingError("Mock should be defined when calling mocker");
|
|
602
|
+
let thrown = false;
|
|
603
|
+
const { requestTime = 20, responseTime = 20, totalUploaded = 1e3, totalDownloaded = 1e3, timeout } = request.unstable_mock.config;
|
|
604
|
+
const result = await request.unstable_mock.fn({
|
|
605
|
+
request,
|
|
606
|
+
requestId
|
|
607
|
+
});
|
|
608
|
+
const { data, error, status, extra = request.client.adapter.defaultExtra } = result;
|
|
609
|
+
const hasData = data !== void 0 && data !== null;
|
|
610
|
+
const { success = !error || hasData } = result;
|
|
611
|
+
createAbortListener({
|
|
612
|
+
status: adapter.systemErrorStatus,
|
|
613
|
+
extra: adapter.systemErrorExtra,
|
|
614
|
+
onAbort: () => {
|
|
615
|
+
thrown = true;
|
|
616
|
+
}
|
|
617
|
+
});
|
|
618
|
+
onBeforeRequest();
|
|
619
|
+
onRequestStart();
|
|
620
|
+
const progress = (totalTime, totalSize, progressFunction) => new Promise((resolveProgress) => {
|
|
621
|
+
if (thrown) {
|
|
622
|
+
resolveProgress(true);
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
625
|
+
const interval = 20;
|
|
626
|
+
const dataStart = Date.now();
|
|
627
|
+
const intervals = Math.ceil(totalTime / interval);
|
|
628
|
+
const chunkSize = Math.ceil(totalSize / intervals);
|
|
629
|
+
let currentlyLoaded = 0;
|
|
630
|
+
const timer = setInterval(function handleProgressInterval() {
|
|
631
|
+
if (thrown) {
|
|
632
|
+
resolveProgress(true);
|
|
633
|
+
clearInterval(timer);
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
const currentTime = Math.min(totalTime, Date.now() - dataStart);
|
|
637
|
+
currentlyLoaded += currentlyLoaded + chunkSize >= totalSize ? totalSize - currentlyLoaded : chunkSize;
|
|
638
|
+
progressFunction({
|
|
639
|
+
total: totalSize,
|
|
640
|
+
loaded: currentTime >= totalTime ? totalSize : currentlyLoaded
|
|
641
|
+
});
|
|
642
|
+
if (currentTime >= totalTime) {
|
|
643
|
+
resolveProgress(true);
|
|
644
|
+
clearInterval(timer);
|
|
645
|
+
}
|
|
646
|
+
}, interval);
|
|
647
|
+
});
|
|
648
|
+
let timeoutId;
|
|
649
|
+
if (typeof timeout === "number") timeoutId = setTimeout(() => {
|
|
650
|
+
thrown = true;
|
|
651
|
+
onTimeoutError({
|
|
652
|
+
status: 0,
|
|
653
|
+
extra
|
|
654
|
+
});
|
|
655
|
+
}, timeout);
|
|
656
|
+
if (!thrown) await progress(requestTime, totalUploaded, onRequestProgress);
|
|
657
|
+
if (!thrown) {
|
|
658
|
+
onRequestEnd();
|
|
659
|
+
onResponseStart();
|
|
660
|
+
}
|
|
661
|
+
if (!thrown) await progress(responseTime, totalDownloaded, onResponseProgress);
|
|
662
|
+
clearTimeout(timeoutId);
|
|
663
|
+
if (thrown) return;
|
|
664
|
+
if (success || error && data) onSuccess({
|
|
665
|
+
data,
|
|
666
|
+
error,
|
|
667
|
+
status,
|
|
668
|
+
extra
|
|
669
|
+
});
|
|
670
|
+
else onError({
|
|
671
|
+
error,
|
|
672
|
+
status,
|
|
673
|
+
extra
|
|
674
|
+
});
|
|
675
|
+
onResponseEnd();
|
|
633
676
|
};
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
677
|
+
//#endregion
|
|
678
|
+
//#region src/adapter/adapter.bindings.ts
|
|
679
|
+
var getAdapterBindings = async ({ request: baseRequest, requestId, resolve, onStartTime, internalErrorMapping }) => {
|
|
680
|
+
const { requestManager, loggerManager } = baseRequest.client;
|
|
681
|
+
const { unstable_payloadMapper } = baseRequest.client.adapter;
|
|
682
|
+
const logger = loggerManager.initialize(baseRequest.client, "Adapter");
|
|
683
|
+
let requestStartTimestamp = null;
|
|
684
|
+
let responseStartTimestamp = null;
|
|
685
|
+
let request = baseRequest;
|
|
686
|
+
let requestTotal = 1;
|
|
687
|
+
let responseTotal = 1;
|
|
688
|
+
let previousRequestProgress = null;
|
|
689
|
+
let previousResponseProgress = null;
|
|
690
|
+
const isSameProgress = (previous, next) => !!previous && previous.total === next.total && previous.loaded === next.loaded;
|
|
691
|
+
logger.debug({
|
|
692
|
+
title: `Running middleware callbacks`,
|
|
693
|
+
type: "request",
|
|
694
|
+
extra: {
|
|
695
|
+
request,
|
|
696
|
+
requestId
|
|
697
|
+
}
|
|
698
|
+
});
|
|
699
|
+
request = await request.client.unstable_modifyRequest(request);
|
|
700
|
+
if (request.auth) request = await request.client.unstable_modifyAuth(request);
|
|
701
|
+
if (request.unstable_requestMapper) request = await request.unstable_requestMapper(request, requestId);
|
|
702
|
+
const { client, abortKey } = request;
|
|
703
|
+
const scopedAbortKey = scopeKey(abortKey, request.scope);
|
|
704
|
+
let payload = request.payload;
|
|
705
|
+
if (request.unstable_payloadMapper) payload = await request.unstable_payloadMapper(request.payload);
|
|
706
|
+
else if (unstable_payloadMapper) payload = await unstable_payloadMapper(payload);
|
|
707
|
+
const adapterDefaults = client.adapter.unstable_getAdapterDefaults?.(request);
|
|
708
|
+
const adapterOptions = adapterDefaults ? {
|
|
709
|
+
...adapterDefaults,
|
|
710
|
+
...request.options
|
|
711
|
+
} : request.options;
|
|
712
|
+
const startTime = Date.now();
|
|
713
|
+
onStartTime(startTime);
|
|
714
|
+
const getRequestStartTimestamp = () => {
|
|
715
|
+
return requestStartTimestamp;
|
|
716
|
+
};
|
|
717
|
+
const getResponseStartTimestamp = () => {
|
|
718
|
+
return responseStartTimestamp;
|
|
719
|
+
};
|
|
720
|
+
const getTotal = (previousTotal, progress) => {
|
|
721
|
+
if (!progress) return previousTotal;
|
|
722
|
+
const total = Number(progress.total || 0);
|
|
723
|
+
const loaded = Number(progress.loaded || 0);
|
|
724
|
+
return Math.max(total, loaded, previousTotal);
|
|
725
|
+
};
|
|
726
|
+
const handleRequestProgress = (startTimestamp, progressTimestamp, progressEvent) => {
|
|
727
|
+
const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);
|
|
728
|
+
if (!isSameProgress(previousRequestProgress, progress)) {
|
|
729
|
+
previousRequestProgress = {
|
|
730
|
+
total: progress.total,
|
|
731
|
+
loaded: progress.loaded
|
|
732
|
+
};
|
|
733
|
+
requestManager.events.emitUploadProgress({
|
|
734
|
+
...progress,
|
|
735
|
+
requestId,
|
|
651
736
|
request
|
|
652
737
|
});
|
|
653
|
-
|
|
654
|
-
|
|
738
|
+
}
|
|
739
|
+
};
|
|
740
|
+
const handleResponseProgress = (startTimestamp, progressTimestamp, progressEvent) => {
|
|
741
|
+
const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);
|
|
742
|
+
if (!isSameProgress(previousResponseProgress, progress)) {
|
|
743
|
+
previousResponseProgress = {
|
|
744
|
+
total: progress.total,
|
|
745
|
+
loaded: progress.loaded
|
|
746
|
+
};
|
|
747
|
+
requestManager.events.emitDownloadProgress({
|
|
748
|
+
...progress,
|
|
749
|
+
requestId,
|
|
655
750
|
request
|
|
656
751
|
});
|
|
657
|
-
} catch (interceptorError) {
|
|
658
|
-
response = {
|
|
659
|
-
...response,
|
|
660
|
-
data: null,
|
|
661
|
-
error: interceptorError,
|
|
662
|
-
success: false
|
|
663
|
-
};
|
|
664
752
|
}
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
753
|
+
};
|
|
754
|
+
const onBeforeRequest = () => {
|
|
755
|
+
logger.debug({
|
|
756
|
+
title: `Request about to be sent`,
|
|
668
757
|
type: "request",
|
|
669
758
|
extra: {
|
|
670
759
|
request,
|
|
671
|
-
requestId
|
|
672
|
-
response
|
|
760
|
+
requestId
|
|
673
761
|
}
|
|
674
762
|
});
|
|
675
|
-
|
|
763
|
+
client.triggerPlugins("onRequestTrigger", { request });
|
|
676
764
|
};
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
};
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
};
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
};
|
|
698
|
-
|
|
699
|
-
description = void 0;
|
|
700
|
-
constructor(description) {
|
|
701
|
-
super("Request processing error");
|
|
702
|
-
this.description = description;
|
|
703
|
-
this.name = "RequestProcessingError";
|
|
704
|
-
}
|
|
705
|
-
};
|
|
706
|
-
var UnexpectedError = class extends Error {
|
|
707
|
-
description = void 0;
|
|
708
|
-
constructor(description) {
|
|
709
|
-
super("Unexpected error");
|
|
710
|
-
this.description = description;
|
|
711
|
-
this.name = "UnexpectedError";
|
|
712
|
-
}
|
|
713
|
-
};
|
|
714
|
-
var getErrorMessage = (errorCase) => {
|
|
715
|
-
if (errorCase === "timeout") return new TimeoutError();
|
|
716
|
-
if (errorCase === "abort") return new AbortError();
|
|
717
|
-
if (errorCase === "deleted") return new DeletedError();
|
|
718
|
-
if (errorCase === "processing") return new RequestProcessingError();
|
|
719
|
-
return new UnexpectedError();
|
|
720
|
-
};
|
|
721
|
-
var stringifyValue = (response) => {
|
|
722
|
-
try {
|
|
723
|
-
return JSON.stringify(response);
|
|
724
|
-
} catch {
|
|
725
|
-
return "";
|
|
726
|
-
}
|
|
727
|
-
};
|
|
728
|
-
/**
|
|
729
|
-
* Payloads which are sent as they are - `fetch`, XHR and other transports know how to handle them
|
|
730
|
-
* (and how to describe them with the `Content-Type` header)
|
|
731
|
-
*/
|
|
732
|
-
var isRawPayload = (payload) => {
|
|
733
|
-
return typeof FormData !== "undefined" && payload instanceof FormData || typeof Blob !== "undefined" && payload instanceof Blob || typeof URLSearchParams !== "undefined" && payload instanceof URLSearchParams || typeof ReadableStream !== "undefined" && payload instanceof ReadableStream || typeof ArrayBuffer !== "undefined" && (payload instanceof ArrayBuffer || ArrayBuffer.isView(payload));
|
|
734
|
-
};
|
|
735
|
-
/** `HeadersInit` can be an object, a list of pairs or the `Headers` instance */
|
|
736
|
-
var getHeadersEntries = (headers) => {
|
|
737
|
-
if (!headers) return [];
|
|
738
|
-
if (typeof Headers !== "undefined" && headers instanceof Headers) {
|
|
739
|
-
const entries = [];
|
|
740
|
-
headers.forEach((value, key) => entries.push([key, value]));
|
|
741
|
-
return entries;
|
|
742
|
-
}
|
|
743
|
-
if (Array.isArray(headers)) return headers;
|
|
744
|
-
return Object.entries(headers);
|
|
745
|
-
};
|
|
746
|
-
var getAdapterHeaders = (request) => {
|
|
747
|
-
const isObject = typeof request.payload === "object" && request.payload !== null;
|
|
748
|
-
const entries = getHeadersEntries(request.headers);
|
|
749
|
-
const hasContentType = entries.some(([name]) => name.toLowerCase() === "content-type");
|
|
750
|
-
const headers = {};
|
|
751
|
-
if (isObject && !isRawPayload(request.payload) && !hasContentType) headers["Content-Type"] = "application/json";
|
|
752
|
-
entries.forEach(([name, value]) => {
|
|
753
|
-
if (value !== void 0 && value !== null) headers[name] = value;
|
|
754
|
-
});
|
|
755
|
-
return headers;
|
|
756
|
-
};
|
|
757
|
-
var getAdapterPayload = (data) => {
|
|
758
|
-
if (isRawPayload(data)) return data;
|
|
759
|
-
return stringifyValue(data);
|
|
760
|
-
};
|
|
761
|
-
//#endregion
|
|
762
|
-
//#region src/adapter/adapter.ts
|
|
763
|
-
var defaultMapper = (value) => value;
|
|
764
|
-
/**
|
|
765
|
-
* Base adapter class responsible for executing HTTP requests. Adapters handle endpoint resolution,
|
|
766
|
-
* header/payload/query-params mapping, and the actual fetch call. Extend or configure this class
|
|
767
|
-
* to integrate custom transport layers (e.g., axios, graphql, firebase).
|
|
768
|
-
*/
|
|
769
|
-
var Adapter = class {
|
|
770
|
-
/** Fetching function */
|
|
771
|
-
unstable_fetcher;
|
|
772
|
-
/**
|
|
773
|
-
* ********************
|
|
774
|
-
* Defaults
|
|
775
|
-
* ********************
|
|
776
|
-
*/
|
|
777
|
-
name;
|
|
778
|
-
defaultMethod;
|
|
779
|
-
defaultExtra;
|
|
780
|
-
systemErrorStatus;
|
|
781
|
-
systemErrorExtra;
|
|
782
|
-
defaultRequestOptions = void 0;
|
|
783
|
-
logger;
|
|
784
|
-
initialized = false;
|
|
785
|
-
client;
|
|
786
|
-
unstable_onInitializeCallback = void 0;
|
|
787
|
-
unstable_queryParamsMapperConfig;
|
|
788
|
-
unstable_headerMapperConfig;
|
|
789
|
-
unstable_payloadMapperConfig;
|
|
790
|
-
unstable_endpointMapperConfig;
|
|
791
|
-
/**
|
|
792
|
-
* Type-only carrier of the additional `createRequest` fields declared by this adapter.
|
|
793
|
-
* It has no runtime value - adapters read those fields from `request.requestOptions`.
|
|
794
|
-
*/
|
|
795
|
-
unstable_requestOptionsType = void 0;
|
|
796
|
-
constructor(options) {
|
|
797
|
-
this.options = options;
|
|
798
|
-
this.name = options.name;
|
|
799
|
-
this.defaultMethod = options.defaultMethod;
|
|
800
|
-
this.defaultExtra = options.defaultExtra;
|
|
801
|
-
this.systemErrorStatus = options.systemErrorStatus;
|
|
802
|
-
this.systemErrorExtra = options.systemErrorExtra;
|
|
803
|
-
this.defaultRequestOptions = options.defaultRequestOptions;
|
|
804
|
-
}
|
|
805
|
-
/** Initialize the adapter with a client reference and set up logging. Called automatically when the client is created. */
|
|
806
|
-
initialize = (client) => {
|
|
807
|
-
this.logger = client.loggerManager.initialize(client, "Adapter");
|
|
808
|
-
this.initialized = true;
|
|
809
|
-
this.client = client;
|
|
810
|
-
this.unstable_onInitializeCallback?.({ client });
|
|
811
|
-
return this;
|
|
812
|
-
};
|
|
813
|
-
/** Register a callback invoked once the adapter is initialized with a client. */
|
|
814
|
-
onInitialize = (callback) => {
|
|
815
|
-
this.unstable_onInitializeCallback = callback;
|
|
816
|
-
return this;
|
|
817
|
-
};
|
|
818
|
-
/**
|
|
819
|
-
* ********************
|
|
820
|
-
* Options Setters
|
|
821
|
-
* ********************
|
|
822
|
-
*/
|
|
823
|
-
unstable_internalErrorMapping = (error) => error;
|
|
824
|
-
/** Method to get default headers and to map them based on the data format exchange, by default it handles FormData / JSON formats. */
|
|
825
|
-
unstable_headerMapper = getAdapterHeaders;
|
|
826
|
-
/** Method to get request data and transform them to the required format. It handles FormData and JSON by default. */
|
|
827
|
-
unstable_payloadMapper = getAdapterPayload;
|
|
828
|
-
/** Method to get the endpoint for the adapter request. */
|
|
829
|
-
unstable_endpointMapper = defaultMapper;
|
|
830
|
-
/** Method to get request data and transform them to the required format. */
|
|
831
|
-
unstable_queryParamsMapper = defaultMapper;
|
|
832
|
-
/**
|
|
833
|
-
* Turns query params given as a callback into data, at the moment they are set on a request. Unset by default, so
|
|
834
|
-
* adapters without it store query params as given. See {@link Adapter.setQueryParamsResolver}.
|
|
835
|
-
*/
|
|
836
|
-
unstable_queryParamsResolver = void 0;
|
|
837
|
-
/** Get default adapter options for the request. */
|
|
838
|
-
unstable_getAdapterDefaults = void 0;
|
|
839
|
-
/** Get default request options for the request. */
|
|
840
|
-
unstable_getRequestDefaults = void 0;
|
|
841
|
-
/**
|
|
842
|
-
* Get formatted endpoint name of the request.
|
|
843
|
-
* Helpful in displaying long endpoints like in case of graphql schemas etc.
|
|
844
|
-
*/
|
|
845
|
-
unstable_devtoolsEndpointGetter = (endpoint) => endpoint;
|
|
846
|
-
/**
|
|
847
|
-
* ********************
|
|
848
|
-
* Methods
|
|
849
|
-
* ********************
|
|
850
|
-
*/
|
|
851
|
-
/** Set the default HTTP method used when a request does not specify one. */
|
|
852
|
-
setDefaultMethod = (method) => {
|
|
853
|
-
this.defaultMethod = method;
|
|
854
|
-
return this;
|
|
855
|
-
};
|
|
856
|
-
/** Set the default extra metadata attached to every request response (e.g., headers, status). */
|
|
857
|
-
setDefaultExtra = (extra) => {
|
|
858
|
-
this.defaultExtra = extra;
|
|
859
|
-
return this;
|
|
860
|
-
};
|
|
861
|
-
/** Set a function that formats the endpoint string for display in devtools. */
|
|
862
|
-
setDevtoolsEndpointGetter = (callback) => {
|
|
863
|
-
this.unstable_devtoolsEndpointGetter = callback;
|
|
864
|
-
return this;
|
|
865
|
-
};
|
|
866
|
-
/**
|
|
867
|
-
* This method allows to configure global defaults for the request configuration like method, auth, deduplication etc.
|
|
868
|
-
*/
|
|
869
|
-
setRequestDefaults = (callback) => {
|
|
870
|
-
this.unstable_getRequestDefaults = callback;
|
|
871
|
-
return this;
|
|
872
|
-
};
|
|
873
|
-
/**
|
|
874
|
-
* Set the adapter default options added to every sent request
|
|
875
|
-
*/
|
|
876
|
-
setAdapterDefaults = (callback) => {
|
|
877
|
-
this.unstable_getAdapterDefaults = callback;
|
|
878
|
-
return this;
|
|
879
|
-
};
|
|
880
|
-
/** Set a custom mapping for internal adapter errors before they are returned in the response. */
|
|
881
|
-
setInternalErrorMapping = (callback) => {
|
|
882
|
-
this.unstable_internalErrorMapping = callback;
|
|
883
|
-
return this;
|
|
884
|
-
};
|
|
885
|
-
/**
|
|
886
|
-
* Set the custom header mapping function
|
|
887
|
-
*/
|
|
888
|
-
setHeaderMapper = (headerMapper) => {
|
|
889
|
-
this.unstable_headerMapper = ((req) => headerMapper(req, this.unstable_headerMapperConfig));
|
|
890
|
-
return this;
|
|
891
|
-
};
|
|
892
|
-
/**
|
|
893
|
-
* Set the payload mapping function which runs before every request is sent.
|
|
894
|
-
* It is called with the raw payload and the value set with `setPayloadMapperConfig`,
|
|
895
|
-
* and its return value is the body passed to the adapter.
|
|
896
|
-
* Requests with their own `request.setPayloadMapper` skip it.
|
|
897
|
-
* @example
|
|
898
|
-
* ```ts
|
|
899
|
-
* client.adapter.setPayloadMapper((payload, config) => encrypt(JSON.stringify(payload), config));
|
|
900
|
-
* ```
|
|
901
|
-
*/
|
|
902
|
-
setPayloadMapper = (payloadMapper) => {
|
|
903
|
-
this.unstable_payloadMapper = ((payload) => payloadMapper(payload, this.unstable_payloadMapperConfig));
|
|
904
|
-
return this;
|
|
905
|
-
};
|
|
906
|
-
/**
|
|
907
|
-
* Set the endpoint mapping function which transforms the endpoint string before the request is sent
|
|
908
|
-
*/
|
|
909
|
-
setEndpointMapper = (endpointMapper) => {
|
|
910
|
-
this.unstable_endpointMapper = ((endpoint) => endpointMapper(endpoint, this.unstable_endpointMapperConfig));
|
|
911
|
-
return this;
|
|
912
|
-
};
|
|
913
|
-
/**
|
|
914
|
-
* Set the query params mapping function which get triggered before request get sent
|
|
915
|
-
*/
|
|
916
|
-
setQueryParamsMapper = (queryParamsMapper) => {
|
|
917
|
-
this.unstable_queryParamsMapper = ((queryParams) => queryParamsMapper(queryParams, this.unstable_queryParamsMapperConfig));
|
|
918
|
-
return this;
|
|
919
|
-
};
|
|
920
|
-
/**
|
|
921
|
-
* Let requests take query params as a callback. When a request gets a function as its query params (in
|
|
922
|
-
* `createRequest`, `setQueryParams` or `send`), the resolver runs right away and the request stores what it returns,
|
|
923
|
-
* so cache keys, query keys and `toJSON()` only ever see data. The resolver decides what the callback receives.
|
|
924
|
-
*
|
|
925
|
-
* Opt-in: adapters without a resolver store query params as given. Declare the callback in the adapter's query params
|
|
926
|
-
* type so requests accept it.
|
|
927
|
-
*
|
|
928
|
-
* @example
|
|
929
|
-
* // The Firebase adapter passes a constraints builder and stores the constraints it collected
|
|
930
|
-
* adapter.setQueryParamsResolver((callback) => callback(createConstraints()).toJSON());
|
|
931
|
-
*/
|
|
932
|
-
setQueryParamsResolver = (resolver) => {
|
|
933
|
-
this.unstable_queryParamsResolver = resolver;
|
|
934
|
-
return this;
|
|
765
|
+
const onRequestStart = (progress) => {
|
|
766
|
+
logger.info({
|
|
767
|
+
title: `Request start`,
|
|
768
|
+
type: "request",
|
|
769
|
+
extra: {
|
|
770
|
+
request,
|
|
771
|
+
requestId
|
|
772
|
+
}
|
|
773
|
+
});
|
|
774
|
+
client.triggerPlugins("onRequestStart", { request });
|
|
775
|
+
if (progress?.total) requestTotal = getTotal(requestTotal, progress);
|
|
776
|
+
const initialPayload = {
|
|
777
|
+
total: requestTotal,
|
|
778
|
+
loaded: progress?.loaded || 0
|
|
779
|
+
};
|
|
780
|
+
requestStartTimestamp = Date.now();
|
|
781
|
+
handleRequestProgress(requestStartTimestamp, requestStartTimestamp, initialPayload);
|
|
782
|
+
requestManager.events.emitRequestStart({
|
|
783
|
+
requestId,
|
|
784
|
+
request
|
|
785
|
+
});
|
|
786
|
+
return requestStartTimestamp;
|
|
935
787
|
};
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
788
|
+
const onRequestProgress = (progress) => {
|
|
789
|
+
if (!requestStartTimestamp) requestStartTimestamp = Date.now();
|
|
790
|
+
requestTotal = getTotal(requestTotal, progress);
|
|
791
|
+
const progressTimestamp = Date.now();
|
|
792
|
+
handleRequestProgress(requestStartTimestamp, progressTimestamp, {
|
|
793
|
+
total: requestTotal,
|
|
794
|
+
loaded: progress.loaded || 0
|
|
795
|
+
});
|
|
796
|
+
return progressTimestamp;
|
|
940
797
|
};
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
798
|
+
const onRequestEnd = () => {
|
|
799
|
+
if (!requestStartTimestamp) requestStartTimestamp = Date.now();
|
|
800
|
+
const progressTimestamp = Date.now();
|
|
801
|
+
handleRequestProgress(requestStartTimestamp, progressTimestamp, {
|
|
802
|
+
total: requestTotal,
|
|
803
|
+
loaded: requestTotal
|
|
804
|
+
});
|
|
805
|
+
return progressTimestamp;
|
|
945
806
|
};
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
807
|
+
const onResponseStart = (progress) => {
|
|
808
|
+
responseStartTimestamp = Date.now();
|
|
809
|
+
responseTotal = getTotal(responseTotal, progress);
|
|
810
|
+
const initialPayload = {
|
|
811
|
+
total: responseTotal,
|
|
812
|
+
loaded: progress?.loaded || 0
|
|
813
|
+
};
|
|
814
|
+
handleResponseProgress(responseStartTimestamp, responseStartTimestamp, initialPayload);
|
|
815
|
+
requestManager.events.emitResponseStart({
|
|
816
|
+
requestId,
|
|
817
|
+
request
|
|
818
|
+
});
|
|
819
|
+
return responseStartTimestamp;
|
|
950
820
|
};
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
821
|
+
const onResponseProgress = (progress) => {
|
|
822
|
+
if (!responseStartTimestamp) responseStartTimestamp = Date.now();
|
|
823
|
+
const progressTimestamp = Date.now();
|
|
824
|
+
responseTotal = getTotal(responseTotal, progress);
|
|
825
|
+
handleResponseProgress(responseStartTimestamp, progressTimestamp, {
|
|
826
|
+
total: responseTotal,
|
|
827
|
+
loaded: progress.loaded || 0
|
|
828
|
+
});
|
|
829
|
+
return progressTimestamp;
|
|
955
830
|
};
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
setFetcher(fetcher) {
|
|
963
|
-
this.unstable_fetcher = fetcher.bind(this);
|
|
964
|
-
return this;
|
|
965
|
-
}
|
|
966
|
-
/** Execute a request through the adapter pipeline: maps endpoint/headers/payload, runs plugins, then calls the fetcher. */
|
|
967
|
-
async fetch(request, requestId) {
|
|
968
|
-
let startTime;
|
|
969
|
-
const execute = async (resolve) => {
|
|
970
|
-
try {
|
|
971
|
-
if (!this.initialized) throw new RequestProcessingError(`Adapter ${this.options.name} is not initialized`);
|
|
972
|
-
if (!this.unstable_fetcher) throw new RequestProcessingError(`Fetcher for ${this.options.name} adapter is not set`);
|
|
973
|
-
this.client.triggerPlugins("onAdapterFetch", {
|
|
974
|
-
adapter: this,
|
|
975
|
-
request,
|
|
976
|
-
requestId
|
|
977
|
-
});
|
|
978
|
-
const bindings = await getAdapterBindings({
|
|
979
|
-
request,
|
|
980
|
-
requestId,
|
|
981
|
-
resolve,
|
|
982
|
-
internalErrorMapping: this.unstable_internalErrorMapping,
|
|
983
|
-
onStartTime: (time) => {
|
|
984
|
-
startTime = time;
|
|
985
|
-
}
|
|
986
|
-
});
|
|
987
|
-
if (request.unstable_mock && request.isMockerEnabled && request.client.isMockerEnabled) return await mocker(bindings);
|
|
988
|
-
return await this.unstable_fetcher(bindings);
|
|
989
|
-
} catch (error) {
|
|
990
|
-
return getAdapterOnError({
|
|
991
|
-
request,
|
|
992
|
-
requestId,
|
|
993
|
-
startTime: startTime || Date.now(),
|
|
994
|
-
logger: this.logger,
|
|
995
|
-
resolve
|
|
996
|
-
})({
|
|
997
|
-
error: this.unstable_internalErrorMapping(error),
|
|
998
|
-
status: this.options.systemErrorStatus,
|
|
999
|
-
extra: this.options.systemErrorExtra
|
|
1000
|
-
});
|
|
1001
|
-
}
|
|
1002
|
-
};
|
|
1003
|
-
return new Promise((resolve) => {
|
|
1004
|
-
execute(resolve);
|
|
831
|
+
const onResponseEnd = () => {
|
|
832
|
+
if (!responseStartTimestamp) responseStartTimestamp = Date.now();
|
|
833
|
+
const progressTimestamp = Date.now();
|
|
834
|
+
handleResponseProgress(responseStartTimestamp, progressTimestamp, {
|
|
835
|
+
total: responseTotal,
|
|
836
|
+
loaded: responseTotal
|
|
1005
837
|
});
|
|
1006
|
-
|
|
1007
|
-
};
|
|
1008
|
-
//#endregion
|
|
1009
|
-
//#region src/constants/http.constants.ts
|
|
1010
|
-
var HttpMethods = /* @__PURE__ */ function(HttpMethods) {
|
|
1011
|
-
HttpMethods["GET"] = "GET";
|
|
1012
|
-
HttpMethods["POST"] = "POST";
|
|
1013
|
-
HttpMethods["PUT"] = "PUT";
|
|
1014
|
-
HttpMethods["PATCH"] = "PATCH";
|
|
1015
|
-
HttpMethods["DELETE"] = "DELETE";
|
|
1016
|
-
/** Safe, idempotent read with a request body (IETF draft-ietf-httpbis-safe-method-w-body). */
|
|
1017
|
-
HttpMethods["QUERY"] = "QUERY";
|
|
1018
|
-
return HttpMethods;
|
|
1019
|
-
}({});
|
|
1020
|
-
/** Methods that are safe reads: routed to the fetch dispatcher and deduplicated by default. */
|
|
1021
|
-
var SAFE_HTTP_METHODS = [HttpMethods.GET, HttpMethods.QUERY];
|
|
1022
|
-
//#endregion
|
|
1023
|
-
//#region src/optimistic/optimistic.utils.ts
|
|
1024
|
-
var isComparableId = (value) => typeof value === "string" || typeof value === "number";
|
|
1025
|
-
/**
|
|
1026
|
-
* Tells if the item is selected by the match. Plain values are compared with the `key` field of the item, numbers and
|
|
1027
|
-
* strings match each other the same way route params do (`"1"` matches `1`).
|
|
1028
|
-
*/
|
|
1029
|
-
var isOptimisticMatch = (item, match, key = "id") => {
|
|
1030
|
-
if (typeof match === "function") return !!match(item);
|
|
1031
|
-
if (item === null || typeof item !== "object") return false;
|
|
1032
|
-
const value = item[key];
|
|
1033
|
-
if (Object.is(value, match)) return true;
|
|
1034
|
-
return isComparableId(value) && isComparableId(match) && String(value) === String(match);
|
|
1035
|
-
};
|
|
1036
|
-
var assertList = (list) => {
|
|
1037
|
-
if (!Array.isArray(list)) throw new TypeError("Optimistic list helpers need an array, use .list(field) for an array inside an object");
|
|
1038
|
-
return list;
|
|
1039
|
-
};
|
|
1040
|
-
var assertEntry = (data) => {
|
|
1041
|
-
if (data === null || typeof data !== "object" || Array.isArray(data)) throw new TypeError("Optimistic increment(field, by) needs an object, use increment(match, field, by) on a list");
|
|
1042
|
-
return data;
|
|
1043
|
-
};
|
|
1044
|
-
var addToField = (item, field, by) => {
|
|
1045
|
-
const value = item[field];
|
|
1046
|
-
return {
|
|
1047
|
-
...item,
|
|
1048
|
-
[field]: (typeof value === "number" ? value : 0) + by
|
|
838
|
+
return progressTimestamp;
|
|
1049
839
|
};
|
|
1050
|
-
}
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
*/
|
|
1094
|
-
var updateListField = (data, field, update) => {
|
|
1095
|
-
const entry = assertEntry(data);
|
|
1096
|
-
const list = entry[field] ?? [];
|
|
1097
|
-
const next = update(assertList(list));
|
|
1098
|
-
return next === list ? entry : {
|
|
1099
|
-
...entry,
|
|
1100
|
-
[field]: next
|
|
840
|
+
const onSuccess = async ({ data, error, status, extra }) => {
|
|
841
|
+
let response = {
|
|
842
|
+
data,
|
|
843
|
+
error: error ?? null,
|
|
844
|
+
success: true,
|
|
845
|
+
status,
|
|
846
|
+
extra,
|
|
847
|
+
requestTimestamp: startTime,
|
|
848
|
+
responseTimestamp: Date.now()
|
|
849
|
+
};
|
|
850
|
+
try {
|
|
851
|
+
response = await request.client.unstable_modifyResponse?.(response, request);
|
|
852
|
+
response = await request.client.unstable_modifySuccessResponse?.(response, request);
|
|
853
|
+
client.triggerPlugins("onRequestSuccess", {
|
|
854
|
+
response,
|
|
855
|
+
request
|
|
856
|
+
});
|
|
857
|
+
client.triggerPlugins("onRequestFinished", {
|
|
858
|
+
response,
|
|
859
|
+
request
|
|
860
|
+
});
|
|
861
|
+
} catch (interceptorError) {
|
|
862
|
+
response = {
|
|
863
|
+
data: null,
|
|
864
|
+
error: internalErrorMapping(interceptorError),
|
|
865
|
+
success: false,
|
|
866
|
+
status,
|
|
867
|
+
extra,
|
|
868
|
+
requestTimestamp: startTime,
|
|
869
|
+
responseTimestamp: Date.now()
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
resolve(response);
|
|
873
|
+
logger.info({
|
|
874
|
+
title: `Response success`,
|
|
875
|
+
type: "response",
|
|
876
|
+
extra: {
|
|
877
|
+
request,
|
|
878
|
+
requestId,
|
|
879
|
+
response
|
|
880
|
+
}
|
|
881
|
+
});
|
|
882
|
+
return response;
|
|
1101
883
|
};
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
/** @internal */
|
|
1118
|
-
onRollback = void 0;
|
|
1119
|
-
/** @internal */
|
|
1120
|
-
onCommit = void 0;
|
|
1121
|
-
constructor(options) {
|
|
1122
|
-
this.target = options.target;
|
|
1123
|
-
this.allVariants = options.allVariants;
|
|
1124
|
-
this.update = options.update;
|
|
1125
|
-
this.onRollback = options.onRollback;
|
|
1126
|
-
this.onCommit = options.onCommit;
|
|
1127
|
-
}
|
|
1128
|
-
/**
|
|
1129
|
-
* Undo of this change, written by hand and run by core when the mutation fails for good, is aborted or removed from
|
|
1130
|
-
* the queue. Rollbacks of one mutation run in reverse order of the changes. It receives
|
|
1131
|
-
* `{ data, previous, reason, response, request }` and returns the new data; returning nothing leaves the data as it
|
|
1132
|
-
* is. Build the result from `data` and use `previous` only to look old values up. Must be synchronous.
|
|
1133
|
-
* Without it nothing is undone locally and the target is refetched.
|
|
1134
|
-
*/
|
|
1135
|
-
rollback(callback) {
|
|
1136
|
-
return new OptimisticOperation({
|
|
1137
|
-
target: this.target,
|
|
1138
|
-
allVariants: this.allVariants,
|
|
1139
|
-
update: this.update,
|
|
1140
|
-
onRollback: callback,
|
|
1141
|
-
onCommit: this.onCommit
|
|
884
|
+
const onError = getAdapterOnError({
|
|
885
|
+
request,
|
|
886
|
+
requestId,
|
|
887
|
+
startTime,
|
|
888
|
+
logger,
|
|
889
|
+
resolve
|
|
890
|
+
});
|
|
891
|
+
const onAbortError = ({ status, extra }) => {
|
|
892
|
+
logger.error({
|
|
893
|
+
title: `Abort error`,
|
|
894
|
+
type: "request",
|
|
895
|
+
extra: {
|
|
896
|
+
request,
|
|
897
|
+
requestId
|
|
898
|
+
}
|
|
1142
899
|
});
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
* the data as it is. Must be synchronous.
|
|
1148
|
-
*/
|
|
1149
|
-
commit(callback) {
|
|
1150
|
-
return new OptimisticOperation({
|
|
1151
|
-
target: this.target,
|
|
1152
|
-
allVariants: this.allVariants,
|
|
1153
|
-
update: this.update,
|
|
1154
|
-
onRollback: this.onRollback,
|
|
1155
|
-
onCommit: callback
|
|
900
|
+
return onError({
|
|
901
|
+
error: internalErrorMapping(getErrorMessage("abort")),
|
|
902
|
+
status,
|
|
903
|
+
extra
|
|
1156
904
|
});
|
|
1157
|
-
}
|
|
1158
|
-
}
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
905
|
+
};
|
|
906
|
+
const onTimeoutError = ({ status, extra }) => {
|
|
907
|
+
logger.error({
|
|
908
|
+
title: `Timeout error`,
|
|
909
|
+
type: "request",
|
|
910
|
+
extra: {
|
|
911
|
+
request,
|
|
912
|
+
requestId
|
|
913
|
+
}
|
|
914
|
+
});
|
|
915
|
+
return onError({
|
|
916
|
+
error: internalErrorMapping(getErrorMessage("timeout")),
|
|
917
|
+
status,
|
|
918
|
+
extra
|
|
1165
919
|
});
|
|
1166
920
|
};
|
|
1167
|
-
const
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
921
|
+
const onUnexpectedError = ({ status, extra }) => {
|
|
922
|
+
logger.error({
|
|
923
|
+
title: `Unexpected error`,
|
|
924
|
+
type: "request",
|
|
925
|
+
extra: {
|
|
926
|
+
request,
|
|
927
|
+
requestId
|
|
928
|
+
}
|
|
929
|
+
});
|
|
930
|
+
return onError({
|
|
931
|
+
error: internalErrorMapping(getErrorMessage()),
|
|
932
|
+
status,
|
|
933
|
+
extra
|
|
934
|
+
});
|
|
935
|
+
};
|
|
936
|
+
const getAbortController = () => {
|
|
937
|
+
return requestManager.getAbortController(scopedAbortKey, requestId);
|
|
938
|
+
};
|
|
939
|
+
const createAbortListener = ({ status, extra, onAbort = () => {} }) => {
|
|
940
|
+
const controller = getAbortController();
|
|
941
|
+
if (!controller) throw new RequestProcessingError("Controller is not found");
|
|
942
|
+
const abort = () => {
|
|
943
|
+
onAbortError({
|
|
944
|
+
status,
|
|
945
|
+
extra
|
|
946
|
+
});
|
|
947
|
+
onAbort();
|
|
948
|
+
requestManager.events.emitAbort({
|
|
949
|
+
requestId,
|
|
950
|
+
request
|
|
951
|
+
});
|
|
952
|
+
};
|
|
953
|
+
if (controller.signal.aborted) abort();
|
|
954
|
+
controller.signal.addEventListener("abort", abort);
|
|
955
|
+
return () => controller.signal.removeEventListener("abort", abort);
|
|
956
|
+
};
|
|
957
|
+
logger.debug({
|
|
958
|
+
title: `Mounted adapter bindings`,
|
|
959
|
+
type: "request",
|
|
960
|
+
extra: {
|
|
961
|
+
request,
|
|
962
|
+
requestId,
|
|
963
|
+
payload,
|
|
964
|
+
adapterOptions
|
|
1191
965
|
}
|
|
1192
966
|
});
|
|
1193
|
-
const
|
|
967
|
+
const queryParams = baseRequest.client.adapter.unstable_queryParamsMapper(request.queryParams);
|
|
968
|
+
const endpoint = baseRequest.client.adapter.unstable_endpointMapper(request.endpoint);
|
|
969
|
+
const headers = baseRequest.client.adapter.unstable_headerMapper(request);
|
|
970
|
+
const { url } = baseRequest.client;
|
|
1194
971
|
return {
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
972
|
+
request,
|
|
973
|
+
requestId,
|
|
974
|
+
url,
|
|
975
|
+
endpoint,
|
|
976
|
+
queryParams,
|
|
977
|
+
payload,
|
|
978
|
+
headers,
|
|
979
|
+
adapter: baseRequest.client.adapter,
|
|
980
|
+
adapterOptions,
|
|
981
|
+
getAbortController,
|
|
982
|
+
getRequestStartTimestamp,
|
|
983
|
+
getResponseStartTimestamp,
|
|
984
|
+
createAbortListener,
|
|
985
|
+
onBeforeRequest,
|
|
986
|
+
onRequestStart,
|
|
987
|
+
onRequestProgress,
|
|
988
|
+
onRequestEnd,
|
|
989
|
+
onResponseStart,
|
|
990
|
+
onResponseProgress,
|
|
991
|
+
onResponseEnd,
|
|
992
|
+
onSuccess,
|
|
993
|
+
onAbortError,
|
|
994
|
+
onTimeoutError,
|
|
995
|
+
onUnexpectedError,
|
|
996
|
+
onError
|
|
997
|
+
};
|
|
998
|
+
};
|
|
999
|
+
function getAdapterOnError({ request, requestId, startTime, resolve, logger }) {
|
|
1000
|
+
const { client } = request;
|
|
1001
|
+
return async ({ error, status, extra }) => {
|
|
1002
|
+
let response = {
|
|
1003
|
+
data: null,
|
|
1004
|
+
status,
|
|
1005
|
+
error,
|
|
1006
|
+
success: false,
|
|
1007
|
+
extra,
|
|
1008
|
+
requestTimestamp: startTime,
|
|
1009
|
+
responseTimestamp: Date.now()
|
|
1010
|
+
};
|
|
1011
|
+
try {
|
|
1012
|
+
response = await client.unstable_modifyResponse(response, request);
|
|
1013
|
+
response = await client.unstable_modifyErrorResponse(response, request);
|
|
1014
|
+
client.triggerPlugins("onRequestError", {
|
|
1015
|
+
response,
|
|
1016
|
+
request
|
|
1017
|
+
});
|
|
1018
|
+
client.triggerPlugins("onRequestFinished", {
|
|
1019
|
+
response,
|
|
1020
|
+
request
|
|
1021
|
+
});
|
|
1022
|
+
} catch (interceptorError) {
|
|
1023
|
+
response = {
|
|
1024
|
+
...response,
|
|
1025
|
+
data: null,
|
|
1026
|
+
error: interceptorError,
|
|
1027
|
+
success: false
|
|
1028
|
+
};
|
|
1207
1029
|
}
|
|
1030
|
+
resolve(response);
|
|
1031
|
+
logger.error({
|
|
1032
|
+
title: `Request error`,
|
|
1033
|
+
type: "request",
|
|
1034
|
+
extra: {
|
|
1035
|
+
request,
|
|
1036
|
+
requestId,
|
|
1037
|
+
response
|
|
1038
|
+
}
|
|
1039
|
+
});
|
|
1040
|
+
return response;
|
|
1208
1041
|
};
|
|
1209
|
-
}
|
|
1210
|
-
var optimisticFactory = (target) => createTarget(target, false);
|
|
1211
|
-
optimisticFactory.all = (target) => createTarget(target, true);
|
|
1212
|
-
/**
|
|
1213
|
-
* Describes an optimistic change of a cached request. Return the operations from `setOptimistic` or pass them with the
|
|
1214
|
-
* `optimistic` send option, core applies them, runs `.commit()` / `.rollback()` when the mutation settles and refreshes
|
|
1215
|
-
* the targets once the last pending mutation on them is done.
|
|
1216
|
-
*
|
|
1217
|
-
* - `optimistic(getTodos)` - the entry of this request (its params and query params)
|
|
1218
|
-
* - `optimistic.all(getTodos)` - every cached variant of it, whatever the query params (filters, infinite pages)
|
|
1219
|
-
*
|
|
1220
|
-
* Helpers: `set(updater)`, `patch(match, fields)`, `insert(item, { at })`, `remove(match)`,
|
|
1221
|
-
* `increment(field, by)` / `increment(match, field, by)` and `.list("field")` for an array inside an object.
|
|
1222
|
-
*
|
|
1223
|
-
* @example
|
|
1224
|
-
* optimistic(getTodos)
|
|
1225
|
-
* .patch(params.todoId, payload)
|
|
1226
|
-
* .rollback(({ data, previous }) => {
|
|
1227
|
-
* const before = previous.find((todo) => todo.id === params.todoId);
|
|
1228
|
-
* return data.map((todo) => (todo.id === params.todoId && before ? before : todo));
|
|
1229
|
-
* });
|
|
1230
|
-
*/
|
|
1231
|
-
var optimistic = optimisticFactory;
|
|
1042
|
+
}
|
|
1232
1043
|
//#endregion
|
|
1233
|
-
//#region src/
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
}
|
|
1044
|
+
//#region src/adapter/adapter.utils.ts
|
|
1045
|
+
var TimeoutError = class extends Error {
|
|
1046
|
+
constructor() {
|
|
1047
|
+
super("Request timeout");
|
|
1048
|
+
this.name = "TimeoutError";
|
|
1049
|
+
}
|
|
1050
|
+
};
|
|
1051
|
+
var AbortError = class extends Error {
|
|
1052
|
+
constructor() {
|
|
1053
|
+
super("Request aborted");
|
|
1054
|
+
this.name = "AbortError";
|
|
1055
|
+
}
|
|
1056
|
+
};
|
|
1057
|
+
var DeletedError = class extends Error {
|
|
1058
|
+
constructor() {
|
|
1059
|
+
super("Request deleted");
|
|
1060
|
+
this.name = "DeletedError";
|
|
1061
|
+
}
|
|
1062
|
+
};
|
|
1063
|
+
var RequestProcessingError = class extends Error {
|
|
1064
|
+
description = void 0;
|
|
1065
|
+
constructor(description) {
|
|
1066
|
+
super("Request processing error");
|
|
1067
|
+
this.description = description;
|
|
1068
|
+
this.name = "RequestProcessingError";
|
|
1069
|
+
}
|
|
1070
|
+
};
|
|
1071
|
+
var UnexpectedError = class extends Error {
|
|
1072
|
+
description = void 0;
|
|
1073
|
+
constructor(description) {
|
|
1074
|
+
super("Unexpected error");
|
|
1075
|
+
this.description = description;
|
|
1076
|
+
this.name = "UnexpectedError";
|
|
1077
|
+
}
|
|
1078
|
+
};
|
|
1079
|
+
var getErrorMessage = (errorCase) => {
|
|
1080
|
+
if (errorCase === "timeout") return new TimeoutError();
|
|
1081
|
+
if (errorCase === "abort") return new AbortError();
|
|
1082
|
+
if (errorCase === "deleted") return new DeletedError();
|
|
1083
|
+
if (errorCase === "processing") return new RequestProcessingError();
|
|
1084
|
+
return new UnexpectedError();
|
|
1085
|
+
};
|
|
1086
|
+
var stringifyValue = (response) => {
|
|
1087
|
+
try {
|
|
1088
|
+
return JSON.stringify(response);
|
|
1089
|
+
} catch {
|
|
1090
|
+
return "";
|
|
1091
|
+
}
|
|
1245
1092
|
};
|
|
1246
1093
|
/**
|
|
1247
|
-
*
|
|
1248
|
-
* and
|
|
1249
|
-
* @internal
|
|
1250
|
-
* @param callback code of the user to run
|
|
1251
|
-
* @returns `true` when the callback finished, `false` when it threw
|
|
1094
|
+
* Payloads which are sent as they are - `fetch`, XHR and other transports know how to handle them
|
|
1095
|
+
* (and how to describe them with the `Content-Type` header)
|
|
1252
1096
|
*/
|
|
1253
|
-
var
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1097
|
+
var isRawPayload = (payload) => {
|
|
1098
|
+
return typeof FormData !== "undefined" && payload instanceof FormData || typeof Blob !== "undefined" && payload instanceof Blob || typeof URLSearchParams !== "undefined" && payload instanceof URLSearchParams || typeof ReadableStream !== "undefined" && payload instanceof ReadableStream || typeof ArrayBuffer !== "undefined" && (payload instanceof ArrayBuffer || ArrayBuffer.isView(payload));
|
|
1099
|
+
};
|
|
1100
|
+
/** `HeadersInit` can be an object, a list of pairs or the `Headers` instance */
|
|
1101
|
+
var getHeadersEntries = (headers) => {
|
|
1102
|
+
if (!headers) return [];
|
|
1103
|
+
if (typeof Headers !== "undefined" && headers instanceof Headers) {
|
|
1104
|
+
const entries = [];
|
|
1105
|
+
headers.forEach((value, key) => entries.push([key, value]));
|
|
1106
|
+
return entries;
|
|
1260
1107
|
}
|
|
1108
|
+
if (Array.isArray(headers)) return headers;
|
|
1109
|
+
return Object.entries(headers);
|
|
1261
1110
|
};
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1111
|
+
var getAdapterHeaders = (request) => {
|
|
1112
|
+
const isObject = typeof request.payload === "object" && request.payload !== null;
|
|
1113
|
+
const entries = getHeadersEntries(request.headers);
|
|
1114
|
+
const hasContentType = entries.some(([name]) => name.toLowerCase() === "content-type");
|
|
1115
|
+
const headers = {};
|
|
1116
|
+
if (isObject && !isRawPayload(request.payload) && !hasContentType) headers["Content-Type"] = "application/json";
|
|
1117
|
+
entries.forEach(([name, value]) => {
|
|
1118
|
+
if (value !== void 0 && value !== null) headers[name] = value;
|
|
1119
|
+
});
|
|
1120
|
+
return headers;
|
|
1121
|
+
};
|
|
1122
|
+
var getAdapterPayload = (data) => {
|
|
1123
|
+
if (isRawPayload(data)) return data;
|
|
1124
|
+
return stringifyValue(data);
|
|
1266
1125
|
};
|
|
1267
1126
|
//#endregion
|
|
1268
|
-
//#region src/
|
|
1269
|
-
var
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1127
|
+
//#region src/adapter/adapter.ts
|
|
1128
|
+
var defaultMapper = (value) => value;
|
|
1129
|
+
/**
|
|
1130
|
+
* Base adapter class responsible for executing HTTP requests. Adapters handle endpoint resolution,
|
|
1131
|
+
* header/payload/query-params mapping, and the actual fetch call. Extend or configure this class
|
|
1132
|
+
* to integrate custom transport layers (e.g., axios, graphql, firebase).
|
|
1133
|
+
*/
|
|
1134
|
+
var Adapter = class {
|
|
1135
|
+
/** Fetching function */
|
|
1136
|
+
unstable_fetcher;
|
|
1137
|
+
/**
|
|
1138
|
+
* ********************
|
|
1139
|
+
* Defaults
|
|
1140
|
+
* ********************
|
|
1141
|
+
*/
|
|
1142
|
+
name;
|
|
1143
|
+
defaultMethod;
|
|
1144
|
+
defaultExtra;
|
|
1145
|
+
systemErrorStatus;
|
|
1146
|
+
systemErrorExtra;
|
|
1147
|
+
defaultRequestOptions = void 0;
|
|
1148
|
+
logger;
|
|
1149
|
+
initialized = false;
|
|
1150
|
+
client;
|
|
1151
|
+
unstable_onInitializeCallback = void 0;
|
|
1152
|
+
unstable_queryParamsMapperConfig;
|
|
1153
|
+
unstable_headerMapperConfig;
|
|
1154
|
+
unstable_payloadMapperConfig;
|
|
1155
|
+
unstable_endpointMapperConfig;
|
|
1156
|
+
/**
|
|
1157
|
+
* Type-only carrier of the additional `createRequest` fields declared by this adapter.
|
|
1158
|
+
* It has no runtime value - adapters read those fields from `request.requestOptions`.
|
|
1159
|
+
*/
|
|
1160
|
+
unstable_requestOptionsType = void 0;
|
|
1161
|
+
constructor(options) {
|
|
1162
|
+
this.options = options;
|
|
1163
|
+
this.name = options.name;
|
|
1164
|
+
this.defaultMethod = options.defaultMethod;
|
|
1165
|
+
this.defaultExtra = options.defaultExtra;
|
|
1166
|
+
this.systemErrorStatus = options.systemErrorStatus;
|
|
1167
|
+
this.systemErrorExtra = options.systemErrorExtra;
|
|
1168
|
+
this.defaultRequestOptions = options.defaultRequestOptions;
|
|
1284
1169
|
}
|
|
1285
|
-
|
|
1286
|
-
|
|
1170
|
+
/** Initialize the adapter with a client reference and set up logging. Called automatically when the client is created. */
|
|
1171
|
+
initialize = (client) => {
|
|
1172
|
+
this.logger = client.loggerManager.initialize(client, "Adapter");
|
|
1173
|
+
this.initialized = true;
|
|
1174
|
+
this.client = client;
|
|
1175
|
+
this.unstable_onInitializeCallback?.({ client });
|
|
1176
|
+
return this;
|
|
1287
1177
|
};
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1178
|
+
/** Register a callback invoked once the adapter is initialized with a client. */
|
|
1179
|
+
onInitialize = (callback) => {
|
|
1180
|
+
this.unstable_onInitializeCallback = callback;
|
|
1181
|
+
return this;
|
|
1182
|
+
};
|
|
1183
|
+
/**
|
|
1184
|
+
* ********************
|
|
1185
|
+
* Options Setters
|
|
1186
|
+
* ********************
|
|
1187
|
+
*/
|
|
1188
|
+
unstable_internalErrorMapping = (error) => error;
|
|
1189
|
+
/** Method to get default headers and to map them based on the data format exchange, by default it handles FormData / JSON formats. */
|
|
1190
|
+
unstable_headerMapper = getAdapterHeaders;
|
|
1191
|
+
/** Method to get request data and transform them to the required format. It handles FormData and JSON by default. */
|
|
1192
|
+
unstable_payloadMapper = getAdapterPayload;
|
|
1193
|
+
/** Method to get the endpoint for the adapter request. */
|
|
1194
|
+
unstable_endpointMapper = defaultMapper;
|
|
1195
|
+
/** Method to get request data and transform them to the required format. */
|
|
1196
|
+
unstable_queryParamsMapper = defaultMapper;
|
|
1197
|
+
/**
|
|
1198
|
+
* Turns query params given as a callback into data, at the moment they are set on a request. Unset by default, so
|
|
1199
|
+
* adapters without it store query params as given. See {@link Adapter.setQueryParamsResolver}.
|
|
1200
|
+
*/
|
|
1201
|
+
unstable_queryParamsResolver = void 0;
|
|
1202
|
+
/** Get default adapter options for the request. */
|
|
1203
|
+
unstable_getAdapterDefaults = void 0;
|
|
1204
|
+
/** Get default request options for the request. */
|
|
1205
|
+
unstable_getRequestDefaults = void 0;
|
|
1206
|
+
/**
|
|
1207
|
+
* Get formatted endpoint name of the request.
|
|
1208
|
+
* Helpful in displaying long endpoints like in case of graphql schemas etc.
|
|
1209
|
+
*/
|
|
1210
|
+
unstable_devtoolsEndpointGetter = (endpoint) => endpoint;
|
|
1211
|
+
/**
|
|
1212
|
+
* ********************
|
|
1213
|
+
* Methods
|
|
1214
|
+
* ********************
|
|
1215
|
+
*/
|
|
1216
|
+
/** Set the default HTTP method used when a request does not specify one. */
|
|
1217
|
+
setDefaultMethod = (method) => {
|
|
1218
|
+
this.defaultMethod = method;
|
|
1219
|
+
return this;
|
|
1317
1220
|
};
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
this.
|
|
1221
|
+
/** Set the default extra metadata attached to every request response (e.g., headers, status). */
|
|
1222
|
+
setDefaultExtra = (extra) => {
|
|
1223
|
+
this.defaultExtra = extra;
|
|
1321
1224
|
return this;
|
|
1322
1225
|
};
|
|
1323
|
-
function
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
|
|
1328
|
-
return _getMaxListeners(this);
|
|
1226
|
+
/** Set a function that formats the endpoint string for display in devtools. */
|
|
1227
|
+
setDevtoolsEndpointGetter = (callback) => {
|
|
1228
|
+
this.unstable_devtoolsEndpointGetter = callback;
|
|
1229
|
+
return this;
|
|
1329
1230
|
};
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
else if (!doError) return false;
|
|
1337
|
-
if (doError) {
|
|
1338
|
-
var er;
|
|
1339
|
-
if (args.length > 0) er = args[0];
|
|
1340
|
-
if (er instanceof Error) throw er;
|
|
1341
|
-
var err = /* @__PURE__ */ new Error("Unhandled error." + (er ? " (" + er.message + ")" : ""));
|
|
1342
|
-
err.context = er;
|
|
1343
|
-
throw err;
|
|
1344
|
-
}
|
|
1345
|
-
var handler = events[type];
|
|
1346
|
-
if (handler === void 0) return false;
|
|
1347
|
-
if (typeof handler === "function") ReflectApply(handler, this, args);
|
|
1348
|
-
else {
|
|
1349
|
-
var len = handler.length;
|
|
1350
|
-
var listeners = arrayClone(handler, len);
|
|
1351
|
-
for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args);
|
|
1352
|
-
}
|
|
1353
|
-
return true;
|
|
1231
|
+
/**
|
|
1232
|
+
* This method allows to configure global defaults for the request configuration like method, auth, deduplication etc.
|
|
1233
|
+
*/
|
|
1234
|
+
setRequestDefaults = (callback) => {
|
|
1235
|
+
this.unstable_getRequestDefaults = callback;
|
|
1236
|
+
return this;
|
|
1354
1237
|
};
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
if (events === void 0) {
|
|
1362
|
-
events = target._events = Object.create(null);
|
|
1363
|
-
target._eventsCount = 0;
|
|
1364
|
-
} else {
|
|
1365
|
-
if (events.newListener !== void 0) {
|
|
1366
|
-
target.emit("newListener", type, listener.listener ? listener.listener : listener);
|
|
1367
|
-
events = target._events;
|
|
1368
|
-
}
|
|
1369
|
-
existing = events[type];
|
|
1370
|
-
}
|
|
1371
|
-
if (existing === void 0) {
|
|
1372
|
-
existing = events[type] = listener;
|
|
1373
|
-
++target._eventsCount;
|
|
1374
|
-
} else {
|
|
1375
|
-
if (typeof existing === "function") existing = events[type] = prepend ? [listener, existing] : [existing, listener];
|
|
1376
|
-
else if (prepend) existing.unshift(listener);
|
|
1377
|
-
else existing.push(listener);
|
|
1378
|
-
m = _getMaxListeners(target);
|
|
1379
|
-
if (m > 0 && existing.length > m && !existing.warned) {
|
|
1380
|
-
existing.warned = true;
|
|
1381
|
-
var w = /* @__PURE__ */ new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit");
|
|
1382
|
-
w.name = "MaxListenersExceededWarning";
|
|
1383
|
-
w.emitter = target;
|
|
1384
|
-
w.type = type;
|
|
1385
|
-
w.count = existing.length;
|
|
1386
|
-
ProcessEmitWarning(w);
|
|
1387
|
-
}
|
|
1388
|
-
}
|
|
1389
|
-
return target;
|
|
1390
|
-
}
|
|
1391
|
-
EventEmitter.prototype.addListener = function addListener(type, listener) {
|
|
1392
|
-
return _addListener(this, type, listener, false);
|
|
1238
|
+
/**
|
|
1239
|
+
* Set the adapter default options added to every sent request
|
|
1240
|
+
*/
|
|
1241
|
+
setAdapterDefaults = (callback) => {
|
|
1242
|
+
this.unstable_getAdapterDefaults = callback;
|
|
1243
|
+
return this;
|
|
1393
1244
|
};
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1245
|
+
/** Set a custom mapping for internal adapter errors before they are returned in the response. */
|
|
1246
|
+
setInternalErrorMapping = (callback) => {
|
|
1247
|
+
this.unstable_internalErrorMapping = callback;
|
|
1248
|
+
return this;
|
|
1397
1249
|
};
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
return this.listener.apply(this.target, arguments);
|
|
1404
|
-
}
|
|
1405
|
-
}
|
|
1406
|
-
function _onceWrap(target, type, listener) {
|
|
1407
|
-
var state = {
|
|
1408
|
-
fired: false,
|
|
1409
|
-
wrapFn: void 0,
|
|
1410
|
-
target,
|
|
1411
|
-
type,
|
|
1412
|
-
listener
|
|
1413
|
-
};
|
|
1414
|
-
var wrapped = onceWrapper.bind(state);
|
|
1415
|
-
wrapped.listener = listener;
|
|
1416
|
-
state.wrapFn = wrapped;
|
|
1417
|
-
return wrapped;
|
|
1418
|
-
}
|
|
1419
|
-
EventEmitter.prototype.once = function once(type, listener) {
|
|
1420
|
-
checkListener(listener);
|
|
1421
|
-
this.on(type, _onceWrap(this, type, listener));
|
|
1250
|
+
/**
|
|
1251
|
+
* Set the custom header mapping function
|
|
1252
|
+
*/
|
|
1253
|
+
setHeaderMapper = (headerMapper) => {
|
|
1254
|
+
this.unstable_headerMapper = ((req) => headerMapper(req, this.unstable_headerMapperConfig));
|
|
1422
1255
|
return this;
|
|
1423
1256
|
};
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1257
|
+
/**
|
|
1258
|
+
* Set the payload mapping function which runs before every request is sent.
|
|
1259
|
+
* It is called with the raw payload and the value set with `setPayloadMapperConfig`,
|
|
1260
|
+
* and its return value is the body passed to the adapter.
|
|
1261
|
+
* Requests with their own `request.setPayloadMapper` skip it.
|
|
1262
|
+
* @example
|
|
1263
|
+
* ```ts
|
|
1264
|
+
* client.adapter.setPayloadMapper((payload, config) => encrypt(JSON.stringify(payload), config));
|
|
1265
|
+
* ```
|
|
1266
|
+
*/
|
|
1267
|
+
setPayloadMapper = (payloadMapper) => {
|
|
1268
|
+
this.unstable_payloadMapper = ((payload) => payloadMapper(payload, this.unstable_payloadMapperConfig));
|
|
1427
1269
|
return this;
|
|
1428
1270
|
};
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
list = events[type];
|
|
1435
|
-
if (list === void 0) return this;
|
|
1436
|
-
if (list === listener || list.listener === listener) if (--this._eventsCount === 0) this._events = Object.create(null);
|
|
1437
|
-
else {
|
|
1438
|
-
delete events[type];
|
|
1439
|
-
if (events.removeListener) this.emit("removeListener", type, list.listener || listener);
|
|
1440
|
-
}
|
|
1441
|
-
else if (typeof list !== "function") {
|
|
1442
|
-
position = -1;
|
|
1443
|
-
for (i = list.length - 1; i >= 0; i--) if (list[i] === listener || list[i].listener === listener) {
|
|
1444
|
-
originalListener = list[i].listener;
|
|
1445
|
-
position = i;
|
|
1446
|
-
break;
|
|
1447
|
-
}
|
|
1448
|
-
if (position < 0) return this;
|
|
1449
|
-
if (position === 0) list.shift();
|
|
1450
|
-
else spliceOne(list, position);
|
|
1451
|
-
if (list.length === 1) events[type] = list[0];
|
|
1452
|
-
if (events.removeListener !== void 0) this.emit("removeListener", type, originalListener || listener);
|
|
1453
|
-
}
|
|
1271
|
+
/**
|
|
1272
|
+
* Set the endpoint mapping function which transforms the endpoint string before the request is sent
|
|
1273
|
+
*/
|
|
1274
|
+
setEndpointMapper = (endpointMapper) => {
|
|
1275
|
+
this.unstable_endpointMapper = ((endpoint) => endpointMapper(endpoint, this.unstable_endpointMapperConfig));
|
|
1454
1276
|
return this;
|
|
1455
1277
|
};
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
if (arguments.length === 0) {
|
|
1462
|
-
this._events = Object.create(null);
|
|
1463
|
-
this._eventsCount = 0;
|
|
1464
|
-
} else if (events[type] !== void 0) if (--this._eventsCount === 0) this._events = Object.create(null);
|
|
1465
|
-
else delete events[type];
|
|
1466
|
-
return this;
|
|
1467
|
-
}
|
|
1468
|
-
if (arguments.length === 0) {
|
|
1469
|
-
var keys = Object.keys(events);
|
|
1470
|
-
var key;
|
|
1471
|
-
for (i = 0; i < keys.length; ++i) {
|
|
1472
|
-
key = keys[i];
|
|
1473
|
-
if (key === "removeListener") continue;
|
|
1474
|
-
this.removeAllListeners(key);
|
|
1475
|
-
}
|
|
1476
|
-
this.removeAllListeners("removeListener");
|
|
1477
|
-
this._events = Object.create(null);
|
|
1478
|
-
this._eventsCount = 0;
|
|
1479
|
-
return this;
|
|
1480
|
-
}
|
|
1481
|
-
listeners = events[type];
|
|
1482
|
-
if (typeof listeners === "function") this.removeListener(type, listeners);
|
|
1483
|
-
else if (listeners !== void 0) for (i = listeners.length - 1; i >= 0; i--) this.removeListener(type, listeners[i]);
|
|
1278
|
+
/**
|
|
1279
|
+
* Set the query params mapping function which get triggered before request get sent
|
|
1280
|
+
*/
|
|
1281
|
+
setQueryParamsMapper = (queryParamsMapper) => {
|
|
1282
|
+
this.unstable_queryParamsMapper = ((queryParams) => queryParamsMapper(queryParams, this.unstable_queryParamsMapperConfig));
|
|
1484
1283
|
return this;
|
|
1485
1284
|
};
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1285
|
+
/**
|
|
1286
|
+
* Let requests take query params as a callback. When a request gets a function as its query params (in
|
|
1287
|
+
* `createRequest`, `setQueryParams` or `send`), the resolver runs right away and the request stores what it returns,
|
|
1288
|
+
* so cache keys, query keys and `toJSON()` only ever see data. The resolver decides what the callback receives.
|
|
1289
|
+
*
|
|
1290
|
+
* Opt-in: adapters without a resolver store query params as given. Declare the callback in the adapter's query params
|
|
1291
|
+
* type so requests accept it.
|
|
1292
|
+
*
|
|
1293
|
+
* @example
|
|
1294
|
+
* // The Firebase adapter passes a constraints builder and stores the constraints it collected
|
|
1295
|
+
* adapter.setQueryParamsResolver((callback) => callback(createConstraints()).toJSON());
|
|
1296
|
+
*/
|
|
1297
|
+
setQueryParamsResolver = (resolver) => {
|
|
1298
|
+
this.unstable_queryParamsResolver = resolver;
|
|
1299
|
+
return this;
|
|
1496
1300
|
};
|
|
1497
|
-
|
|
1498
|
-
|
|
1301
|
+
/** Set the configuration object passed as the second argument to the query params mapper. */
|
|
1302
|
+
setQueryParamsMapperConfig = (config) => {
|
|
1303
|
+
this.unstable_queryParamsMapperConfig = config;
|
|
1304
|
+
return this;
|
|
1499
1305
|
};
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1306
|
+
/** Set the configuration object passed as the second argument to the header mapper. */
|
|
1307
|
+
setHeaderMapperConfig = (config) => {
|
|
1308
|
+
this.unstable_headerMapperConfig = config;
|
|
1309
|
+
return this;
|
|
1503
1310
|
};
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
var evlistener = events[type];
|
|
1509
|
-
if (typeof evlistener === "function") return 1;
|
|
1510
|
-
else if (evlistener !== void 0) return evlistener.length;
|
|
1511
|
-
}
|
|
1512
|
-
return 0;
|
|
1513
|
-
}
|
|
1514
|
-
EventEmitter.prototype.eventNames = function eventNames() {
|
|
1515
|
-
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
|
|
1311
|
+
/** Set the configuration object passed as the second argument to the endpoint mapper. */
|
|
1312
|
+
setEndpointMapperConfig = (config) => {
|
|
1313
|
+
this.unstable_endpointMapperConfig = config;
|
|
1314
|
+
return this;
|
|
1516
1315
|
};
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
return
|
|
1521
|
-
}
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1316
|
+
/** Set the configuration object passed as the second argument to the payload mapper. */
|
|
1317
|
+
setPayloadMapperConfig = (config) => {
|
|
1318
|
+
this.unstable_payloadMapperConfig = config;
|
|
1319
|
+
return this;
|
|
1320
|
+
};
|
|
1321
|
+
/**
|
|
1322
|
+
* ********************
|
|
1323
|
+
* Fetching
|
|
1324
|
+
* ********************
|
|
1325
|
+
*/
|
|
1326
|
+
/** Set the fetcher function that performs the actual network request. Must be called before any request can be executed. */
|
|
1327
|
+
setFetcher(fetcher) {
|
|
1328
|
+
this.unstable_fetcher = fetcher.bind(this);
|
|
1329
|
+
return this;
|
|
1530
1330
|
}
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1331
|
+
/** Execute a request through the adapter pipeline: maps endpoint/headers/payload, runs plugins, then calls the fetcher. */
|
|
1332
|
+
async fetch(request, requestId) {
|
|
1333
|
+
let startTime;
|
|
1334
|
+
const execute = async (resolve) => {
|
|
1335
|
+
try {
|
|
1336
|
+
if (!this.initialized) throw new RequestProcessingError(`Adapter ${this.options.name} is not initialized`);
|
|
1337
|
+
if (!this.unstable_fetcher) throw new RequestProcessingError(`Fetcher for ${this.options.name} adapter is not set`);
|
|
1338
|
+
this.client.triggerPlugins("onAdapterFetch", {
|
|
1339
|
+
adapter: this,
|
|
1340
|
+
request,
|
|
1341
|
+
requestId
|
|
1342
|
+
});
|
|
1343
|
+
const bindings = await getAdapterBindings({
|
|
1344
|
+
request,
|
|
1345
|
+
requestId,
|
|
1346
|
+
resolve,
|
|
1347
|
+
internalErrorMapping: this.unstable_internalErrorMapping,
|
|
1348
|
+
onStartTime: (time) => {
|
|
1349
|
+
startTime = time;
|
|
1350
|
+
}
|
|
1351
|
+
});
|
|
1352
|
+
if (request.unstable_mock && request.isMockerEnabled && request.client.isMockerEnabled) return await mocker(bindings);
|
|
1353
|
+
return await this.unstable_fetcher(bindings);
|
|
1354
|
+
} catch (error) {
|
|
1355
|
+
return getAdapterOnError({
|
|
1356
|
+
request,
|
|
1357
|
+
requestId,
|
|
1358
|
+
startTime: startTime || Date.now(),
|
|
1359
|
+
logger: this.logger,
|
|
1360
|
+
resolve
|
|
1361
|
+
})({
|
|
1362
|
+
error: this.unstable_internalErrorMapping(error),
|
|
1363
|
+
status: this.options.systemErrorStatus,
|
|
1364
|
+
extra: this.options.systemErrorExtra
|
|
1365
|
+
});
|
|
1540
1366
|
}
|
|
1541
|
-
|
|
1542
|
-
|
|
1367
|
+
};
|
|
1368
|
+
return new Promise((resolve) => {
|
|
1369
|
+
execute(resolve);
|
|
1543
1370
|
});
|
|
1544
1371
|
}
|
|
1545
|
-
|
|
1546
|
-
|
|
1372
|
+
};
|
|
1373
|
+
//#endregion
|
|
1374
|
+
//#region src/constants/http.constants.ts
|
|
1375
|
+
var HttpMethods = /* @__PURE__ */ function(HttpMethods) {
|
|
1376
|
+
HttpMethods["GET"] = "GET";
|
|
1377
|
+
HttpMethods["POST"] = "POST";
|
|
1378
|
+
HttpMethods["PUT"] = "PUT";
|
|
1379
|
+
HttpMethods["PATCH"] = "PATCH";
|
|
1380
|
+
HttpMethods["DELETE"] = "DELETE";
|
|
1381
|
+
/** Safe, idempotent read with a request body (IETF draft-ietf-httpbis-safe-method-w-body). */
|
|
1382
|
+
HttpMethods["QUERY"] = "QUERY";
|
|
1383
|
+
return HttpMethods;
|
|
1384
|
+
}({});
|
|
1385
|
+
/** Methods that are safe reads: routed to the fetch dispatcher and deduplicated by default. */
|
|
1386
|
+
var SAFE_HTTP_METHODS = [HttpMethods.GET, HttpMethods.QUERY];
|
|
1387
|
+
//#endregion
|
|
1388
|
+
//#region src/optimistic/optimistic.utils.ts
|
|
1389
|
+
var isComparableId = (value) => typeof value === "string" || typeof value === "number";
|
|
1390
|
+
/**
|
|
1391
|
+
* Tells if the item is selected by the match. Plain values are compared with the `key` field of the item, numbers and
|
|
1392
|
+
* strings match each other the same way route params do (`"1"` matches `1`).
|
|
1393
|
+
*/
|
|
1394
|
+
var isOptimisticMatch = (item, match, key = "id") => {
|
|
1395
|
+
if (typeof match === "function") return !!match(item);
|
|
1396
|
+
if (item === null || typeof item !== "object") return false;
|
|
1397
|
+
const value = item[key];
|
|
1398
|
+
if (Object.is(value, match)) return true;
|
|
1399
|
+
return isComparableId(value) && isComparableId(match) && String(value) === String(match);
|
|
1400
|
+
};
|
|
1401
|
+
var assertList = (list) => {
|
|
1402
|
+
if (!Array.isArray(list)) throw new TypeError("Optimistic list helpers need an array, use .list(field) for an array inside an object");
|
|
1403
|
+
return list;
|
|
1404
|
+
};
|
|
1405
|
+
var assertEntry = (data) => {
|
|
1406
|
+
if (data === null || typeof data !== "object" || Array.isArray(data)) throw new TypeError("Optimistic increment(field, by) needs an object, use increment(match, field, by) on a list");
|
|
1407
|
+
return data;
|
|
1408
|
+
};
|
|
1409
|
+
var addToField = (item, field, by) => {
|
|
1410
|
+
const value = item[field];
|
|
1411
|
+
return {
|
|
1412
|
+
...item,
|
|
1413
|
+
[field]: (typeof value === "number" ? value : 0) + by
|
|
1414
|
+
};
|
|
1415
|
+
};
|
|
1416
|
+
/**
|
|
1417
|
+
* Maps the matching items. The list keeps its reference when nothing matched, so unchanged data produces no write.
|
|
1418
|
+
*/
|
|
1419
|
+
var mapMatching = (list, { match, key }, map) => {
|
|
1420
|
+
const items = assertList(list);
|
|
1421
|
+
let changed = false;
|
|
1422
|
+
const next = items.map((item) => {
|
|
1423
|
+
if (!isOptimisticMatch(item, match, key)) return item;
|
|
1424
|
+
changed = true;
|
|
1425
|
+
return map(item);
|
|
1426
|
+
});
|
|
1427
|
+
return changed ? next : items;
|
|
1428
|
+
};
|
|
1429
|
+
var patchItems = (list, selector, fields) => {
|
|
1430
|
+
return mapMatching(list, selector, (item) => ({
|
|
1431
|
+
...item,
|
|
1432
|
+
...fields
|
|
1433
|
+
}));
|
|
1434
|
+
};
|
|
1435
|
+
var insertItem = (list, item, options) => {
|
|
1436
|
+
const items = assertList(list);
|
|
1437
|
+
const at = options?.at ?? "end";
|
|
1438
|
+
if (at === "start") return [item, ...items];
|
|
1439
|
+
if (at === "end") return [...items, item];
|
|
1440
|
+
const next = [...items];
|
|
1441
|
+
next.splice(at, 0, item);
|
|
1442
|
+
return next;
|
|
1443
|
+
};
|
|
1444
|
+
var removeItems = (list, { match, key }) => {
|
|
1445
|
+
const items = assertList(list);
|
|
1446
|
+
const next = items.filter((item) => !isOptimisticMatch(item, match, key));
|
|
1447
|
+
return next.length === items.length ? items : next;
|
|
1448
|
+
};
|
|
1449
|
+
var incrementItems = (list, selector, { field, by }) => {
|
|
1450
|
+
return mapMatching(list, selector, (item) => addToField(item, field, by));
|
|
1451
|
+
};
|
|
1452
|
+
var incrementField = (data, field, by) => {
|
|
1453
|
+
return addToField(assertEntry(data), field, by);
|
|
1454
|
+
};
|
|
1455
|
+
/**
|
|
1456
|
+
* Runs a list helper on the array held in `field`. A missing list counts as empty, the object keeps its reference when
|
|
1457
|
+
* the list did not change.
|
|
1458
|
+
*/
|
|
1459
|
+
var updateListField = (data, field, update) => {
|
|
1460
|
+
const entry = assertEntry(data);
|
|
1461
|
+
const list = entry[field] ?? [];
|
|
1462
|
+
const next = update(assertList(list));
|
|
1463
|
+
return next === list ? entry : {
|
|
1464
|
+
...entry,
|
|
1465
|
+
[field]: next
|
|
1466
|
+
};
|
|
1467
|
+
};
|
|
1468
|
+
//#endregion
|
|
1469
|
+
//#region src/optimistic/optimistic.ts
|
|
1470
|
+
/**
|
|
1471
|
+
* One change of one target, built with `optimistic(target)`. Core applies it before the mutation is sent, and runs its
|
|
1472
|
+
* `.commit()` on success or its `.rollback()` when the mutation fails, is aborted or removed from the queue.
|
|
1473
|
+
* Operations are immutable - `.rollback()` and `.commit()` return a new operation, so one can be reused.
|
|
1474
|
+
*/
|
|
1475
|
+
var OptimisticOperation = class OptimisticOperation {
|
|
1476
|
+
/** @internal */
|
|
1477
|
+
target;
|
|
1478
|
+
/** @internal */
|
|
1479
|
+
allVariants;
|
|
1480
|
+
/** @internal */
|
|
1481
|
+
update;
|
|
1482
|
+
/** @internal */
|
|
1483
|
+
onRollback = void 0;
|
|
1484
|
+
/** @internal */
|
|
1485
|
+
onCommit = void 0;
|
|
1486
|
+
constructor(options) {
|
|
1487
|
+
this.target = options.target;
|
|
1488
|
+
this.allVariants = options.allVariants;
|
|
1489
|
+
this.update = options.update;
|
|
1490
|
+
this.onRollback = options.onRollback;
|
|
1491
|
+
this.onCommit = options.onCommit;
|
|
1547
1492
|
}
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1493
|
+
/**
|
|
1494
|
+
* Undo of this change, written by hand and run by core when the mutation fails for good, is aborted or removed from
|
|
1495
|
+
* the queue. Rollbacks of one mutation run in reverse order of the changes. It receives
|
|
1496
|
+
* `{ data, previous, reason, response, request }` and returns the new data; returning nothing leaves the data as it
|
|
1497
|
+
* is. Build the result from `data` and use `previous` only to look old values up. Must be synchronous.
|
|
1498
|
+
* Without it nothing is undone locally and the target is refetched.
|
|
1499
|
+
*/
|
|
1500
|
+
rollback(callback) {
|
|
1501
|
+
return new OptimisticOperation({
|
|
1502
|
+
target: this.target,
|
|
1503
|
+
allVariants: this.allVariants,
|
|
1504
|
+
update: this.update,
|
|
1505
|
+
onRollback: callback,
|
|
1506
|
+
onCommit: this.onCommit
|
|
1554
1507
|
});
|
|
1555
|
-
else throw new TypeError("The \"emitter\" argument must be of type EventEmitter. Received type " + typeof emitter);
|
|
1556
|
-
}
|
|
1557
|
-
})))());
|
|
1558
|
-
var getListenName = (event) => `listen_${String(event)}`;
|
|
1559
|
-
var EventEmitter = class extends import_events.default {
|
|
1560
|
-
emitCallbacks = [];
|
|
1561
|
-
constructor(options) {
|
|
1562
|
-
super(options);
|
|
1563
1508
|
}
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
return
|
|
1509
|
+
/**
|
|
1510
|
+
* Runs when the mutation succeeds, before the target is refreshed. It receives `{ data, response, request }` and
|
|
1511
|
+
* returns the new data, for example to swap a temporary item for the one from the response. Returning nothing leaves
|
|
1512
|
+
* the data as it is. Must be synchronous.
|
|
1513
|
+
*/
|
|
1514
|
+
commit(callback) {
|
|
1515
|
+
return new OptimisticOperation({
|
|
1516
|
+
target: this.target,
|
|
1517
|
+
allVariants: this.allVariants,
|
|
1518
|
+
update: this.update,
|
|
1519
|
+
onRollback: this.onRollback,
|
|
1520
|
+
onCommit: callback
|
|
1521
|
+
});
|
|
1571
1522
|
}
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
return () => {
|
|
1581
|
-
super.off(getListenName(event), listener);
|
|
1582
|
-
};
|
|
1583
|
-
};
|
|
1584
|
-
on = (event, listener) => {
|
|
1585
|
-
super.on(event, listener);
|
|
1586
|
-
super.emit(getListenName(event), super.listeners(event).length);
|
|
1587
|
-
return this;
|
|
1523
|
+
};
|
|
1524
|
+
var createTarget = (target, allVariants) => {
|
|
1525
|
+
const operation = (update) => {
|
|
1526
|
+
return new OptimisticOperation({
|
|
1527
|
+
target,
|
|
1528
|
+
allVariants,
|
|
1529
|
+
update
|
|
1530
|
+
});
|
|
1588
1531
|
};
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1532
|
+
const createListHelpers = (onList) => ({
|
|
1533
|
+
patch: (match, fields, options) => {
|
|
1534
|
+
return operation(onList((list) => patchItems(list, {
|
|
1535
|
+
match,
|
|
1536
|
+
key: options?.key
|
|
1537
|
+
}, fields)));
|
|
1538
|
+
},
|
|
1539
|
+
insert: (item, options) => {
|
|
1540
|
+
return operation(onList((list) => insertItem(list, item, options)));
|
|
1541
|
+
},
|
|
1542
|
+
remove: (match, options) => {
|
|
1543
|
+
return operation(onList((list) => removeItems(list, {
|
|
1544
|
+
match,
|
|
1545
|
+
key: options?.key
|
|
1546
|
+
})));
|
|
1547
|
+
},
|
|
1548
|
+
increment: (match, field, by, options) => {
|
|
1549
|
+
return operation(onList((list) => incrementItems(list, {
|
|
1550
|
+
match,
|
|
1551
|
+
key: options?.key
|
|
1552
|
+
}, {
|
|
1553
|
+
field,
|
|
1554
|
+
by
|
|
1555
|
+
})));
|
|
1556
|
+
}
|
|
1557
|
+
});
|
|
1558
|
+
const listHelpers = createListHelpers((update) => (data) => update(data));
|
|
1559
|
+
return {
|
|
1560
|
+
...listHelpers,
|
|
1561
|
+
set: (updater) => operation(updater),
|
|
1562
|
+
increment: (...args) => {
|
|
1563
|
+
if (args.length >= 3) {
|
|
1564
|
+
const [match, field, by, options] = args;
|
|
1565
|
+
return listHelpers.increment(match, field, by, options);
|
|
1566
|
+
}
|
|
1567
|
+
const [field, by] = args;
|
|
1568
|
+
return operation((data) => incrementField(data, field, by));
|
|
1569
|
+
},
|
|
1570
|
+
list: (field) => {
|
|
1571
|
+
return createListHelpers((update) => (data) => updateListField(data, field, update));
|
|
1572
|
+
}
|
|
1593
1573
|
};
|
|
1594
|
-
addListener = this.on;
|
|
1595
|
-
removeListener = this.off;
|
|
1596
1574
|
};
|
|
1575
|
+
var optimisticFactory = (target) => createTarget(target, false);
|
|
1576
|
+
optimisticFactory.all = (target) => createTarget(target, true);
|
|
1577
|
+
/**
|
|
1578
|
+
* Describes an optimistic change of a cached request. Return the operations from `setOptimistic` or pass them with the
|
|
1579
|
+
* `optimistic` send option, core applies them, runs `.commit()` / `.rollback()` when the mutation settles and refreshes
|
|
1580
|
+
* the targets once the last pending mutation on them is done.
|
|
1581
|
+
*
|
|
1582
|
+
* - `optimistic(getTodos)` - the entry of this request (its params and query params)
|
|
1583
|
+
* - `optimistic.all(getTodos)` - every cached variant of it, whatever the query params (filters, infinite pages)
|
|
1584
|
+
*
|
|
1585
|
+
* Helpers: `set(updater)`, `patch(match, fields)`, `insert(item, { at })`, `remove(match)`,
|
|
1586
|
+
* `increment(field, by)` / `increment(match, field, by)` and `.list("field")` for an array inside an object.
|
|
1587
|
+
*
|
|
1588
|
+
* @example
|
|
1589
|
+
* optimistic(getTodos)
|
|
1590
|
+
* .patch(params.todoId, payload)
|
|
1591
|
+
* .rollback(({ data, previous }) => {
|
|
1592
|
+
* const before = previous.find((todo) => todo.id === params.todoId);
|
|
1593
|
+
* return data.map((todo) => (todo.id === params.todoId && before ? before : todo));
|
|
1594
|
+
* });
|
|
1595
|
+
*/
|
|
1596
|
+
var optimistic = optimisticFactory;
|
|
1597
1597
|
//#endregion
|
|
1598
1598
|
//#region src/optimistic/optimistic.settlement.ts
|
|
1599
1599
|
var clientStates = /* @__PURE__ */ new WeakMap();
|
|
@@ -2010,10 +2010,90 @@ var mapResponseForSend = async (request, response) => {
|
|
|
2010
2010
|
if (mapping instanceof Promise) return await mapping;
|
|
2011
2011
|
return mapping || response;
|
|
2012
2012
|
};
|
|
2013
|
+
/**
|
|
2014
|
+
* Passes the lifecycle events of one request id to the callbacks given to `send()` / `exec()` and to the request
|
|
2015
|
+
* `$hooks`. Returns the function that removes the listeners.
|
|
2016
|
+
*/
|
|
2017
|
+
var subscribeRequestCallbacks = ({ request, requestId, options, mutationContext }) => {
|
|
2018
|
+
const { requestManager } = request.client;
|
|
2019
|
+
const { $hooks } = request;
|
|
2020
|
+
const unmounts = [
|
|
2021
|
+
requestManager.events.onRequestStartById(requestId, (data) => {
|
|
2022
|
+
const enriched = {
|
|
2023
|
+
...data,
|
|
2024
|
+
mutationContext
|
|
2025
|
+
};
|
|
2026
|
+
runUserCode(() => options?.onRequestStart?.(enriched));
|
|
2027
|
+
runUserCode(() => $hooks.__emit("onRequestStart", enriched));
|
|
2028
|
+
}),
|
|
2029
|
+
requestManager.events.onResponseStartById(requestId, (data) => {
|
|
2030
|
+
const enriched = {
|
|
2031
|
+
...data,
|
|
2032
|
+
mutationContext
|
|
2033
|
+
};
|
|
2034
|
+
runUserCode(() => options?.onResponseStart?.(enriched));
|
|
2035
|
+
runUserCode(() => $hooks.__emit("onResponseStart", enriched));
|
|
2036
|
+
}),
|
|
2037
|
+
requestManager.events.onUploadProgressById(requestId, (data) => {
|
|
2038
|
+
const enriched = {
|
|
2039
|
+
...data,
|
|
2040
|
+
mutationContext
|
|
2041
|
+
};
|
|
2042
|
+
runUserCode(() => options?.onUploadProgress?.(enriched));
|
|
2043
|
+
runUserCode(() => $hooks.__emit("onUploadProgress", enriched));
|
|
2044
|
+
}),
|
|
2045
|
+
requestManager.events.onDownloadProgressById(requestId, (data) => {
|
|
2046
|
+
const enriched = {
|
|
2047
|
+
...data,
|
|
2048
|
+
mutationContext
|
|
2049
|
+
};
|
|
2050
|
+
runUserCode(() => options?.onDownloadProgress?.(enriched));
|
|
2051
|
+
runUserCode(() => $hooks.__emit("onDownloadProgress", enriched));
|
|
2052
|
+
}),
|
|
2053
|
+
requestManager.events.onRetryById(requestId, (data) => {
|
|
2054
|
+
const enriched = {
|
|
2055
|
+
...data,
|
|
2056
|
+
mutationContext
|
|
2057
|
+
};
|
|
2058
|
+
runUserCode(() => options?.onRetry?.(enriched));
|
|
2059
|
+
runUserCode(() => $hooks.__emit("onRetry", enriched));
|
|
2060
|
+
})
|
|
2061
|
+
];
|
|
2062
|
+
return () => unmounts.forEach((unmount) => unmount());
|
|
2063
|
+
};
|
|
2064
|
+
/**
|
|
2065
|
+
* Calls `onAbort` once when the signal of the caller aborts - right away when it is aborted already. The signal only
|
|
2066
|
+
* triggers the abort controller HyperFetch keeps for the request, so it ends like `request.abort()` does. Returns the
|
|
2067
|
+
* function that stops listening.
|
|
2068
|
+
*/
|
|
2069
|
+
var linkAbortSignal = (signal, onAbort) => {
|
|
2070
|
+
if (!signal) return () => {};
|
|
2071
|
+
if (signal.aborted) {
|
|
2072
|
+
onAbort();
|
|
2073
|
+
return () => {};
|
|
2074
|
+
}
|
|
2075
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2076
|
+
return () => signal.removeEventListener("abort", onAbort);
|
|
2077
|
+
};
|
|
2078
|
+
/** Response of a call that was aborted before the adapter could answer it - the same as the adapter gives an abort */
|
|
2079
|
+
var getAbortedResponse = (request) => {
|
|
2080
|
+
const { adapter } = request.client;
|
|
2081
|
+
return {
|
|
2082
|
+
data: null,
|
|
2083
|
+
error: adapter.unstable_internalErrorMapping(getErrorMessage("abort")),
|
|
2084
|
+
status: adapter.systemErrorStatus,
|
|
2085
|
+
success: false,
|
|
2086
|
+
extra: adapter.systemErrorExtra,
|
|
2087
|
+
requestTimestamp: Date.now(),
|
|
2088
|
+
responseTimestamp: Date.now()
|
|
2089
|
+
};
|
|
2090
|
+
};
|
|
2013
2091
|
var sendRequest = async (request, options) => {
|
|
2014
2092
|
const { client } = request;
|
|
2015
2093
|
const { requestManager } = client;
|
|
2016
2094
|
const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);
|
|
2095
|
+
const signal = options?.signal;
|
|
2096
|
+
if (signal?.aborted) return getAbortedResponse(request);
|
|
2017
2097
|
let mutationContext;
|
|
2018
2098
|
let pendingOptimistic;
|
|
2019
2099
|
const optimisticSource = options?.optimistic ?? request.optimistic;
|
|
@@ -2045,8 +2125,12 @@ var sendRequest = async (request, options) => {
|
|
|
2045
2125
|
let isResolved = false;
|
|
2046
2126
|
let isDelivered = false;
|
|
2047
2127
|
let isSettled = false;
|
|
2048
|
-
const requestId = dispatcher.add(request);
|
|
2049
2128
|
const queryKey = scopeKey(request.queryKey, request.scope);
|
|
2129
|
+
const queuedIds = signal ? new Set(dispatcher.getQueue(queryKey).requests.map((item) => item.requestId)) : null;
|
|
2130
|
+
const requestId = dispatcher.add(request);
|
|
2131
|
+
const isJoined = !!queuedIds?.has(requestId);
|
|
2132
|
+
let isRemovedBySignal = false;
|
|
2133
|
+
let unlinkSignal = () => {};
|
|
2050
2134
|
const { $hooks } = request;
|
|
2051
2135
|
const getWillBeResent = ({ response, details }) => {
|
|
2052
2136
|
if (response.success || details.isCanceled) return false;
|
|
@@ -2093,45 +2177,11 @@ var sendRequest = async (request, options) => {
|
|
|
2093
2177
|
};
|
|
2094
2178
|
runUserCode(() => options?.onBeforeSent?.(beforeSentData));
|
|
2095
2179
|
runUserCode(() => $hooks.__emit("onBeforeSent", beforeSentData));
|
|
2096
|
-
const
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
runUserCode(() => options?.onRequestStart?.(enriched));
|
|
2102
|
-
runUserCode(() => $hooks.__emit("onRequestStart", enriched));
|
|
2103
|
-
});
|
|
2104
|
-
const unmountResponseStart = requestManager.events.onResponseStartById(requestId, (data) => {
|
|
2105
|
-
const enriched = {
|
|
2106
|
-
...data,
|
|
2107
|
-
mutationContext
|
|
2108
|
-
};
|
|
2109
|
-
runUserCode(() => options?.onResponseStart?.(enriched));
|
|
2110
|
-
runUserCode(() => $hooks.__emit("onResponseStart", enriched));
|
|
2111
|
-
});
|
|
2112
|
-
const unmountUpload = requestManager.events.onUploadProgressById(requestId, (data) => {
|
|
2113
|
-
const enriched = {
|
|
2114
|
-
...data,
|
|
2115
|
-
mutationContext
|
|
2116
|
-
};
|
|
2117
|
-
runUserCode(() => options?.onUploadProgress?.(enriched));
|
|
2118
|
-
runUserCode(() => $hooks.__emit("onUploadProgress", enriched));
|
|
2119
|
-
});
|
|
2120
|
-
const unmountDownload = requestManager.events.onDownloadProgressById(requestId, (data) => {
|
|
2121
|
-
const enriched = {
|
|
2122
|
-
...data,
|
|
2123
|
-
mutationContext
|
|
2124
|
-
};
|
|
2125
|
-
runUserCode(() => options?.onDownloadProgress?.(enriched));
|
|
2126
|
-
runUserCode(() => $hooks.__emit("onDownloadProgress", enriched));
|
|
2127
|
-
});
|
|
2128
|
-
const unmountRetry = requestManager.events.onRetryById(requestId, (data) => {
|
|
2129
|
-
const enriched = {
|
|
2130
|
-
...data,
|
|
2131
|
-
mutationContext
|
|
2132
|
-
};
|
|
2133
|
-
runUserCode(() => options?.onRetry?.(enriched));
|
|
2134
|
-
runUserCode(() => $hooks.__emit("onRetry", enriched));
|
|
2180
|
+
const unmountCallbacks = subscribeRequestCallbacks({
|
|
2181
|
+
request,
|
|
2182
|
+
requestId,
|
|
2183
|
+
options,
|
|
2184
|
+
mutationContext
|
|
2135
2185
|
});
|
|
2136
2186
|
const unmountResponse = requestManager.events.onResponseById(requestId, (values) => {
|
|
2137
2187
|
const { response } = values;
|
|
@@ -2165,9 +2215,23 @@ var sendRequest = async (request, options) => {
|
|
|
2165
2215
|
if (!isResolved) {
|
|
2166
2216
|
isResolved = true;
|
|
2167
2217
|
isDelivered = true;
|
|
2218
|
+
const removedResponse = isRemovedBySignal ? getAbortedResponse(request) : {
|
|
2219
|
+
data: null,
|
|
2220
|
+
status: null,
|
|
2221
|
+
success: false,
|
|
2222
|
+
error: getErrorMessage("deleted"),
|
|
2223
|
+
extra: request.client.adapter.defaultExtra,
|
|
2224
|
+
requestTimestamp: Date.now(),
|
|
2225
|
+
responseTimestamp: Date.now()
|
|
2226
|
+
};
|
|
2168
2227
|
if (pendingOptimistic && !isSettled) {
|
|
2169
2228
|
isSettled = true;
|
|
2170
|
-
settleOptimistic(pendingOptimistic, {
|
|
2229
|
+
settleOptimistic(pendingOptimistic, isRemovedBySignal ? {
|
|
2230
|
+
type: "rollback",
|
|
2231
|
+
reason: "abort",
|
|
2232
|
+
response: removedResponse,
|
|
2233
|
+
request
|
|
2234
|
+
} : {
|
|
2171
2235
|
type: "rollback",
|
|
2172
2236
|
reason: "removed",
|
|
2173
2237
|
request
|
|
@@ -2179,27 +2243,43 @@ var sendRequest = async (request, options) => {
|
|
|
2179
2243
|
};
|
|
2180
2244
|
runUserCode(() => options?.onRemove?.(enriched));
|
|
2181
2245
|
runUserCode(() => $hooks.__emit("onRemove", enriched));
|
|
2182
|
-
resolve(
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2246
|
+
resolve(removedResponse);
|
|
2247
|
+
umountAll();
|
|
2248
|
+
}
|
|
2249
|
+
});
|
|
2250
|
+
unlinkSignal = linkAbortSignal(signal, () => {
|
|
2251
|
+
if (isDelivered) return;
|
|
2252
|
+
if (isJoined) {
|
|
2253
|
+
isResolved = true;
|
|
2254
|
+
isDelivered = true;
|
|
2255
|
+
const aborted = getAbortedResponse(request);
|
|
2256
|
+
if (pendingOptimistic && !isSettled) {
|
|
2257
|
+
isSettled = true;
|
|
2258
|
+
settleOptimistic(pendingOptimistic, {
|
|
2259
|
+
type: "rollback",
|
|
2260
|
+
reason: "abort",
|
|
2261
|
+
response: aborted,
|
|
2262
|
+
request
|
|
2263
|
+
});
|
|
2264
|
+
}
|
|
2265
|
+
resolve(aborted);
|
|
2191
2266
|
umountAll();
|
|
2267
|
+
return;
|
|
2192
2268
|
}
|
|
2269
|
+
const abortKey = scopeKey(request.abortKey, request.scope);
|
|
2270
|
+
if (dispatcher.hasRunningRequest(queryKey, requestId)) {
|
|
2271
|
+
requestManager.abortByRequestId(abortKey, requestId);
|
|
2272
|
+
return;
|
|
2273
|
+
}
|
|
2274
|
+
isRemovedBySignal = true;
|
|
2275
|
+
dispatcher.delete(queryKey, requestId, abortKey);
|
|
2193
2276
|
});
|
|
2194
2277
|
function umountAll() {
|
|
2195
2278
|
unmountSettlement?.();
|
|
2196
|
-
|
|
2197
|
-
unmountResponseStart();
|
|
2198
|
-
unmountUpload();
|
|
2199
|
-
unmountDownload();
|
|
2200
|
-
unmountRetry();
|
|
2279
|
+
unmountCallbacks();
|
|
2201
2280
|
unmountResponse();
|
|
2202
2281
|
unmountRemoveQueueElement();
|
|
2282
|
+
unlinkSignal();
|
|
2203
2283
|
}
|
|
2204
2284
|
});
|
|
2205
2285
|
};
|
|
@@ -2265,6 +2345,7 @@ var Request = class Request {
|
|
|
2265
2345
|
deduplicate;
|
|
2266
2346
|
deduplicateTime;
|
|
2267
2347
|
structuralSharing;
|
|
2348
|
+
throwOnError;
|
|
2268
2349
|
scope;
|
|
2269
2350
|
/**
|
|
2270
2351
|
* Instance-level lifecycle hooks. These callbacks fire for every `send()` / `exec()` call
|
|
@@ -2306,7 +2387,7 @@ var Request = class Request {
|
|
|
2306
2387
|
this.client = client;
|
|
2307
2388
|
this.requestOptions = requestOptions;
|
|
2308
2389
|
this.initialRequestConfiguration = initialRequestConfiguration;
|
|
2309
|
-
const { endpoint, headers, auth = true, method = client.adapter.defaultMethod, options, cancelable = false, retry = 0, retryTime = 500, cacheTime = Time.MIN * 5, cache = true, staleTime = Time.MIN * 5, queued = false, offline = true, abortKey, cacheKey, queryKey, deduplicate = false, deduplicateTime = null, structuralSharing = true } = {
|
|
2390
|
+
const { endpoint, headers, auth = true, method = client.adapter.defaultMethod, options, cancelable = false, retry = 0, retryTime = 500, cacheTime = Time.MIN * 5, cache = true, staleTime = Time.MIN * 5, queued = false, offline = true, abortKey, cacheKey, queryKey, deduplicate = false, deduplicateTime = null, structuralSharing = true, throwOnError = false } = {
|
|
2310
2391
|
...this.client.adapter.unstable_getRequestDefaults?.(requestOptions),
|
|
2311
2392
|
...requestOptions
|
|
2312
2393
|
};
|
|
@@ -2333,6 +2414,7 @@ var Request = class Request {
|
|
|
2333
2414
|
this.deduplicate = initialRequestConfiguration?.deduplicate ?? deduplicate;
|
|
2334
2415
|
this.deduplicateTime = initialRequestConfiguration?.deduplicateTime ?? deduplicateTime;
|
|
2335
2416
|
this.structuralSharing = initialRequestConfiguration?.structuralSharing ?? structuralSharing;
|
|
2417
|
+
this.throwOnError = initialRequestConfiguration?.throwOnError ?? throwOnError;
|
|
2336
2418
|
this.scope = initialRequestConfiguration?.scope ?? null;
|
|
2337
2419
|
this.updatedAbortKey = initialRequestConfiguration?.updatedAbortKey ?? false;
|
|
2338
2420
|
this.updatedCacheKey = initialRequestConfiguration?.updatedCacheKey ?? false;
|
|
@@ -2464,6 +2546,13 @@ var Request = class Request {
|
|
|
2464
2546
|
setStructuralSharing = (structuralSharing) => {
|
|
2465
2547
|
return this.clone({ structuralSharing });
|
|
2466
2548
|
};
|
|
2549
|
+
/**
|
|
2550
|
+
* Make `send()` and `exec()` reject with the `error` of a failed response instead of resolving with it - for the
|
|
2551
|
+
* query functions of React Query, the fetchers of SWR and other code which tells failures by a rejected promise.
|
|
2552
|
+
*/
|
|
2553
|
+
setThrowOnError = (throwOnError) => {
|
|
2554
|
+
return this.clone({ throwOnError });
|
|
2555
|
+
};
|
|
2467
2556
|
/** Mark the request as used (prevents automatic refetching in hooks). */
|
|
2468
2557
|
setUsed = (used) => {
|
|
2469
2558
|
return this.clone({ used });
|
|
@@ -2565,6 +2654,7 @@ var Request = class Request {
|
|
|
2565
2654
|
deduplicate: this.deduplicate,
|
|
2566
2655
|
deduplicateTime: this.deduplicateTime,
|
|
2567
2656
|
structuralSharing: this.structuralSharing,
|
|
2657
|
+
throwOnError: this.throwOnError,
|
|
2568
2658
|
scope: this.scope,
|
|
2569
2659
|
isMockerEnabled: this.isMockerEnabled,
|
|
2570
2660
|
hasMock: !!this.unstable_mock
|
|
@@ -2659,23 +2749,62 @@ var Request = class Request {
|
|
|
2659
2749
|
};
|
|
2660
2750
|
}
|
|
2661
2751
|
/**
|
|
2662
|
-
*
|
|
2752
|
+
* Send the request straight to the adapter, WITHOUT the dispatcher and the cache: it is not queued, deduplicated,
|
|
2753
|
+
* retried or cached. Lifecycle callbacks, `$hooks`, interceptors and the response mapper work like in `send()`.
|
|
2754
|
+
* Use it when something else owns caching and retries, like React Query or SWR - with `signal` and `throwOnError`.
|
|
2663
2755
|
* @param options
|
|
2664
2756
|
* @disableReturns
|
|
2665
2757
|
* @returns
|
|
2666
2758
|
* ```tsx
|
|
2667
|
-
* Promise<
|
|
2759
|
+
* Promise<{ data: Data | null, error: Error | null, status: HttpStatus, ... }>
|
|
2668
2760
|
* ```
|
|
2669
2761
|
*/
|
|
2670
2762
|
exec = async (options) => {
|
|
2763
|
+
const { signal, ...configuration } = options || {};
|
|
2671
2764
|
const { adapter, requestManager } = this.client;
|
|
2672
|
-
const request = this.clone(
|
|
2765
|
+
const request = this.clone(configuration);
|
|
2766
|
+
const { $hooks } = request;
|
|
2673
2767
|
const requestId = this.client.unstable_requestIdMapper(this);
|
|
2674
|
-
const
|
|
2675
|
-
|
|
2768
|
+
const abortKey = scopeKey(request.abortKey, request.scope);
|
|
2769
|
+
const triggerTimestamp = Date.now();
|
|
2770
|
+
requestManager.addAbortController(abortKey, requestId);
|
|
2771
|
+
const unmountCallbacks = subscribeRequestCallbacks({
|
|
2772
|
+
request,
|
|
2773
|
+
requestId,
|
|
2774
|
+
options
|
|
2775
|
+
});
|
|
2776
|
+
const beforeSentData = {
|
|
2777
|
+
requestId,
|
|
2778
|
+
request
|
|
2779
|
+
};
|
|
2780
|
+
runUserCode(() => options?.onBeforeSent?.(beforeSentData));
|
|
2781
|
+
runUserCode(() => $hooks.__emit("onBeforeSent", beforeSentData));
|
|
2782
|
+
const unlinkSignal = linkAbortSignal(signal, () => requestManager.abortByRequestId(abortKey, requestId));
|
|
2676
2783
|
const response = await adapter.fetch(request, requestId);
|
|
2677
|
-
requestManager.
|
|
2678
|
-
|
|
2784
|
+
const isCanceled = requestManager.isCanceled(abortKey, requestId);
|
|
2785
|
+
unlinkSignal();
|
|
2786
|
+
unmountCallbacks();
|
|
2787
|
+
requestManager.removeAbortController(abortKey, requestId);
|
|
2788
|
+
const mappedResponse = await mapResponseForSend(request, response);
|
|
2789
|
+
const responseData = {
|
|
2790
|
+
requestId,
|
|
2791
|
+
request,
|
|
2792
|
+
response,
|
|
2793
|
+
details: {
|
|
2794
|
+
retries: 0,
|
|
2795
|
+
isCanceled,
|
|
2796
|
+
isOffline: false,
|
|
2797
|
+
willRetry: false,
|
|
2798
|
+
addedTimestamp: triggerTimestamp,
|
|
2799
|
+
triggerTimestamp,
|
|
2800
|
+
requestTimestamp: response.requestTimestamp,
|
|
2801
|
+
responseTimestamp: response.responseTimestamp
|
|
2802
|
+
}
|
|
2803
|
+
};
|
|
2804
|
+
runUserCode(() => options?.onResponse?.(responseData));
|
|
2805
|
+
runUserCode(() => $hooks.__emit("onResponse", responseData));
|
|
2806
|
+
if (request.throwOnError && !mappedResponse.success) throw mappedResponse.error;
|
|
2807
|
+
return mappedResponse;
|
|
2679
2808
|
};
|
|
2680
2809
|
/**
|
|
2681
2810
|
* Method used to perform requests with usage of cache and queues
|
|
@@ -2688,24 +2817,29 @@ var Request = class Request {
|
|
|
2688
2817
|
* ```
|
|
2689
2818
|
*/
|
|
2690
2819
|
send = async (options) => {
|
|
2691
|
-
const { dispatcherType: _dispatcherType, cachePolicy = "network-only", optimistic: _optimistic, ...configuration } = options || {};
|
|
2820
|
+
const { dispatcherType: _dispatcherType, cachePolicy = "network-only", optimistic: _optimistic, signal: _signal, ...configuration } = options || {};
|
|
2692
2821
|
const request = this.clone(configuration);
|
|
2693
2822
|
const sendRequestOptions = options === void 0 ? void 0 : {
|
|
2694
2823
|
...options,
|
|
2695
2824
|
cachePolicy: void 0
|
|
2696
2825
|
};
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
if (
|
|
2826
|
+
const getResponse = async () => {
|
|
2827
|
+
if (cachePolicy === "network-only") return sendRequest(request, sendRequestOptions);
|
|
2828
|
+
const cached = request.read();
|
|
2829
|
+
if (cachePolicy === "cache-first") {
|
|
2830
|
+
if (cached) return mapResponseForSend(request, cached);
|
|
2831
|
+
return sendRequest(request, sendRequestOptions);
|
|
2832
|
+
}
|
|
2833
|
+
if (cached) {
|
|
2834
|
+
const resolved = await mapResponseForSend(request, cached);
|
|
2835
|
+
sendRequest(request, sendRequestOptions);
|
|
2836
|
+
return resolved;
|
|
2837
|
+
}
|
|
2701
2838
|
return sendRequest(request, sendRequestOptions);
|
|
2702
|
-
}
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
return resolved;
|
|
2707
|
-
}
|
|
2708
|
-
return sendRequest(request, sendRequestOptions);
|
|
2839
|
+
};
|
|
2840
|
+
const response = await getResponse();
|
|
2841
|
+
if (request.throwOnError && !response.success) throw response.error;
|
|
2842
|
+
return response;
|
|
2709
2843
|
};
|
|
2710
2844
|
/** Reconstruct a Request instance from a previously serialized JSON representation. */
|
|
2711
2845
|
static fromJSON = (client, json) => {
|
|
@@ -5605,6 +5739,7 @@ var applyObjectDefaults = (request, config) => {
|
|
|
5605
5739
|
if (config.deduplicate !== void 0) result = result.setDeduplicate(config.deduplicate);
|
|
5606
5740
|
if (config.deduplicateTime !== void 0 && config.deduplicateTime !== null) result = result.setDeduplicateTime(config.deduplicateTime);
|
|
5607
5741
|
if (config.structuralSharing !== void 0) result = result.setStructuralSharing(config.structuralSharing);
|
|
5742
|
+
if (config.throwOnError !== void 0) result = result.setThrowOnError(config.throwOnError);
|
|
5608
5743
|
return result;
|
|
5609
5744
|
};
|
|
5610
5745
|
var applyDefaults = (request, context) => {
|
|
@@ -5950,7 +6085,7 @@ var fetchInfinite = async (request, options) => {
|
|
|
5950
6085
|
let param = getInitialPageParam(request, pagination);
|
|
5951
6086
|
for (let index = 0; index < pageCount; index += 1) {
|
|
5952
6087
|
const pageRequest = getPageRequest(request, pagination, param);
|
|
5953
|
-
const response = await pageRequest.exec({});
|
|
6088
|
+
const response = await pageRequest.exec({ throwOnError: false });
|
|
5954
6089
|
result.responses.push(response);
|
|
5955
6090
|
if (!response.success) {
|
|
5956
6091
|
result.error = response.error;
|
|
@@ -5975,6 +6110,6 @@ var fetchInfinite = async (request, options) => {
|
|
|
5975
6110
|
return result;
|
|
5976
6111
|
};
|
|
5977
6112
|
//#endregion
|
|
5978
|
-
export { AbortError, Adapter, AppEvents, AppManager, Cache, Client, DeletedError, Dispatcher, DispatcherMode, EventEmitter, HttpAdapter, HttpMethods, LoggerManager, OptimisticOperation, Plugin, Request, RequestManager, RequestProcessingError, SAFE_HTTP_METHODS, Time, TimeoutError, UnexpectedError, appManagerInitialOptions, applyOptimistic, canRetryRequest, createClient, createConfiguration, createRequestHooks, createSdk, defaultMapper, defaultTimeout, exponentialBackoff, fetchInfinite, getAbortByAbortKey, getAbortByIdKey, getAbortKey, getAdapter, getAdapterBindings, getAdapterHeaders, getAdapterOnError, getAdapterPayload, getAppManagerEvents, getCacheByKey, getCacheData, getCacheEvents, getCacheKey, getCachedPages, getDeleteByKey, getDeleteKey, getDispatcherChangeByKey, getDispatcherChangeKey, getDispatcherDrainedByKey, getDispatcherDrainedKey, getDispatcherEvents, getDispatcherRunningByKey, getDispatcherRunningKey, getDispatcherStatusByKey, getDispatcherStatusKey, getDownloadProgressByIdKey, getDownloadProgressByQueryKey, getDownloadProgressKey, getErrorMessage, getHasNextPage, getHasPreviousPage, getInitialPageParam, getInvalidateByKey, getInvalidateKey, getIsEqualTimestamp, getLoadingByCacheKey, getLoadingByIdKey, getLoadingByQueryKey, getLoadingKey, getNextPageParam, getOptimisticResult, getPageItems, getPageRequest, getPageTotal, getPaginationMode, getPreviousPageParam, getProgressData, getProgressValue, getRemoveByIdKey, getRemoveByQueryKey, getRemoveKey, getRequestDeduplicatedByCacheKey, getRequestDeduplicatedByIdKey, getRequestDeduplicatedByQueryKey, getRequestDeduplicatedKey, getRequestDispatcher, getRequestEta, getRequestKey, getRequestManagerEvents, getRequestStarByQueryKey, getRequestStartByIdKey, getRequestStartKey, getRequestType, getResponseByCacheKey, getResponseByIdKey, getResponseHeaders, getResponseKey, getResponseStartByIdKey, getResponseStartByQueryKey, getResponseStartKey, getRetryByIdKey, getRetryByQueryKey, getRetryKey, getSimpleKey, getTime, getUniqueRequestId, getUploadProgressByIdKey, getUploadProgressByQueryKey, getUploadProgressKey, handleResponse, hasDocument, hasWindow, httpExtra, incrementField, incrementItems, insertItem, interceptRequest, interceptResponse, isNavigatorOnline, isOptimisticMatch, isPlainObject, isStaleOptimisticResponse, logLevelOrder, logger, loggerColors, loggerStyles, mapResponseForSend, mocker, onDocumentEvent, onWindowEvent, optimistic, parseErrorResponse, parseResponse, patchItems, removeItems, replaceEqualDeep, resetOptimisticState, resolveClientMode, resolveQueryParams, runResponseMapper, runUserCode, scopeKey, sendRequest, settleOptimistic, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, throwOutsideLifecycle, updateListField, xhrExtra };
|
|
6113
|
+
export { AbortError, Adapter, AppEvents, AppManager, Cache, Client, DeletedError, Dispatcher, DispatcherMode, EventEmitter, HttpAdapter, HttpMethods, LoggerManager, OptimisticOperation, Plugin, Request, RequestManager, RequestProcessingError, SAFE_HTTP_METHODS, Time, TimeoutError, UnexpectedError, appManagerInitialOptions, applyOptimistic, canRetryRequest, createClient, createConfiguration, createRequestHooks, createSdk, defaultMapper, defaultTimeout, exponentialBackoff, fetchInfinite, getAbortByAbortKey, getAbortByIdKey, getAbortKey, getAbortedResponse, getAdapter, getAdapterBindings, getAdapterHeaders, getAdapterOnError, getAdapterPayload, getAppManagerEvents, getCacheByKey, getCacheData, getCacheEvents, getCacheKey, getCachedPages, getDeleteByKey, getDeleteKey, getDispatcherChangeByKey, getDispatcherChangeKey, getDispatcherDrainedByKey, getDispatcherDrainedKey, getDispatcherEvents, getDispatcherRunningByKey, getDispatcherRunningKey, getDispatcherStatusByKey, getDispatcherStatusKey, getDownloadProgressByIdKey, getDownloadProgressByQueryKey, getDownloadProgressKey, getErrorMessage, getHasNextPage, getHasPreviousPage, getInitialPageParam, getInvalidateByKey, getInvalidateKey, getIsEqualTimestamp, getLoadingByCacheKey, getLoadingByIdKey, getLoadingByQueryKey, getLoadingKey, getNextPageParam, getOptimisticResult, getPageItems, getPageRequest, getPageTotal, getPaginationMode, getPreviousPageParam, getProgressData, getProgressValue, getRemoveByIdKey, getRemoveByQueryKey, getRemoveKey, getRequestDeduplicatedByCacheKey, getRequestDeduplicatedByIdKey, getRequestDeduplicatedByQueryKey, getRequestDeduplicatedKey, getRequestDispatcher, getRequestEta, getRequestKey, getRequestManagerEvents, getRequestStarByQueryKey, getRequestStartByIdKey, getRequestStartKey, getRequestType, getResponseByCacheKey, getResponseByIdKey, getResponseHeaders, getResponseKey, getResponseStartByIdKey, getResponseStartByQueryKey, getResponseStartKey, getRetryByIdKey, getRetryByQueryKey, getRetryKey, getSimpleKey, getTime, getUniqueRequestId, getUploadProgressByIdKey, getUploadProgressByQueryKey, getUploadProgressKey, handleResponse, hasDocument, hasWindow, httpExtra, incrementField, incrementItems, insertItem, interceptRequest, interceptResponse, isNavigatorOnline, isOptimisticMatch, isPlainObject, isStaleOptimisticResponse, linkAbortSignal, logLevelOrder, logger, loggerColors, loggerStyles, mapResponseForSend, mocker, onDocumentEvent, onWindowEvent, optimistic, parseErrorResponse, parseResponse, patchItems, removeItems, replaceEqualDeep, resetOptimisticState, resolveClientMode, resolveQueryParams, runResponseMapper, runUserCode, scopeKey, sendRequest, settleOptimistic, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, subscribeRequestCallbacks, throwOutsideLifecycle, updateListField, xhrExtra };
|
|
5979
6114
|
|
|
5980
6115
|
//# sourceMappingURL=index.mjs.map
|