@uni-helper/uni-network
Version:
为 uni-app 打造的基于 Promise 的 HTTP 客户端
968 lines (935 loc) • 36.3 kB
JavaScript
import statuses from "statuses-es";
import qs from "fast-querystring";
import merge from "lodash.merge";
//#region package.json
var version = "0.23.1";
//#endregion
//#region \0@oxc-project+runtime@0.95.0/helpers/typeof.js
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
return typeof o$1;
} : function(o$1) {
return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
}, _typeof(o);
}
//#endregion
//#region \0@oxc-project+runtime@0.95.0/helpers/toPrimitive.js
function toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != _typeof(i)) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
//#endregion
//#region \0@oxc-project+runtime@0.95.0/helpers/toPropertyKey.js
function toPropertyKey(t) {
var i = toPrimitive(t, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
//#endregion
//#region \0@oxc-project+runtime@0.95.0/helpers/defineProperty.js
function _defineProperty(e, r, t) {
return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[r] = t, e;
}
//#endregion
//#region src/core/UnError.ts
var UnError = class UnError extends Error {
constructor(message, code, config, task, response) {
super(message);
_defineProperty(this, "code", void 0);
_defineProperty(this, "config", void 0);
_defineProperty(this, "task", void 0);
_defineProperty(this, "response", void 0);
_defineProperty(this, "isUnError", void 0);
_defineProperty(this, "status", void 0);
_defineProperty(this, "cause", void 0);
this.name = "UnError";
this.message = message !== null && message !== void 0 ? message : "";
if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
else this.stack = (/* @__PURE__ */ new Error()).stack;
this.code = code;
this.config = config;
this.task = task;
if (response) {
var _response$status;
this.response = response;
this.status = (_response$status = response.status) !== null && _response$status !== void 0 ? _response$status : void 0;
}
this.isUnError = true;
}
toJSON() {
return {
message: this.message,
name: this.name,
description: this.description,
number: this.number,
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
config: this.config,
code: this.code,
status: this.status
};
}
static from(error, code, config, task, response, customProps) {
const unError = new UnError(error === null || error === void 0 ? void 0 : error.message, code, config, task, response);
if (customProps) Object.assign(unError, customProps);
return unError;
}
};
_defineProperty(UnError, "ERR_FR_TOO_MANY_REDIRECTS", "ERR_FR_TOO_MANY_REDIRECTS");
_defineProperty(UnError, "ERR_BAD_OPTION_VALUE", "ERR_BAD_OPTION_VALUE");
_defineProperty(UnError, "ERR_BAD_OPTION", "ERR_BAD_OPTION");
_defineProperty(UnError, "ERR_NETWORK", "ERR_NETWORK");
_defineProperty(UnError, "ERR_DEPRECATED", "ERR_DEPRECATED");
_defineProperty(UnError, "ERR_BAD_RESPONSE", "ERR_BAD_RESPONSE");
_defineProperty(UnError, "ERR_BAD_REQUEST", "ERR_BAD_REQUEST");
_defineProperty(UnError, "ERR_NOT_SUPPORT", "ERR_NOT_SUPPORT");
_defineProperty(UnError, "ERR_INVALID_URL", "ERR_INVALID_URL");
_defineProperty(UnError, "ERR_CANCELED", "ERR_CANCELED");
_defineProperty(UnError, "ECONNABORTED", "ECONNABORTED");
_defineProperty(UnError, "ETIMEDOUT", "ETIMEDOUT");
//#endregion
//#region src/core/settle.ts
const settle = (resolve, reject, response) => {
var _response$config;
const validateStatus = response === null || response === void 0 || (_response$config = response.config) === null || _response$config === void 0 ? void 0 : _response$config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) resolve(response);
else reject(new UnError(`Request failed with status code ${response.status}`, [UnError.ERR_BAD_REQUEST, UnError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], response.config, response.task, response));
};
//#endregion
//#region src/core/UnCanceledError.ts
var UnCanceledError = class extends UnError {
constructor(message, config, task) {
super(message !== null && message !== void 0 ? message : "canceled");
_defineProperty(this, "isUnCanceledError", true);
this.name = "CanceledError";
this.message = message !== null && message !== void 0 ? message : "canceled";
this.code = UnError.ERR_CANCELED;
this.config = config;
this.task = task;
}
};
UnCanceledError.prototype.isUnCanceledError = true;
//#endregion
//#region src/utils/combineUrls.ts
const combineUrls = (baseUrl, relativeUrl) => {
return relativeUrl ? `${baseUrl.replace(/\/?\/$/, "")}/${relativeUrl.replace(/^\/+/, "")}` : baseUrl;
};
//#endregion
//#region src/utils/isAbsoluteUrl.ts
const isAbsoluteUrl = (url) => {
return /^([a-z][\d+.a-z-]*:)\/\//i.test(url);
};
//#endregion
//#region src/utils/buildFullPath.ts
const buildFullPath = (baseUrl, requestedUrl, allowAbsoluteUrls) => {
const isRelativeUrl = !isAbsoluteUrl(requestedUrl);
if (baseUrl && (isRelativeUrl || !allowAbsoluteUrls)) return combineUrls(baseUrl, requestedUrl);
return requestedUrl;
};
//#endregion
//#region src/utils/buildUrl.ts
const buildUrl = (url, params, paramsSerializer) => {
if (!params) return url;
let newUrl = url;
const hashIndex = url.indexOf("#");
if (hashIndex !== -1) newUrl = newUrl.slice(0, hashIndex);
const serializerParams = paramsSerializer ? paramsSerializer(params) : Object.prototype.toString.call(params).includes("URLSearchParams") ? params.toString() : qs.stringify(params);
if (serializerParams) newUrl += (newUrl.includes("?") ? "&" : "?") + serializerParams;
return newUrl;
};
//#endregion
//#region src/utils/buildDownloadConfig.ts
const buildDownloadConfig = (config) => {
var _config$baseUrl, _config$url, _config$allowAbsolute;
const result = {
url: buildUrl(buildFullPath((_config$baseUrl = config.baseUrl) !== null && _config$baseUrl !== void 0 ? _config$baseUrl : "", (_config$url = config.url) !== null && _config$url !== void 0 ? _config$url : "", (_config$allowAbsolute = config.allowAbsoluteUrls) !== null && _config$allowAbsolute !== void 0 ? _config$allowAbsolute : true), config.params, config.paramsSerializer),
header: config.headers,
timeout: config.timeout,
filePath: config.filePath
};
const entries = Object.entries(result);
return Object.fromEntries(entries.filter(([k]) => result[k] != null));
};
//#endregion
//#region src/utils/buildRequestConfig.ts
const buildRequestConfig = (config) => {
var _config$baseUrl, _config$url, _config$allowAbsolute, _config$method$toUppe, _config$method;
const result = {
url: buildUrl(buildFullPath((_config$baseUrl = config.baseUrl) !== null && _config$baseUrl !== void 0 ? _config$baseUrl : "", (_config$url = config.url) !== null && _config$url !== void 0 ? _config$url : "", (_config$allowAbsolute = config.allowAbsoluteUrls) !== null && _config$allowAbsolute !== void 0 ? _config$allowAbsolute : true), config.params, config.paramsSerializer),
data: config.data,
header: config.headers,
method: (_config$method$toUppe = (_config$method = config.method) === null || _config$method === void 0 ? void 0 : _config$method.toUpperCase()) !== null && _config$method$toUppe !== void 0 ? _config$method$toUppe : "GET",
timeout: config.timeout,
dataType: config.dataType,
responseType: config.responseType,
sslVerify: config.sslVerify,
withCredentials: config.withCredentials,
firstIpv4: config.firstIpv4,
enableHttp2: config.enableHttp2,
enableQuic: config.enableQuic,
enableCache: config.enableCache,
enableHttpDNS: config.enableHttpDNS,
httpDNSServiceId: config.httpDNSServiceId,
enableChunked: config.enableChunked,
forceCellularNetwork: config.forceCellularNetwork,
enableCookie: config.enableCookie,
cloudCache: config.cloudCache,
defer: config.defer
};
const entries = Object.entries(result);
return Object.fromEntries(entries.filter(([k]) => result[k] != null));
};
//#endregion
//#region src/utils/buildUploadConfig.ts
const buildUploadConfig = (config) => {
var _config$baseUrl, _config$url, _config$allowAbsolute;
const result = {
url: buildUrl(buildFullPath((_config$baseUrl = config.baseUrl) !== null && _config$baseUrl !== void 0 ? _config$baseUrl : "", (_config$url = config.url) !== null && _config$url !== void 0 ? _config$url : "", (_config$allowAbsolute = config.allowAbsoluteUrls) !== null && _config$allowAbsolute !== void 0 ? _config$allowAbsolute : true), config.params, config.paramsSerializer),
files: config.files,
fileType: config.fileType,
file: config.file,
filePath: config.filePath,
name: config.name,
header: config.headers,
timeout: config.timeout,
formData: config.formData
};
const entries = Object.entries(result);
return Object.fromEntries(entries.filter(([k]) => result[k] != null));
};
//#endregion
//#region src/utils/forEach.ts
/**
* 遍历数组或对象,为每项调用方法
*
* 如果 obj 是一个数组,传递每项的值、索引和完整的数组
*
* 如果 obj 是一个对象,为每个属性传递值、键和完整的对象
*/
function forEach(obj, fn, { allOwnKeys = false } = {}) {
if (obj === null || obj === void 0) return;
let i;
let l;
const object = typeof obj !== "object" ? [obj] : obj;
if (Array.isArray(object)) for (i = 0, l = object.length; i < l; i++) fn.call(null, object[i], i, object);
else {
const keys = allOwnKeys ? Object.getOwnPropertyNames(object).filter((key$1) => key$1 !== "constructor" && !key$1.startsWith("_")) : Object.keys(object);
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
fn.call(null, object[key], key, object);
}
}
}
//#endregion
//#region src/utils/extend.ts
/**
* 向对象 a 添加对象 b 的属性
*
* 直接改变对象 a
*/
const extend = (a, b, thisArg, { allOwnKeys = false } = {}) => {
forEach(b, (val, key) => {
a[key] = thisArg && typeof val === "function" ? val.bind(thisArg) : val;
}, { allOwnKeys });
return a;
};
//#endregion
//#region src/utils/mergeConfig.ts
function mergeConfig(config1, config2) {
return merge({}, config1 !== null && config1 !== void 0 ? config1 : {}, config2 !== null && config2 !== void 0 ? config2 : {});
}
//#endregion
//#region \0@oxc-project+runtime@0.95.0/helpers/objectSpread2.js
function ownKeys(e, r) {
var t = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
r && (o = o.filter(function(r$1) {
return Object.getOwnPropertyDescriptor(e, r$1).enumerable;
})), t.push.apply(t, o);
}
return t;
}
function _objectSpread2(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys(Object(t), !0).forEach(function(r$1) {
_defineProperty(e, r$1, t[r$1]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) {
Object.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1));
});
}
return e;
}
//#endregion
//#region src/adapters/download.ts
const downloadAdapter = (config) => new Promise((resolve, reject) => {
var _ref, _ref2, _config$onDownloadPro;
const { onHeadersReceived, cancelToken, signal } = config;
const onProgressUpdate = (_ref = (_ref2 = (_config$onDownloadPro = config === null || config === void 0 ? void 0 : config.onDownloadProgress) !== null && _config$onDownloadPro !== void 0 ? _config$onDownloadPro : config === null || config === void 0 ? void 0 : config.onDownloadProgressUpdate) !== null && _ref2 !== void 0 ? _ref2 : config === null || config === void 0 ? void 0 : config.onProgress) !== null && _ref !== void 0 ? _ref : config === null || config === void 0 ? void 0 : config.onProgressUpdate;
const downloadConfig = buildDownloadConfig(config);
let onCanceled;
const done = () => {
cancelToken === null || cancelToken === void 0 || cancelToken.unsubscribe(onCanceled);
signal === null || signal === void 0 || signal.removeEventListener("abort", onCanceled);
};
let task;
task = uni.downloadFile(_objectSpread2(_objectSpread2({}, downloadConfig), {}, {
success: (res) => {
var _ref3, _ref4, _res$errMsg, _res$header;
let statusText;
try {
var _statuses;
statusText = (_statuses = statuses(res === null || res === void 0 ? void 0 : res.statusCode)) === null || _statuses === void 0 ? void 0 : _statuses.toString();
} catch (_) {
statusText = void 0;
}
settle((val) => {
resolve(val);
done();
}, (err) => {
reject(err);
done();
}, {
errMsg: (_ref3 = (_ref4 = (_res$errMsg = res === null || res === void 0 ? void 0 : res.errMsg) !== null && _res$errMsg !== void 0 ? _res$errMsg : res === null || res === void 0 ? void 0 : res.errmsg) !== null && _ref4 !== void 0 ? _ref4 : res === null || res === void 0 ? void 0 : res.msg) !== null && _ref3 !== void 0 ? _ref3 : res === null || res === void 0 ? void 0 : res.message,
errno: res === null || res === void 0 ? void 0 : res.errno,
tempFilePath: res === null || res === void 0 ? void 0 : res.tempFilePath,
filePath: res === null || res === void 0 ? void 0 : res.filePath,
profile: res === null || res === void 0 ? void 0 : res.profile,
status: res === null || res === void 0 ? void 0 : res.statusCode,
statusText,
headers: (_res$header = res === null || res === void 0 ? void 0 : res.header) !== null && _res$header !== void 0 ? _res$header : res === null || res === void 0 ? void 0 : res.headers,
config,
data: {
tempFilePath: res === null || res === void 0 ? void 0 : res.tempFilePath,
filePath: res === null || res === void 0 ? void 0 : res.filePath
},
task
});
},
fail: (err) => {
switch (err.errMsg) {
case "request:fail abort":
reject(new UnError(err.errMsg, UnError.ERR_CANCELED, config, task));
break;
case "request:fail timeout":
reject(new UnError(err.errMsg, UnError.ETIMEDOUT, config, task));
break;
default:
reject(new UnError(err.errMsg, UnError.ERR_NETWORK, config, task));
break;
}
},
complete: () => {
if (onHeadersReceived) task === null || task === void 0 || task.offHeadersReceived(onHeadersReceived);
if (onProgressUpdate) task === null || task === void 0 || task.offProgressUpdate(onProgressUpdate);
}
}));
if (onHeadersReceived) task.onHeadersReceived(onHeadersReceived);
if (onProgressUpdate) task.onProgressUpdate(onProgressUpdate);
if (cancelToken || signal) {
var _signal$addEventListe;
onCanceled = (cancel) => {
if (!task) return;
reject(!cancel || cancel.type ? new UnCanceledError(void 0, config, task) : cancel);
task.abort();
task = void 0;
};
cancelToken === null || cancelToken === void 0 || cancelToken.subscribe(onCanceled);
(signal === null || signal === void 0 ? void 0 : signal.aborted) ? onCanceled({}) : signal === null || signal === void 0 || (_signal$addEventListe = signal.addEventListener) === null || _signal$addEventListe === void 0 || _signal$addEventListe.call(signal, "abort", onCanceled);
}
});
//#endregion
//#region src/adapters/request.ts
const requestAdapter = (config) => new Promise((resolve, reject) => {
const { onHeadersReceived, onChunkReceived, cancelToken, signal } = config;
const requestConfig = buildRequestConfig(config);
let onCanceled;
const done = () => {
var _signal$removeEventLi;
cancelToken === null || cancelToken === void 0 || cancelToken.unsubscribe(onCanceled);
signal === null || signal === void 0 || (_signal$removeEventLi = signal.removeEventListener) === null || _signal$removeEventLi === void 0 || _signal$removeEventLi.call(signal, "abort", onCanceled);
};
let task;
task = uni.request(_objectSpread2(_objectSpread2({}, requestConfig), {}, {
success: (res) => {
var _ref, _ref2, _res$errMsg, _res$header;
let statusText;
try {
var _statuses;
statusText = (_statuses = statuses(res === null || res === void 0 ? void 0 : res.statusCode)) === null || _statuses === void 0 ? void 0 : _statuses.toString();
} catch (_) {
statusText = void 0;
}
settle((val) => {
resolve(val);
done();
}, (err) => {
reject(err);
done();
}, {
errMsg: (_ref = (_ref2 = (_res$errMsg = res === null || res === void 0 ? void 0 : res.errMsg) !== null && _res$errMsg !== void 0 ? _res$errMsg : res === null || res === void 0 ? void 0 : res.errmsg) !== null && _ref2 !== void 0 ? _ref2 : res === null || res === void 0 ? void 0 : res.msg) !== null && _ref !== void 0 ? _ref : res === null || res === void 0 ? void 0 : res.message,
errno: res === null || res === void 0 ? void 0 : res.errno,
cookies: res === null || res === void 0 ? void 0 : res.cookies,
profile: res === null || res === void 0 ? void 0 : res.profile,
status: res === null || res === void 0 ? void 0 : res.statusCode,
statusText,
headers: (_res$header = res === null || res === void 0 ? void 0 : res.header) !== null && _res$header !== void 0 ? _res$header : res === null || res === void 0 ? void 0 : res.headers,
config,
data: res === null || res === void 0 ? void 0 : res.data,
task
});
},
fail: (err) => {
switch (err.errMsg) {
case "request:fail abort":
reject(new UnError(err.errMsg, UnError.ERR_CANCELED, config, task));
break;
case "request:fail timeout":
reject(new UnError(err.errMsg, UnError.ETIMEDOUT, config, task));
break;
default:
reject(new UnError(err.errMsg, UnError.ERR_NETWORK, config, task));
break;
}
},
complete: () => {
if (onHeadersReceived) task === null || task === void 0 || task.offHeadersReceived(onHeadersReceived);
if (onChunkReceived) task === null || task === void 0 || task.offChunkReceived(onChunkReceived);
}
}));
if (onHeadersReceived) task.onHeadersReceived(onHeadersReceived);
if (onChunkReceived) task.onChunkReceived(onChunkReceived);
if (cancelToken || signal) {
var _signal$addEventListe;
onCanceled = (cancel) => {
if (!task) return;
reject(!cancel || cancel.type ? new UnCanceledError(void 0, config, task) : cancel);
task.abort();
task = void 0;
};
cancelToken === null || cancelToken === void 0 || cancelToken.subscribe(onCanceled);
(signal === null || signal === void 0 ? void 0 : signal.aborted) ? onCanceled({}) : signal === null || signal === void 0 || (_signal$addEventListe = signal.addEventListener) === null || _signal$addEventListe === void 0 || _signal$addEventListe.call(signal, "abort", onCanceled);
}
});
//#endregion
//#region src/adapters/upload.ts
const uploadAdapter = (config) => new Promise((resolve, reject) => {
var _ref, _ref2, _config$onUploadProgr;
const { onHeadersReceived, cancelToken, signal } = config;
const onProgressUpdate = (_ref = (_ref2 = (_config$onUploadProgr = config === null || config === void 0 ? void 0 : config.onUploadProgress) !== null && _config$onUploadProgr !== void 0 ? _config$onUploadProgr : config === null || config === void 0 ? void 0 : config.onUploadProgressUpdate) !== null && _ref2 !== void 0 ? _ref2 : config === null || config === void 0 ? void 0 : config.onProgress) !== null && _ref !== void 0 ? _ref : config === null || config === void 0 ? void 0 : config.onProgressUpdate;
const uploadConfig = buildUploadConfig(config);
let onCanceled;
const done = () => {
cancelToken === null || cancelToken === void 0 || cancelToken.unsubscribe(onCanceled);
signal === null || signal === void 0 || signal.removeEventListener("abort", onCanceled);
};
let task;
task = uni.uploadFile(_objectSpread2(_objectSpread2({}, uploadConfig), {}, {
success: (res) => {
var _ref3, _ref4, _res$errMsg, _res$header;
let statusText;
try {
var _statuses;
statusText = (_statuses = statuses(res === null || res === void 0 ? void 0 : res.statusCode)) === null || _statuses === void 0 ? void 0 : _statuses.toString();
} catch (_) {
statusText = void 0;
}
settle((val) => {
resolve(val);
done();
}, (err) => {
reject(err);
done();
}, {
errMsg: (_ref3 = (_ref4 = (_res$errMsg = res === null || res === void 0 ? void 0 : res.errMsg) !== null && _res$errMsg !== void 0 ? _res$errMsg : res === null || res === void 0 ? void 0 : res.errmsg) !== null && _ref4 !== void 0 ? _ref4 : res === null || res === void 0 ? void 0 : res.msg) !== null && _ref3 !== void 0 ? _ref3 : res === null || res === void 0 ? void 0 : res.message,
errno: res === null || res === void 0 ? void 0 : res.errno,
status: res === null || res === void 0 ? void 0 : res.statusCode,
statusText,
headers: (_res$header = res === null || res === void 0 ? void 0 : res.header) !== null && _res$header !== void 0 ? _res$header : res === null || res === void 0 ? void 0 : res.headers,
config,
data: res === null || res === void 0 ? void 0 : res.data,
task
});
},
fail: (err) => {
switch (err.errMsg) {
case "request:fail abort":
reject(new UnError(err.errMsg, UnError.ERR_CANCELED, config, task));
break;
case "request:fail timeout":
reject(new UnError(err.errMsg, UnError.ETIMEDOUT, config, task));
break;
default:
reject(new UnError(err.errMsg, UnError.ERR_NETWORK, config, task));
break;
}
},
complete: () => {
if (onHeadersReceived) task === null || task === void 0 || task.offHeadersReceived(onHeadersReceived);
if (onProgressUpdate) task === null || task === void 0 || task.offProgressUpdate(onProgressUpdate);
}
}));
if (onHeadersReceived) task.onHeadersReceived(onHeadersReceived);
if (onProgressUpdate) task.onProgressUpdate(onProgressUpdate);
if (cancelToken || signal) {
var _signal$addEventListe;
onCanceled = (cancel) => {
if (!task) return;
reject(!cancel || cancel.type ? new UnCanceledError(void 0, config, task) : cancel);
task.abort();
task = void 0;
};
cancelToken === null || cancelToken === void 0 || cancelToken.subscribe(onCanceled);
(signal === null || signal === void 0 ? void 0 : signal.aborted) ? onCanceled({}) : signal === null || signal === void 0 || (_signal$addEventListe = signal.addEventListener) === null || _signal$addEventListe === void 0 || _signal$addEventListe.call(signal, "abort", onCanceled);
}
});
//#endregion
//#region src/adapters/index.ts
const adapters = {
download: downloadAdapter,
request: requestAdapter,
upload: uploadAdapter
};
//#endregion
//#region src/core/isUnCancel.ts
const isUnCancel = (value) => (value === null || value === void 0 ? void 0 : value.isUnCanceledError) === true;
//#endregion
//#region src/core/dispatchRequest.ts
const throwIfCancellationRequested = (config) => {
var _config$signal;
if (config.cancelToken) {
var _config$cancelToken;
(_config$cancelToken = config.cancelToken) === null || _config$cancelToken === void 0 || _config$cancelToken.throwIfRequested();
}
if ((_config$signal = config.signal) === null || _config$signal === void 0 ? void 0 : _config$signal.aborted) throw new UnCanceledError();
};
const dispatchRequest = (config) => {
throwIfCancellationRequested(config);
let adapter = requestAdapter;
if (typeof config.adapter === "string" && adapters[config.adapter]) adapter = adapters[config.adapter];
else if (typeof config.adapter === "function") adapter = config.adapter;
return adapter(config).then((response) => {
throwIfCancellationRequested(config);
return response;
}, (error) => {
if (!isUnCancel(error)) throwIfCancellationRequested(config);
throw error;
});
};
//#endregion
//#region src/core/HttpStatusCode.ts
const HttpStatusCode = {
Continue: 100,
100: "Continue",
SwitchingProtocols: 101,
101: "SwitchingProtocols",
Processing: 102,
102: "Processing",
EarlyHints: 103,
103: "EarlyHints",
Ok: 200,
200: "Ok",
Created: 201,
201: "Created",
Accepted: 202,
202: "Accepted",
NonAuthoritativeInformation: 203,
203: "NonAuthoritativeInformation",
NoContent: 204,
204: "NoContent",
ResetContent: 205,
205: "ResetContent",
PartialContent: 206,
206: "PartialContent",
MultiStatus: 207,
207: "MultiStatus",
AlreadyReported: 208,
208: "AlreadyReported",
ImUsed: 226,
226: "ImUsed",
MultipleChoices: 300,
300: "MultipleChoices",
MovedPermanently: 301,
301: "MovedPermanently",
Found: 302,
302: "Found",
SeeOther: 303,
303: "SeeOther",
NotModified: 304,
304: "NotModified",
UseProxy: 305,
305: "UseProxy",
Unused: 306,
306: "Unused",
TemporaryRedirect: 307,
307: "TemporaryRedirect",
PermanentRedirect: 308,
308: "PermanentRedirect",
BadRequest: 400,
400: "BadRequest",
Unauthorized: 401,
401: "Unauthorized",
PaymentRequired: 402,
402: "PaymentRequired",
Forbidden: 403,
403: "Forbidden",
NotFound: 404,
404: "NotFound",
MethodNotAllowed: 405,
405: "MethodNotAllowed",
NotAcceptable: 406,
406: "NotAcceptable",
ProxyAuthenticationRequired: 407,
407: "ProxyAuthenticationRequired",
RequestTimeout: 408,
408: "RequestTimeout",
Conflict: 409,
409: "Conflict",
Gone: 410,
410: "Gone",
LengthRequired: 411,
411: "LengthRequired",
PreconditionFailed: 412,
412: "PreconditionFailed",
PayloadTooLarge: 413,
413: "PayloadTooLarge",
UriTooLong: 414,
414: "UriTooLong",
UnsupportedMediaType: 415,
415: "UnsupportedMediaType",
RangeNotSatisfiable: 416,
416: "RangeNotSatisfiable",
ExpectationFailed: 417,
417: "ExpectationFailed",
ImATeapot: 418,
418: "ImATeapot",
MisdirectedRequest: 421,
421: "MisdirectedRequest",
UnprocessableEntity: 422,
422: "UnprocessableEntity",
Locked: 423,
423: "Locked",
FailedDependency: 424,
424: "FailedDependency",
TooEarly: 425,
425: "TooEarly",
UpgradeRequired: 426,
426: "UpgradeRequired",
PreconditionRequired: 428,
428: "PreconditionRequired",
TooManyRequests: 429,
429: "TooManyRequests",
RequestHeaderFieldsTooLarge: 431,
431: "RequestHeaderFieldsTooLarge",
UnavailableForLegalReasons: 451,
451: "UnavailableForLegalReasons",
InternalServerError: 500,
500: "InternalServerError",
NotImplemented: 501,
501: "NotImplemented",
BadGateway: 502,
502: "BadGateway",
ServiceUnavailable: 503,
503: "ServiceUnavailable",
GatewayTimeout: 504,
504: "GatewayTimeout",
HttpVersionNotSupported: 505,
505: "HttpVersionNotSupported",
VariantAlsoNegotiates: 506,
506: "VariantAlsoNegotiates",
InsufficientStorage: 507,
507: "InsufficientStorage",
LoopDetected: 508,
508: "LoopDetected",
NotExtended: 510,
510: "NotExtended",
NetworkAuthenticationRequired: 511,
511: "NetworkAuthenticationRequired"
};
//#endregion
//#region src/core/isUnError.ts
const isUnError = (value) => (value === null || value === void 0 ? void 0 : value.isUnError) === true;
//#endregion
//#region src/core/UnInterceptorManager.ts
var UnInterceptorManager = class {
constructor() {
_defineProperty(this, "handlers", []);
}
use(fulfilled, rejected, options) {
var _options$synchronous;
this.handlers.push({
fulfilled,
rejected,
synchronous: (_options$synchronous = options === null || options === void 0 ? void 0 : options.synchronous) !== null && _options$synchronous !== void 0 ? _options$synchronous : false,
runWhen: options === null || options === void 0 ? void 0 : options.runWhen
});
return this.handlers.length - 1;
}
eject(id) {
if (this.handlers[id]) this.handlers[id] = null;
}
clear() {
if (this.handlers) this.handlers = [];
}
each(fn) {
for (const handler of this.handlers) if (handler && fn) fn(handler);
}
};
//#endregion
//#region src/core/Un.ts
var Un = class {
constructor(instanceConfig) {
_defineProperty(this, "defaults", void 0);
_defineProperty(this, "interceptors", void 0);
this.defaults = instanceConfig || {};
this.interceptors = {
request: new UnInterceptorManager(),
response: new UnInterceptorManager()
};
}
_request(configOrUrl, config) {
const _config = typeof configOrUrl === "string" ? _objectSpread2(_objectSpread2({}, config), {}, { url: configOrUrl }) : _objectSpread2(_objectSpread2({}, configOrUrl), config);
const mergedConfig = mergeConfig(this.defaults, _config);
const requestInterceptorChain = [];
let synchronousRequestInterceptors = true;
this.interceptors.request.each((interceptor) => {
var _interceptor$synchron;
if (typeof interceptor.runWhen === "function" && interceptor.runWhen(mergedConfig) === false) return;
synchronousRequestInterceptors = synchronousRequestInterceptors && ((_interceptor$synchron = interceptor === null || interceptor === void 0 ? void 0 : interceptor.synchronous) !== null && _interceptor$synchron !== void 0 ? _interceptor$synchron : false);
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
});
const responseInterceptorChain = [];
this.interceptors.response.each((interceptor) => {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
let promise;
let i = 0;
let len = 0;
if (!synchronousRequestInterceptors) {
const chain = [dispatchRequest.bind(this), void 0];
chain.unshift(...requestInterceptorChain);
chain.push(...responseInterceptorChain);
len = chain.length;
promise = Promise.resolve(mergedConfig);
while (i < len) promise = promise.then(chain[i++], chain[i++]);
return promise;
}
len = requestInterceptorChain.length;
let newConfig = mergedConfig;
i = 0;
while (i < len) {
const onFulfilled = requestInterceptorChain[i++];
const onRejected = requestInterceptorChain[i++];
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected.call(this, error);
break;
}
}
try {
promise = dispatchRequest.call(this, newConfig);
} catch (error) {
return Promise.reject(error);
}
i = 0;
len = responseInterceptorChain.length;
while (i < len) promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
return promise;
}
async request(configOrUrl, config) {
var _this = this;
try {
return await _this._request(configOrUrl, config);
} catch (error) {
if (error instanceof Error) {
let dummy = {};
Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = /* @__PURE__ */ new Error();
const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : "";
if (!error.stack) error.stack = stack;
else if (stack && !String(error.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) error.stack += `\n${stack}`;
}
throw error;
}
}
download(configOrUrl, config) {
return this.request(configOrUrl, _objectSpread2(_objectSpread2({}, config), {}, { adapter: "download" }));
}
upload(configOrUrl, config) {
return this.request(configOrUrl, _objectSpread2(_objectSpread2({}, config), {}, { adapter: "upload" }));
}
get(url, config) {
return this.request(_objectSpread2(_objectSpread2({}, config), {}, {
method: "GET",
url
}));
}
delete(url, config) {
return this.request(_objectSpread2(_objectSpread2({}, config), {}, {
method: "DELETE",
url
}));
}
head(url, config) {
return this.request(_objectSpread2(_objectSpread2({}, config), {}, {
method: "HEAD",
url
}));
}
options(url, config) {
return this.request(_objectSpread2(_objectSpread2({}, config), {}, {
method: "OPTIONS",
url
}));
}
trace(url, config) {
return this.request(_objectSpread2(_objectSpread2({}, config), {}, {
method: "TRACE",
url
}));
}
connect(url, config) {
return this.request(_objectSpread2(_objectSpread2({}, config), {}, {
method: "CONNECT",
url
}));
}
post(url, data, config) {
return this.request(_objectSpread2(_objectSpread2({}, config), {}, {
method: "POST",
url,
data
}));
}
put(url, data, config) {
return this.request(_objectSpread2(_objectSpread2({}, config), {}, {
method: "PUT",
url,
data
}));
}
patch(url, data, config) {
return this.request(_objectSpread2(_objectSpread2({}, config), {}, {
method: "PATCH",
url,
data
}));
}
getUri(config) {
var _mergedConfig$baseUrl, _mergedConfig$url, _mergedConfig$allowAb;
const mergedConfig = mergeConfig(this.defaults, config);
return buildUrl(buildFullPath((_mergedConfig$baseUrl = mergedConfig === null || mergedConfig === void 0 ? void 0 : mergedConfig.baseUrl) !== null && _mergedConfig$baseUrl !== void 0 ? _mergedConfig$baseUrl : "", (_mergedConfig$url = mergedConfig === null || mergedConfig === void 0 ? void 0 : mergedConfig.url) !== null && _mergedConfig$url !== void 0 ? _mergedConfig$url : "", (_mergedConfig$allowAb = mergedConfig === null || mergedConfig === void 0 ? void 0 : mergedConfig.allowAbsoluteUrls) !== null && _mergedConfig$allowAb !== void 0 ? _mergedConfig$allowAb : true), mergedConfig === null || mergedConfig === void 0 ? void 0 : mergedConfig.params, mergedConfig === null || mergedConfig === void 0 ? void 0 : mergedConfig.paramsSerializer);
}
};
//#endregion
//#region src/core/UnCancelToken.ts
var UnCancelToken = class UnCancelToken {
constructor(executor) {
_defineProperty(this, "promise", void 0);
_defineProperty(this, "reason", void 0);
_defineProperty(this, "listeners", []);
if (typeof executor !== "function") throw new TypeError("executor must be a function.");
let resolvePromise;
this.promise = new Promise((resolve) => {
resolvePromise = resolve;
});
this.promise.then((cancel) => {
for (const listener of this.listeners) listener(cancel);
this.listeners = [];
});
this.promise.then = (onfulfilled) => {
let _resolve;
const promise = new Promise((resolve) => {
this.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = () => {
this.unsubscribe(_resolve);
};
return promise;
};
executor((message, config, request) => {
if (this.reason) return;
this.reason = new UnCanceledError(message, config, request);
resolvePromise(this.reason);
});
}
throwIfRequested() {
if (this.reason) throw this.reason;
}
subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
this.listeners.push(listener);
}
unsubscribe(listener) {
const index = this.listeners.indexOf(listener);
if (index !== -1) this.listeners.splice(index, 1);
}
toAbortSignal() {
const controller = new AbortController();
const abort = (error) => {
controller.abort(error);
};
this.subscribe(abort);
controller.signal.unsubscribe = () => this.unsubscribe(abort);
return controller.signal;
}
static source() {
let cancel;
return {
token: new UnCancelToken((c) => {
cancel = c;
}),
cancel
};
}
};
//#endregion
//#region src/defaults/index.ts
const defaults = {
adapter: "request",
validateStatus: (status) => status >= 200 && status < 300
};
//#endregion
//#region src/index.ts
const createInstance = (defaultConfig) => {
const context = new Un(defaultConfig);
const instance = Un.prototype.request.bind(context);
extend(instance, Un.prototype, context, { allOwnKeys: true });
extend(instance, context, null, { allOwnKeys: true });
instance.create = (instanceConfig) => createInstance(mergeConfig(defaultConfig, instanceConfig));
return instance;
};
const un = createInstance(defaults);
un.Un = Un;
un.CanceledError = UnCanceledError;
un.CancelToken = UnCancelToken;
un.isCancel = isUnCancel;
un.VERSION = version;
un.UnError = UnError;
un.isUnError = isUnError;
un.all = (promises) => Promise.all(promises);
un.mergeConfig = mergeConfig;
un.HttpStatusCode = HttpStatusCode;
var src_default = un;
//#endregion
export { buildFullPath as C, settle as D, UnCanceledError as E, UnError as O, buildUrl as S, combineUrls as T, extend as _, Un as a, buildRequestConfig as b, HttpStatusCode as c, adapters as d, uploadAdapter as f, mergeConfig as g, _objectSpread2 as h, UnCancelToken as i, dispatchRequest as l, downloadAdapter as m, un as n, UnInterceptorManager as o, requestAdapter as p, defaults as r, isUnError as s, src_default as t, isUnCancel as u, forEach as v, isAbsoluteUrl as w, buildDownloadConfig as x, buildUploadConfig as y };