@hyper-fetch/core 10.4.0 → 10.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/__tests__/features/adapter/adapter.mapping.spec.ts +29 -1
- package/__tests__/features/cache/cache.modes.spec.ts +33 -0
- package/__tests__/features/client/client.configuration.spec.ts +24 -0
- 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/adapter/adapter.d.ts +8 -1
- package/dist/adapter/adapter.d.ts.map +1 -1
- package/dist/adapter/adapter.types.d.ts +7 -8
- package/dist/adapter/adapter.types.d.ts.map +1 -1
- package/dist/client/client.types.d.ts +2 -1
- package/dist/client/client.types.d.ts.map +1 -1
- package/dist/client/client.utils.d.ts +6 -1
- package/dist/client/client.utils.d.ts.map +1 -1
- package/dist/index.mjs +1539 -1389
- 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/adapter/adapter.ts +10 -3
- package/src/adapter/adapter.types.ts +7 -5
- package/src/client/client.types.ts +2 -1
- package/src/client/client.utils.ts +12 -2
- 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,1420 +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 request payload mapping function which gets triggered before request is send
|
|
894
|
-
*/
|
|
895
|
-
setPayloadMapper = (payloadMapper) => {
|
|
896
|
-
this.unstable_payloadMapper = ((req) => payloadMapper(req, this.unstable_payloadMapperConfig));
|
|
897
|
-
return this;
|
|
898
|
-
};
|
|
899
|
-
/**
|
|
900
|
-
* Set the endpoint mapping function which transforms the endpoint string before the request is sent
|
|
901
|
-
*/
|
|
902
|
-
setEndpointMapper = (endpointMapper) => {
|
|
903
|
-
this.unstable_endpointMapper = ((endpoint) => endpointMapper(endpoint, this.unstable_endpointMapperConfig));
|
|
904
|
-
return this;
|
|
905
|
-
};
|
|
906
|
-
/**
|
|
907
|
-
* Set the query params mapping function which get triggered before request get sent
|
|
908
|
-
*/
|
|
909
|
-
setQueryParamsMapper = (queryParamsMapper) => {
|
|
910
|
-
this.unstable_queryParamsMapper = ((queryParams) => queryParamsMapper(queryParams, this.unstable_queryParamsMapperConfig));
|
|
911
|
-
return this;
|
|
912
|
-
};
|
|
913
|
-
/**
|
|
914
|
-
* Let requests take query params as a callback. When a request gets a function as its query params (in
|
|
915
|
-
* `createRequest`, `setQueryParams` or `send`), the resolver runs right away and the request stores what it returns,
|
|
916
|
-
* so cache keys, query keys and `toJSON()` only ever see data. The resolver decides what the callback receives.
|
|
917
|
-
*
|
|
918
|
-
* Opt-in: adapters without a resolver store query params as given. Declare the callback in the adapter's query params
|
|
919
|
-
* type so requests accept it.
|
|
920
|
-
*
|
|
921
|
-
* @example
|
|
922
|
-
* // The Firebase adapter passes a constraints builder and stores the constraints it collected
|
|
923
|
-
* adapter.setQueryParamsResolver((callback) => callback(createConstraints()).toJSON());
|
|
924
|
-
*/
|
|
925
|
-
setQueryParamsResolver = (resolver) => {
|
|
926
|
-
this.unstable_queryParamsResolver = resolver;
|
|
927
|
-
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;
|
|
928
787
|
};
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
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;
|
|
933
797
|
};
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
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;
|
|
938
806
|
};
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
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;
|
|
943
820
|
};
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
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;
|
|
948
830
|
};
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
setFetcher(fetcher) {
|
|
956
|
-
this.unstable_fetcher = fetcher.bind(this);
|
|
957
|
-
return this;
|
|
958
|
-
}
|
|
959
|
-
/** Execute a request through the adapter pipeline: maps endpoint/headers/payload, runs plugins, then calls the fetcher. */
|
|
960
|
-
async fetch(request, requestId) {
|
|
961
|
-
let startTime;
|
|
962
|
-
const execute = async (resolve) => {
|
|
963
|
-
try {
|
|
964
|
-
if (!this.initialized) throw new RequestProcessingError(`Adapter ${this.options.name} is not initialized`);
|
|
965
|
-
if (!this.unstable_fetcher) throw new RequestProcessingError(`Fetcher for ${this.options.name} adapter is not set`);
|
|
966
|
-
this.client.triggerPlugins("onAdapterFetch", {
|
|
967
|
-
adapter: this,
|
|
968
|
-
request,
|
|
969
|
-
requestId
|
|
970
|
-
});
|
|
971
|
-
const bindings = await getAdapterBindings({
|
|
972
|
-
request,
|
|
973
|
-
requestId,
|
|
974
|
-
resolve,
|
|
975
|
-
internalErrorMapping: this.unstable_internalErrorMapping,
|
|
976
|
-
onStartTime: (time) => {
|
|
977
|
-
startTime = time;
|
|
978
|
-
}
|
|
979
|
-
});
|
|
980
|
-
if (request.unstable_mock && request.isMockerEnabled && request.client.isMockerEnabled) return await mocker(bindings);
|
|
981
|
-
return await this.unstable_fetcher(bindings);
|
|
982
|
-
} catch (error) {
|
|
983
|
-
return getAdapterOnError({
|
|
984
|
-
request,
|
|
985
|
-
requestId,
|
|
986
|
-
startTime: startTime || Date.now(),
|
|
987
|
-
logger: this.logger,
|
|
988
|
-
resolve
|
|
989
|
-
})({
|
|
990
|
-
error: this.unstable_internalErrorMapping(error),
|
|
991
|
-
status: this.options.systemErrorStatus,
|
|
992
|
-
extra: this.options.systemErrorExtra
|
|
993
|
-
});
|
|
994
|
-
}
|
|
995
|
-
};
|
|
996
|
-
return new Promise((resolve) => {
|
|
997
|
-
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
|
|
998
837
|
});
|
|
999
|
-
|
|
1000
|
-
};
|
|
1001
|
-
//#endregion
|
|
1002
|
-
//#region src/constants/http.constants.ts
|
|
1003
|
-
var HttpMethods = /* @__PURE__ */ function(HttpMethods) {
|
|
1004
|
-
HttpMethods["GET"] = "GET";
|
|
1005
|
-
HttpMethods["POST"] = "POST";
|
|
1006
|
-
HttpMethods["PUT"] = "PUT";
|
|
1007
|
-
HttpMethods["PATCH"] = "PATCH";
|
|
1008
|
-
HttpMethods["DELETE"] = "DELETE";
|
|
1009
|
-
/** Safe, idempotent read with a request body (IETF draft-ietf-httpbis-safe-method-w-body). */
|
|
1010
|
-
HttpMethods["QUERY"] = "QUERY";
|
|
1011
|
-
return HttpMethods;
|
|
1012
|
-
}({});
|
|
1013
|
-
/** Methods that are safe reads: routed to the fetch dispatcher and deduplicated by default. */
|
|
1014
|
-
var SAFE_HTTP_METHODS = [HttpMethods.GET, HttpMethods.QUERY];
|
|
1015
|
-
//#endregion
|
|
1016
|
-
//#region src/optimistic/optimistic.utils.ts
|
|
1017
|
-
var isComparableId = (value) => typeof value === "string" || typeof value === "number";
|
|
1018
|
-
/**
|
|
1019
|
-
* Tells if the item is selected by the match. Plain values are compared with the `key` field of the item, numbers and
|
|
1020
|
-
* strings match each other the same way route params do (`"1"` matches `1`).
|
|
1021
|
-
*/
|
|
1022
|
-
var isOptimisticMatch = (item, match, key = "id") => {
|
|
1023
|
-
if (typeof match === "function") return !!match(item);
|
|
1024
|
-
if (item === null || typeof item !== "object") return false;
|
|
1025
|
-
const value = item[key];
|
|
1026
|
-
if (Object.is(value, match)) return true;
|
|
1027
|
-
return isComparableId(value) && isComparableId(match) && String(value) === String(match);
|
|
1028
|
-
};
|
|
1029
|
-
var assertList = (list) => {
|
|
1030
|
-
if (!Array.isArray(list)) throw new TypeError("Optimistic list helpers need an array, use .list(field) for an array inside an object");
|
|
1031
|
-
return list;
|
|
1032
|
-
};
|
|
1033
|
-
var assertEntry = (data) => {
|
|
1034
|
-
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");
|
|
1035
|
-
return data;
|
|
1036
|
-
};
|
|
1037
|
-
var addToField = (item, field, by) => {
|
|
1038
|
-
const value = item[field];
|
|
1039
|
-
return {
|
|
1040
|
-
...item,
|
|
1041
|
-
[field]: (typeof value === "number" ? value : 0) + by
|
|
838
|
+
return progressTimestamp;
|
|
1042
839
|
};
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
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
|
-
var updateListField = (data, field, update) => {
|
|
1088
|
-
const entry = assertEntry(data);
|
|
1089
|
-
const list = entry[field] ?? [];
|
|
1090
|
-
const next = update(assertList(list));
|
|
1091
|
-
return next === list ? entry : {
|
|
1092
|
-
...entry,
|
|
1093
|
-
[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;
|
|
1094
883
|
};
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
/** @internal */
|
|
1111
|
-
onRollback = void 0;
|
|
1112
|
-
/** @internal */
|
|
1113
|
-
onCommit = void 0;
|
|
1114
|
-
constructor(options) {
|
|
1115
|
-
this.target = options.target;
|
|
1116
|
-
this.allVariants = options.allVariants;
|
|
1117
|
-
this.update = options.update;
|
|
1118
|
-
this.onRollback = options.onRollback;
|
|
1119
|
-
this.onCommit = options.onCommit;
|
|
1120
|
-
}
|
|
1121
|
-
/**
|
|
1122
|
-
* Undo of this change, written by hand and run by core when the mutation fails for good, is aborted or removed from
|
|
1123
|
-
* the queue. Rollbacks of one mutation run in reverse order of the changes. It receives
|
|
1124
|
-
* `{ data, previous, reason, response, request }` and returns the new data; returning nothing leaves the data as it
|
|
1125
|
-
* is. Build the result from `data` and use `previous` only to look old values up. Must be synchronous.
|
|
1126
|
-
* Without it nothing is undone locally and the target is refetched.
|
|
1127
|
-
*/
|
|
1128
|
-
rollback(callback) {
|
|
1129
|
-
return new OptimisticOperation({
|
|
1130
|
-
target: this.target,
|
|
1131
|
-
allVariants: this.allVariants,
|
|
1132
|
-
update: this.update,
|
|
1133
|
-
onRollback: callback,
|
|
1134
|
-
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
|
+
}
|
|
1135
899
|
});
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
* the data as it is. Must be synchronous.
|
|
1141
|
-
*/
|
|
1142
|
-
commit(callback) {
|
|
1143
|
-
return new OptimisticOperation({
|
|
1144
|
-
target: this.target,
|
|
1145
|
-
allVariants: this.allVariants,
|
|
1146
|
-
update: this.update,
|
|
1147
|
-
onRollback: this.onRollback,
|
|
1148
|
-
onCommit: callback
|
|
900
|
+
return onError({
|
|
901
|
+
error: internalErrorMapping(getErrorMessage("abort")),
|
|
902
|
+
status,
|
|
903
|
+
extra
|
|
1149
904
|
});
|
|
1150
|
-
}
|
|
1151
|
-
}
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
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
|
|
1158
919
|
});
|
|
1159
920
|
};
|
|
1160
|
-
const
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
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
|
|
1184
965
|
}
|
|
1185
966
|
});
|
|
1186
|
-
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;
|
|
1187
971
|
return {
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
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
|
+
};
|
|
1200
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;
|
|
1201
1041
|
};
|
|
1202
|
-
}
|
|
1203
|
-
var optimisticFactory = (target) => createTarget(target, false);
|
|
1204
|
-
optimisticFactory.all = (target) => createTarget(target, true);
|
|
1205
|
-
/**
|
|
1206
|
-
* Describes an optimistic change of a cached request. Return the operations from `setOptimistic` or pass them with the
|
|
1207
|
-
* `optimistic` send option, core applies them, runs `.commit()` / `.rollback()` when the mutation settles and refreshes
|
|
1208
|
-
* the targets once the last pending mutation on them is done.
|
|
1209
|
-
*
|
|
1210
|
-
* - `optimistic(getTodos)` - the entry of this request (its params and query params)
|
|
1211
|
-
* - `optimistic.all(getTodos)` - every cached variant of it, whatever the query params (filters, infinite pages)
|
|
1212
|
-
*
|
|
1213
|
-
* Helpers: `set(updater)`, `patch(match, fields)`, `insert(item, { at })`, `remove(match)`,
|
|
1214
|
-
* `increment(field, by)` / `increment(match, field, by)` and `.list("field")` for an array inside an object.
|
|
1215
|
-
*
|
|
1216
|
-
* @example
|
|
1217
|
-
* optimistic(getTodos)
|
|
1218
|
-
* .patch(params.todoId, payload)
|
|
1219
|
-
* .rollback(({ data, previous }) => {
|
|
1220
|
-
* const before = previous.find((todo) => todo.id === params.todoId);
|
|
1221
|
-
* return data.map((todo) => (todo.id === params.todoId && before ? before : todo));
|
|
1222
|
-
* });
|
|
1223
|
-
*/
|
|
1224
|
-
var optimistic = optimisticFactory;
|
|
1042
|
+
}
|
|
1225
1043
|
//#endregion
|
|
1226
|
-
//#region src/
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
}
|
|
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
|
+
}
|
|
1238
1092
|
};
|
|
1239
1093
|
/**
|
|
1240
|
-
*
|
|
1241
|
-
* and
|
|
1242
|
-
* @internal
|
|
1243
|
-
* @param callback code of the user to run
|
|
1244
|
-
* @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)
|
|
1245
1096
|
*/
|
|
1246
|
-
var
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
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;
|
|
1253
1107
|
}
|
|
1108
|
+
if (Array.isArray(headers)) return headers;
|
|
1109
|
+
return Object.entries(headers);
|
|
1254
1110
|
};
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
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);
|
|
1259
1125
|
};
|
|
1260
1126
|
//#endregion
|
|
1261
|
-
//#region src/
|
|
1262
|
-
var
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
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;
|
|
1277
1169
|
}
|
|
1278
|
-
|
|
1279
|
-
|
|
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;
|
|
1280
1177
|
};
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
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;
|
|
1310
1220
|
};
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
this.
|
|
1221
|
+
/** Set the default extra metadata attached to every request response (e.g., headers, status). */
|
|
1222
|
+
setDefaultExtra = (extra) => {
|
|
1223
|
+
this.defaultExtra = extra;
|
|
1314
1224
|
return this;
|
|
1315
1225
|
};
|
|
1316
|
-
function
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
|
|
1321
|
-
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;
|
|
1322
1230
|
};
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
else if (!doError) return false;
|
|
1330
|
-
if (doError) {
|
|
1331
|
-
var er;
|
|
1332
|
-
if (args.length > 0) er = args[0];
|
|
1333
|
-
if (er instanceof Error) throw er;
|
|
1334
|
-
var err = /* @__PURE__ */ new Error("Unhandled error." + (er ? " (" + er.message + ")" : ""));
|
|
1335
|
-
err.context = er;
|
|
1336
|
-
throw err;
|
|
1337
|
-
}
|
|
1338
|
-
var handler = events[type];
|
|
1339
|
-
if (handler === void 0) return false;
|
|
1340
|
-
if (typeof handler === "function") ReflectApply(handler, this, args);
|
|
1341
|
-
else {
|
|
1342
|
-
var len = handler.length;
|
|
1343
|
-
var listeners = arrayClone(handler, len);
|
|
1344
|
-
for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args);
|
|
1345
|
-
}
|
|
1346
|
-
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;
|
|
1347
1237
|
};
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
if (events === void 0) {
|
|
1355
|
-
events = target._events = Object.create(null);
|
|
1356
|
-
target._eventsCount = 0;
|
|
1357
|
-
} else {
|
|
1358
|
-
if (events.newListener !== void 0) {
|
|
1359
|
-
target.emit("newListener", type, listener.listener ? listener.listener : listener);
|
|
1360
|
-
events = target._events;
|
|
1361
|
-
}
|
|
1362
|
-
existing = events[type];
|
|
1363
|
-
}
|
|
1364
|
-
if (existing === void 0) {
|
|
1365
|
-
existing = events[type] = listener;
|
|
1366
|
-
++target._eventsCount;
|
|
1367
|
-
} else {
|
|
1368
|
-
if (typeof existing === "function") existing = events[type] = prepend ? [listener, existing] : [existing, listener];
|
|
1369
|
-
else if (prepend) existing.unshift(listener);
|
|
1370
|
-
else existing.push(listener);
|
|
1371
|
-
m = _getMaxListeners(target);
|
|
1372
|
-
if (m > 0 && existing.length > m && !existing.warned) {
|
|
1373
|
-
existing.warned = true;
|
|
1374
|
-
var w = /* @__PURE__ */ new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit");
|
|
1375
|
-
w.name = "MaxListenersExceededWarning";
|
|
1376
|
-
w.emitter = target;
|
|
1377
|
-
w.type = type;
|
|
1378
|
-
w.count = existing.length;
|
|
1379
|
-
ProcessEmitWarning(w);
|
|
1380
|
-
}
|
|
1381
|
-
}
|
|
1382
|
-
return target;
|
|
1383
|
-
}
|
|
1384
|
-
EventEmitter.prototype.addListener = function addListener(type, listener) {
|
|
1385
|
-
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;
|
|
1386
1244
|
};
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
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;
|
|
1390
1249
|
};
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
return this.listener.apply(this.target, arguments);
|
|
1397
|
-
}
|
|
1398
|
-
}
|
|
1399
|
-
function _onceWrap(target, type, listener) {
|
|
1400
|
-
var state = {
|
|
1401
|
-
fired: false,
|
|
1402
|
-
wrapFn: void 0,
|
|
1403
|
-
target,
|
|
1404
|
-
type,
|
|
1405
|
-
listener
|
|
1406
|
-
};
|
|
1407
|
-
var wrapped = onceWrapper.bind(state);
|
|
1408
|
-
wrapped.listener = listener;
|
|
1409
|
-
state.wrapFn = wrapped;
|
|
1410
|
-
return wrapped;
|
|
1411
|
-
}
|
|
1412
|
-
EventEmitter.prototype.once = function once(type, listener) {
|
|
1413
|
-
checkListener(listener);
|
|
1414
|
-
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));
|
|
1415
1255
|
return this;
|
|
1416
1256
|
};
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
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));
|
|
1420
1269
|
return this;
|
|
1421
1270
|
};
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
list = events[type];
|
|
1428
|
-
if (list === void 0) return this;
|
|
1429
|
-
if (list === listener || list.listener === listener) if (--this._eventsCount === 0) this._events = Object.create(null);
|
|
1430
|
-
else {
|
|
1431
|
-
delete events[type];
|
|
1432
|
-
if (events.removeListener) this.emit("removeListener", type, list.listener || listener);
|
|
1433
|
-
}
|
|
1434
|
-
else if (typeof list !== "function") {
|
|
1435
|
-
position = -1;
|
|
1436
|
-
for (i = list.length - 1; i >= 0; i--) if (list[i] === listener || list[i].listener === listener) {
|
|
1437
|
-
originalListener = list[i].listener;
|
|
1438
|
-
position = i;
|
|
1439
|
-
break;
|
|
1440
|
-
}
|
|
1441
|
-
if (position < 0) return this;
|
|
1442
|
-
if (position === 0) list.shift();
|
|
1443
|
-
else spliceOne(list, position);
|
|
1444
|
-
if (list.length === 1) events[type] = list[0];
|
|
1445
|
-
if (events.removeListener !== void 0) this.emit("removeListener", type, originalListener || listener);
|
|
1446
|
-
}
|
|
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));
|
|
1447
1276
|
return this;
|
|
1448
1277
|
};
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
if (arguments.length === 0) {
|
|
1455
|
-
this._events = Object.create(null);
|
|
1456
|
-
this._eventsCount = 0;
|
|
1457
|
-
} else if (events[type] !== void 0) if (--this._eventsCount === 0) this._events = Object.create(null);
|
|
1458
|
-
else delete events[type];
|
|
1459
|
-
return this;
|
|
1460
|
-
}
|
|
1461
|
-
if (arguments.length === 0) {
|
|
1462
|
-
var keys = Object.keys(events);
|
|
1463
|
-
var key;
|
|
1464
|
-
for (i = 0; i < keys.length; ++i) {
|
|
1465
|
-
key = keys[i];
|
|
1466
|
-
if (key === "removeListener") continue;
|
|
1467
|
-
this.removeAllListeners(key);
|
|
1468
|
-
}
|
|
1469
|
-
this.removeAllListeners("removeListener");
|
|
1470
|
-
this._events = Object.create(null);
|
|
1471
|
-
this._eventsCount = 0;
|
|
1472
|
-
return this;
|
|
1473
|
-
}
|
|
1474
|
-
listeners = events[type];
|
|
1475
|
-
if (typeof listeners === "function") this.removeListener(type, listeners);
|
|
1476
|
-
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));
|
|
1477
1283
|
return this;
|
|
1478
1284
|
};
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
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;
|
|
1489
1300
|
};
|
|
1490
|
-
|
|
1491
|
-
|
|
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;
|
|
1305
|
+
};
|
|
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;
|
|
1492
1310
|
};
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
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;
|
|
1496
1315
|
};
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
var evlistener = events[type];
|
|
1502
|
-
if (typeof evlistener === "function") return 1;
|
|
1503
|
-
else if (evlistener !== void 0) return evlistener.length;
|
|
1504
|
-
}
|
|
1505
|
-
return 0;
|
|
1506
|
-
}
|
|
1507
|
-
EventEmitter.prototype.eventNames = function eventNames() {
|
|
1508
|
-
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
|
|
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;
|
|
1509
1320
|
};
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
function
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
function unwrapListeners(arr) {
|
|
1520
|
-
var ret = new Array(arr.length);
|
|
1521
|
-
for (var i = 0; i < ret.length; ++i) ret[i] = arr[i].listener || arr[i];
|
|
1522
|
-
return ret;
|
|
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;
|
|
1523
1330
|
}
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
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
|
+
});
|
|
1533
1366
|
}
|
|
1534
|
-
|
|
1535
|
-
|
|
1367
|
+
};
|
|
1368
|
+
return new Promise((resolve) => {
|
|
1369
|
+
execute(resolve);
|
|
1536
1370
|
});
|
|
1537
1371
|
}
|
|
1538
|
-
|
|
1539
|
-
|
|
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;
|
|
1540
1492
|
}
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
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
|
|
1547
1507
|
});
|
|
1548
|
-
else throw new TypeError("The \"emitter\" argument must be of type EventEmitter. Received type " + typeof emitter);
|
|
1549
|
-
}
|
|
1550
|
-
})))());
|
|
1551
|
-
var getListenName = (event) => `listen_${String(event)}`;
|
|
1552
|
-
var EventEmitter = class extends import_events.default {
|
|
1553
|
-
emitCallbacks = [];
|
|
1554
|
-
constructor(options) {
|
|
1555
|
-
super(options);
|
|
1556
1508
|
}
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
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
|
+
});
|
|
1564
1522
|
}
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
return () => {
|
|
1574
|
-
super.off(getListenName(event), listener);
|
|
1575
|
-
};
|
|
1576
|
-
};
|
|
1577
|
-
on = (event, listener) => {
|
|
1578
|
-
super.on(event, listener);
|
|
1579
|
-
super.emit(getListenName(event), super.listeners(event).length);
|
|
1580
|
-
return this;
|
|
1523
|
+
};
|
|
1524
|
+
var createTarget = (target, allVariants) => {
|
|
1525
|
+
const operation = (update) => {
|
|
1526
|
+
return new OptimisticOperation({
|
|
1527
|
+
target,
|
|
1528
|
+
allVariants,
|
|
1529
|
+
update
|
|
1530
|
+
});
|
|
1581
1531
|
};
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
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
|
+
}
|
|
1586
1573
|
};
|
|
1587
|
-
addListener = this.on;
|
|
1588
|
-
removeListener = this.off;
|
|
1589
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;
|
|
1590
1597
|
//#endregion
|
|
1591
1598
|
//#region src/optimistic/optimistic.settlement.ts
|
|
1592
1599
|
var clientStates = /* @__PURE__ */ new WeakMap();
|
|
@@ -2003,10 +2010,90 @@ var mapResponseForSend = async (request, response) => {
|
|
|
2003
2010
|
if (mapping instanceof Promise) return await mapping;
|
|
2004
2011
|
return mapping || response;
|
|
2005
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
|
+
};
|
|
2006
2091
|
var sendRequest = async (request, options) => {
|
|
2007
2092
|
const { client } = request;
|
|
2008
2093
|
const { requestManager } = client;
|
|
2009
2094
|
const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);
|
|
2095
|
+
const signal = options?.signal;
|
|
2096
|
+
if (signal?.aborted) return getAbortedResponse(request);
|
|
2010
2097
|
let mutationContext;
|
|
2011
2098
|
let pendingOptimistic;
|
|
2012
2099
|
const optimisticSource = options?.optimistic ?? request.optimistic;
|
|
@@ -2038,8 +2125,12 @@ var sendRequest = async (request, options) => {
|
|
|
2038
2125
|
let isResolved = false;
|
|
2039
2126
|
let isDelivered = false;
|
|
2040
2127
|
let isSettled = false;
|
|
2041
|
-
const requestId = dispatcher.add(request);
|
|
2042
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 = () => {};
|
|
2043
2134
|
const { $hooks } = request;
|
|
2044
2135
|
const getWillBeResent = ({ response, details }) => {
|
|
2045
2136
|
if (response.success || details.isCanceled) return false;
|
|
@@ -2086,45 +2177,11 @@ var sendRequest = async (request, options) => {
|
|
|
2086
2177
|
};
|
|
2087
2178
|
runUserCode(() => options?.onBeforeSent?.(beforeSentData));
|
|
2088
2179
|
runUserCode(() => $hooks.__emit("onBeforeSent", beforeSentData));
|
|
2089
|
-
const
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
runUserCode(() => options?.onRequestStart?.(enriched));
|
|
2095
|
-
runUserCode(() => $hooks.__emit("onRequestStart", enriched));
|
|
2096
|
-
});
|
|
2097
|
-
const unmountResponseStart = requestManager.events.onResponseStartById(requestId, (data) => {
|
|
2098
|
-
const enriched = {
|
|
2099
|
-
...data,
|
|
2100
|
-
mutationContext
|
|
2101
|
-
};
|
|
2102
|
-
runUserCode(() => options?.onResponseStart?.(enriched));
|
|
2103
|
-
runUserCode(() => $hooks.__emit("onResponseStart", enriched));
|
|
2104
|
-
});
|
|
2105
|
-
const unmountUpload = requestManager.events.onUploadProgressById(requestId, (data) => {
|
|
2106
|
-
const enriched = {
|
|
2107
|
-
...data,
|
|
2108
|
-
mutationContext
|
|
2109
|
-
};
|
|
2110
|
-
runUserCode(() => options?.onUploadProgress?.(enriched));
|
|
2111
|
-
runUserCode(() => $hooks.__emit("onUploadProgress", enriched));
|
|
2112
|
-
});
|
|
2113
|
-
const unmountDownload = requestManager.events.onDownloadProgressById(requestId, (data) => {
|
|
2114
|
-
const enriched = {
|
|
2115
|
-
...data,
|
|
2116
|
-
mutationContext
|
|
2117
|
-
};
|
|
2118
|
-
runUserCode(() => options?.onDownloadProgress?.(enriched));
|
|
2119
|
-
runUserCode(() => $hooks.__emit("onDownloadProgress", enriched));
|
|
2120
|
-
});
|
|
2121
|
-
const unmountRetry = requestManager.events.onRetryById(requestId, (data) => {
|
|
2122
|
-
const enriched = {
|
|
2123
|
-
...data,
|
|
2124
|
-
mutationContext
|
|
2125
|
-
};
|
|
2126
|
-
runUserCode(() => options?.onRetry?.(enriched));
|
|
2127
|
-
runUserCode(() => $hooks.__emit("onRetry", enriched));
|
|
2180
|
+
const unmountCallbacks = subscribeRequestCallbacks({
|
|
2181
|
+
request,
|
|
2182
|
+
requestId,
|
|
2183
|
+
options,
|
|
2184
|
+
mutationContext
|
|
2128
2185
|
});
|
|
2129
2186
|
const unmountResponse = requestManager.events.onResponseById(requestId, (values) => {
|
|
2130
2187
|
const { response } = values;
|
|
@@ -2158,9 +2215,23 @@ var sendRequest = async (request, options) => {
|
|
|
2158
2215
|
if (!isResolved) {
|
|
2159
2216
|
isResolved = true;
|
|
2160
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
|
+
};
|
|
2161
2227
|
if (pendingOptimistic && !isSettled) {
|
|
2162
2228
|
isSettled = true;
|
|
2163
|
-
settleOptimistic(pendingOptimistic, {
|
|
2229
|
+
settleOptimistic(pendingOptimistic, isRemovedBySignal ? {
|
|
2230
|
+
type: "rollback",
|
|
2231
|
+
reason: "abort",
|
|
2232
|
+
response: removedResponse,
|
|
2233
|
+
request
|
|
2234
|
+
} : {
|
|
2164
2235
|
type: "rollback",
|
|
2165
2236
|
reason: "removed",
|
|
2166
2237
|
request
|
|
@@ -2172,27 +2243,43 @@ var sendRequest = async (request, options) => {
|
|
|
2172
2243
|
};
|
|
2173
2244
|
runUserCode(() => options?.onRemove?.(enriched));
|
|
2174
2245
|
runUserCode(() => $hooks.__emit("onRemove", enriched));
|
|
2175
|
-
resolve(
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
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);
|
|
2184
2266
|
umountAll();
|
|
2267
|
+
return;
|
|
2268
|
+
}
|
|
2269
|
+
const abortKey = scopeKey(request.abortKey, request.scope);
|
|
2270
|
+
if (dispatcher.hasRunningRequest(queryKey, requestId)) {
|
|
2271
|
+
requestManager.abortByRequestId(abortKey, requestId);
|
|
2272
|
+
return;
|
|
2185
2273
|
}
|
|
2274
|
+
isRemovedBySignal = true;
|
|
2275
|
+
dispatcher.delete(queryKey, requestId, abortKey);
|
|
2186
2276
|
});
|
|
2187
2277
|
function umountAll() {
|
|
2188
2278
|
unmountSettlement?.();
|
|
2189
|
-
|
|
2190
|
-
unmountResponseStart();
|
|
2191
|
-
unmountUpload();
|
|
2192
|
-
unmountDownload();
|
|
2193
|
-
unmountRetry();
|
|
2279
|
+
unmountCallbacks();
|
|
2194
2280
|
unmountResponse();
|
|
2195
2281
|
unmountRemoveQueueElement();
|
|
2282
|
+
unlinkSignal();
|
|
2196
2283
|
}
|
|
2197
2284
|
});
|
|
2198
2285
|
};
|
|
@@ -2258,6 +2345,7 @@ var Request = class Request {
|
|
|
2258
2345
|
deduplicate;
|
|
2259
2346
|
deduplicateTime;
|
|
2260
2347
|
structuralSharing;
|
|
2348
|
+
throwOnError;
|
|
2261
2349
|
scope;
|
|
2262
2350
|
/**
|
|
2263
2351
|
* Instance-level lifecycle hooks. These callbacks fire for every `send()` / `exec()` call
|
|
@@ -2299,7 +2387,7 @@ var Request = class Request {
|
|
|
2299
2387
|
this.client = client;
|
|
2300
2388
|
this.requestOptions = requestOptions;
|
|
2301
2389
|
this.initialRequestConfiguration = initialRequestConfiguration;
|
|
2302
|
-
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 } = {
|
|
2303
2391
|
...this.client.adapter.unstable_getRequestDefaults?.(requestOptions),
|
|
2304
2392
|
...requestOptions
|
|
2305
2393
|
};
|
|
@@ -2326,6 +2414,7 @@ var Request = class Request {
|
|
|
2326
2414
|
this.deduplicate = initialRequestConfiguration?.deduplicate ?? deduplicate;
|
|
2327
2415
|
this.deduplicateTime = initialRequestConfiguration?.deduplicateTime ?? deduplicateTime;
|
|
2328
2416
|
this.structuralSharing = initialRequestConfiguration?.structuralSharing ?? structuralSharing;
|
|
2417
|
+
this.throwOnError = initialRequestConfiguration?.throwOnError ?? throwOnError;
|
|
2329
2418
|
this.scope = initialRequestConfiguration?.scope ?? null;
|
|
2330
2419
|
this.updatedAbortKey = initialRequestConfiguration?.updatedAbortKey ?? false;
|
|
2331
2420
|
this.updatedCacheKey = initialRequestConfiguration?.updatedCacheKey ?? false;
|
|
@@ -2457,6 +2546,13 @@ var Request = class Request {
|
|
|
2457
2546
|
setStructuralSharing = (structuralSharing) => {
|
|
2458
2547
|
return this.clone({ structuralSharing });
|
|
2459
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
|
+
};
|
|
2460
2556
|
/** Mark the request as used (prevents automatic refetching in hooks). */
|
|
2461
2557
|
setUsed = (used) => {
|
|
2462
2558
|
return this.clone({ used });
|
|
@@ -2558,6 +2654,7 @@ var Request = class Request {
|
|
|
2558
2654
|
deduplicate: this.deduplicate,
|
|
2559
2655
|
deduplicateTime: this.deduplicateTime,
|
|
2560
2656
|
structuralSharing: this.structuralSharing,
|
|
2657
|
+
throwOnError: this.throwOnError,
|
|
2561
2658
|
scope: this.scope,
|
|
2562
2659
|
isMockerEnabled: this.isMockerEnabled,
|
|
2563
2660
|
hasMock: !!this.unstable_mock
|
|
@@ -2652,23 +2749,62 @@ var Request = class Request {
|
|
|
2652
2749
|
};
|
|
2653
2750
|
}
|
|
2654
2751
|
/**
|
|
2655
|
-
*
|
|
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`.
|
|
2656
2755
|
* @param options
|
|
2657
2756
|
* @disableReturns
|
|
2658
2757
|
* @returns
|
|
2659
2758
|
* ```tsx
|
|
2660
|
-
* Promise<
|
|
2759
|
+
* Promise<{ data: Data | null, error: Error | null, status: HttpStatus, ... }>
|
|
2661
2760
|
* ```
|
|
2662
2761
|
*/
|
|
2663
2762
|
exec = async (options) => {
|
|
2763
|
+
const { signal, ...configuration } = options || {};
|
|
2664
2764
|
const { adapter, requestManager } = this.client;
|
|
2665
|
-
const request = this.clone(
|
|
2765
|
+
const request = this.clone(configuration);
|
|
2766
|
+
const { $hooks } = request;
|
|
2666
2767
|
const requestId = this.client.unstable_requestIdMapper(this);
|
|
2667
|
-
const
|
|
2668
|
-
|
|
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));
|
|
2669
2783
|
const response = await adapter.fetch(request, requestId);
|
|
2670
|
-
requestManager.
|
|
2671
|
-
|
|
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;
|
|
2672
2808
|
};
|
|
2673
2809
|
/**
|
|
2674
2810
|
* Method used to perform requests with usage of cache and queues
|
|
@@ -2681,24 +2817,29 @@ var Request = class Request {
|
|
|
2681
2817
|
* ```
|
|
2682
2818
|
*/
|
|
2683
2819
|
send = async (options) => {
|
|
2684
|
-
const { dispatcherType: _dispatcherType, cachePolicy = "network-only", optimistic: _optimistic, ...configuration } = options || {};
|
|
2820
|
+
const { dispatcherType: _dispatcherType, cachePolicy = "network-only", optimistic: _optimistic, signal: _signal, ...configuration } = options || {};
|
|
2685
2821
|
const request = this.clone(configuration);
|
|
2686
2822
|
const sendRequestOptions = options === void 0 ? void 0 : {
|
|
2687
2823
|
...options,
|
|
2688
2824
|
cachePolicy: void 0
|
|
2689
2825
|
};
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
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
|
+
}
|
|
2694
2838
|
return sendRequest(request, sendRequestOptions);
|
|
2695
|
-
}
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
return resolved;
|
|
2700
|
-
}
|
|
2701
|
-
return sendRequest(request, sendRequestOptions);
|
|
2839
|
+
};
|
|
2840
|
+
const response = await getResponse();
|
|
2841
|
+
if (request.throwOnError && !response.success) throw response.error;
|
|
2842
|
+
return response;
|
|
2702
2843
|
};
|
|
2703
2844
|
/** Reconstruct a Request instance from a previously serialized JSON representation. */
|
|
2704
2845
|
static fromJSON = (client, json) => {
|
|
@@ -5108,10 +5249,18 @@ var loggerColors = {
|
|
|
5108
5249
|
};
|
|
5109
5250
|
//#endregion
|
|
5110
5251
|
//#region src/client/client.utils.ts
|
|
5111
|
-
/**
|
|
5252
|
+
/**
|
|
5253
|
+
* Picks effective {@link ClientMode}: explicit override, else environment detection.
|
|
5254
|
+
*
|
|
5255
|
+
* Auto mode picks `"client"` in runtimes that serve one user: a browser, React Native and every Electron process.
|
|
5256
|
+
* Anything else, like Node.js, Deno, Bun or an edge runtime, may serve many users and gets `"server"`.
|
|
5257
|
+
*/
|
|
5112
5258
|
function resolveClientMode(modeOption) {
|
|
5113
5259
|
if (modeOption === "client" || modeOption === "server") return modeOption;
|
|
5114
|
-
|
|
5260
|
+
const inBrowser = typeof window !== "undefined" && typeof document !== "undefined";
|
|
5261
|
+
const inReactNative = typeof navigator !== "undefined" && navigator.product === "ReactNative";
|
|
5262
|
+
const inElectron = typeof process !== "undefined" && !!process.versions?.electron;
|
|
5263
|
+
if (inBrowser || inReactNative || inElectron) return "client";
|
|
5115
5264
|
return "server";
|
|
5116
5265
|
}
|
|
5117
5266
|
var interceptRequest = async (interceptors, request) => {
|
|
@@ -5590,6 +5739,7 @@ var applyObjectDefaults = (request, config) => {
|
|
|
5590
5739
|
if (config.deduplicate !== void 0) result = result.setDeduplicate(config.deduplicate);
|
|
5591
5740
|
if (config.deduplicateTime !== void 0 && config.deduplicateTime !== null) result = result.setDeduplicateTime(config.deduplicateTime);
|
|
5592
5741
|
if (config.structuralSharing !== void 0) result = result.setStructuralSharing(config.structuralSharing);
|
|
5742
|
+
if (config.throwOnError !== void 0) result = result.setThrowOnError(config.throwOnError);
|
|
5593
5743
|
return result;
|
|
5594
5744
|
};
|
|
5595
5745
|
var applyDefaults = (request, context) => {
|
|
@@ -5935,7 +6085,7 @@ var fetchInfinite = async (request, options) => {
|
|
|
5935
6085
|
let param = getInitialPageParam(request, pagination);
|
|
5936
6086
|
for (let index = 0; index < pageCount; index += 1) {
|
|
5937
6087
|
const pageRequest = getPageRequest(request, pagination, param);
|
|
5938
|
-
const response = await pageRequest.exec({});
|
|
6088
|
+
const response = await pageRequest.exec({ throwOnError: false });
|
|
5939
6089
|
result.responses.push(response);
|
|
5940
6090
|
if (!response.success) {
|
|
5941
6091
|
result.error = response.error;
|
|
@@ -5960,6 +6110,6 @@ var fetchInfinite = async (request, options) => {
|
|
|
5960
6110
|
return result;
|
|
5961
6111
|
};
|
|
5962
6112
|
//#endregion
|
|
5963
|
-
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 };
|
|
5964
6114
|
|
|
5965
6115
|
//# sourceMappingURL=index.mjs.map
|