ym-userequest
Version:
useRequest for vue3
1,332 lines • 50.1 kB
JavaScript
"use strict";
function _array_like_to_array(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _array_without_holes(arr) {
if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _async_to_generator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _iterable_to_array(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _non_iterable_spread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function(key) {
_define_property(target, key, source[key]);
});
}
return target;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _object_spread_props(target, source) {
source = source != null ? source : {};
if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
function _object_without_properties(source, excluded) {
if (source == null) return {};
var target = _object_without_properties_loose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for(i = 0; i < sourceSymbolKeys.length; i++){
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _object_without_properties_loose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for(i = 0; i < sourceKeys.length; i++){
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _to_consumable_array(arr) {
return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
function _type_of(obj) {
"@swc/helpers - typeof";
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
}
function _unsupported_iterable_to_array(o, minLen) {
if (!o) return;
if (typeof o === "string") return _array_like_to_array(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
function _ts_generator(thisArg, body) {
var f, y, t, g, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
};
return g = {
next: verb(0),
"throw": verb(1),
"return": verb(2)
}, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([
n,
v
]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while(_)try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [
op[0] & 2,
t.value
];
switch(op[0]){
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {
value: op[1],
done: false
};
case 5:
_.label++;
y = op[1];
op = [
0
];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [
6,
e
];
y = 0;
} finally{
f = t = 0;
}
if (op[0] & 5) throw op[1];
return {
value: op[0] ? op[1] : void 0,
done: true
};
}
}
var _window;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = function(target, all) {
for(var name in all)__defProp(target, name, {
get: all[name],
enumerable: true
});
};
var __copyProps = function(to, from, except, desc) {
if (from && (typeof from === "undefined" ? "undefined" : _type_of(from)) === "object" || typeof from === "function") {
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
try {
var _loop = function() {
var key = _step.value;
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: function() {
return from[key];
},
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
};
for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop();
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally{
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally{
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
return to;
};
var __toCommonJS = function(mod) {
return __copyProps(__defProp({}, "__esModule", {
value: true
}), mod);
};
// lib/index.ts
var lib_exports = {};
__export(lib_exports, {
TypeChecker: function() {
return TypeChecker;
},
clearCache: function() {
return clearCache;
},
debounce: function() {
return debounce_default;
},
definePlugins: function() {
return definePlugins;
},
getCache: function() {
return getCache;
},
setCache: function() {
return setCache;
},
throttle: function() {
return throttle_default;
},
trigger: function() {
return trigger;
},
useRequest: function() {
return useRequest;
}
});
module.exports = __toCommonJS(lib_exports);
// lib/utils/index.ts
var import_vue = require("vue");
function useDelay(fn, delay) {
if (delay) {
return setTimeout(function() {
fn();
}, delay);
} else {
fn();
}
}
var isNonZeroFalsy = function(value) {
return !isNumber(value) && !value;
};
var unrefParms = function(value) {
var _value = (0, import_vue.unref)(value);
_value = TypeChecker.isArray(_value) ? _value : [
_value
];
return _value;
};
var composeMiddleware = function(middleArray, hook) {
return function() {
var next = hook;
for(var i = middleArray.length; i-- > 0;){
next = middleArray[i](next);
}
return next();
};
};
var isType = function isType(o) {
var s = Object.prototype.toString.call(o);
return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};
var isNull = function(v) {
return isType(v) === "null";
};
var isUndefined = function(v) {
return isType(v) === "undefined";
};
var isObject = function(v) {
return isType(v) === "object";
};
var isArray = function(v) {
return isType(v) === "array";
};
var isString = function(v) {
return isType(v) === "string";
};
var isNumber = function(v) {
return isType(v) === "number";
};
var isBoolean = function(v) {
return isType(v) === "boolean";
};
var isFunction = function(v) {
return isType(v) === "function";
};
var isRegExp = function(v) {
return isType(v) === "regexp";
};
var isPromise = function(v) {
return Boolean(v && typeof v.then === "function");
};
var TypeChecker = {
isNull: isNull,
isUndefined: isUndefined,
isObject: isObject,
isArray: isArray,
isString: isString,
isNumber: isNumber,
isBoolean: isBoolean,
isFunction: isFunction,
isRegExp: isRegExp,
isPromise: isPromise
};
function limit(fn, timespan) {
var pending = false;
return function() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
if (pending) return;
pending = true;
fn.apply(void 0, _to_consumable_array(args));
setTimeout(function() {
pending = false;
}, timespan);
};
}
// lib/utils/debounce.ts
function debounce(func, wait, options) {
var lastArgs, lastThis, maxWait, result, timerId, lastCallTime;
var lastInvokeTime = 0;
var leading = false;
var maxing = false;
var trailing = true;
var useRAF = !wait && wait !== 0 && window && typeof window.requestAnimationFrame === "function";
if (typeof func !== "function") {
throw new TypeError("Expected a function");
}
wait = +wait || 0;
if (options && isObject(options)) {
leading = !!options.leading;
maxing = "maxWait" in options;
maxWait = maxing ? Math.max(+options.maxWait || 0, wait) : maxWait;
trailing = "trailing" in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs;
var thisArg = lastThis;
lastArgs = lastThis = void 0;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function startTimer(pendingFunc, wait2) {
if (useRAF) {
window.cancelAnimationFrame(timerId);
return window.requestAnimationFrame(pendingFunc);
}
return setTimeout(pendingFunc, wait2);
}
function cancelTimer(id) {
if (useRAF) {
return window.cancelAnimationFrame(id);
}
clearTimeout(id);
}
function leadingEdge(time) {
lastInvokeTime = time;
timerId = startTimer(timerExpired, wait);
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime;
var timeSinceLastInvoke = time - lastInvokeTime;
var timeWaiting = wait - timeSinceLastCall;
return maxing ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime;
var timeSinceLastInvoke = time - lastInvokeTime;
return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
}
function timerExpired() {
var time = Date.now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
timerId = startTimer(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = void 0;
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = void 0;
return result;
}
function cancel() {
if (timerId !== void 0) {
cancelTimer(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = void 0;
}
function flush() {
return timerId === void 0 ? result : trailingEdge(Date.now());
}
function pending() {
return timerId !== void 0;
}
function debounced() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
var time = Date.now();
var isInvoking = shouldInvoke(time);
lastArgs = args;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === void 0) {
return leadingEdge(lastCallTime);
}
if (maxing) {
timerId = startTimer(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === void 0) {
timerId = startTimer(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
debounced.pending = pending;
return debounced;
}
var debounce_default = debounce;
// lib/utils/throttle.ts
function throttle(func, wait, options) {
var leading = true;
var trailing = true;
if (typeof func !== "function") {
throw new TypeError("Expected a function");
}
if (options && isObject(options)) {
leading = "leading" in options ? !!options.leading : leading;
trailing = "trailing" in options ? !!options.trailing : trailing;
}
return debounce_default(func, wait, {
leading: leading,
trailing: trailing,
maxWait: wait
});
}
var throttle_default = throttle;
// lib/utils/cache.ts
var cache = /* @__PURE__ */ new Map();
var setCache = function(key, value, cacheTime) {
var currentCache = cache.get(key);
if (currentCache === null || currentCache === void 0 ? void 0 : currentCache.timer) {
clearTimeout(currentCache.time);
}
var timer;
if (cacheTime > -1) {
timer = setTimeout(function() {
cache.delete(key);
}, cacheTime);
}
cache.set(key, _object_spread_props(_object_spread({}, value), {
timer: timer
}));
};
var getCache = function(key) {
return cache.get(key);
};
var clearCache = function(key) {
if (key) {
var cachedKeys = Array.isArray(key) ? key : [
key
];
cachedKeys.forEach(function(cachedKey) {
return cache.delete(cachedKey);
});
} else {
cache.clear();
}
};
// lib/utils/cacheSubscribe.ts
var listeners = {};
var trigger = function(key, data) {
if (listeners[key]) {
listeners[key].forEach(function(item) {
return item(data);
});
}
};
var subscribe = function(key, listener) {
if (!listeners[key]) {
listeners[key] = [];
}
listeners[key].push(listener);
return function() {
var index = listeners[key].indexOf(listener);
listeners[key].splice(index, 1);
};
};
// lib/usePlugins.ts
var import_vue3 = require("vue");
// lib/createInstance.ts
var import_vue2 = require("vue");
function createInstance(service, options) {
var _functionContext, _functionContext1;
var defaultData = options.defaultData, defaultParams = options.defaultParams, onBefore = options.onBefore, onRequest = options.onRequest, onSuccess = options.onSuccess, onError = options.onError, onFinally = options.onFinally, onCancel = options.onCancel, onCache = options.onCache;
var data = (0, import_vue2.isRef)(defaultData) ? defaultData : (0, import_vue2.ref)(defaultData);
var loading = (0, import_vue2.ref)(false);
var params = (0, import_vue2.ref)(defaultParams);
var pollingCount = (0, import_vue2.ref)(0);
var error = (0, import_vue2.shallowRef)();
var status = (0, import_vue2.ref)("pending");
var plugins = (0, import_vue2.ref)([]);
var count = (0, import_vue2.ref)(0);
var callPlugin = function(type) {
for(var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
args[_key - 1] = arguments[_key];
}
if (type == "onInit") {
var InstanceFn = plugins.value.map(function(i) {
return i.onInit;
}).filter(Boolean);
return {
servicePromise: composeMiddleware(InstanceFn, args[0])()
};
} else {
var _Object;
var res = plugins.value.map(function(i) {
var _i_type;
var _i_type1;
return (_i_type1 = i[type]) === null || _i_type1 === void 0 ? void 0 : (_i_type = _i_type1).call.apply(_i_type, [
i
].concat(_to_consumable_array(args)));
});
return (_Object = Object).assign.apply(_Object, [
{}
].concat(_to_consumable_array(res)));
}
};
var functionContext = {};
var resolveTick;
var tickPromise = new Promise(function(resolve) {
resolveTick = resolve;
});
functionContext.runAsync = /*#__PURE__*/ _async_to_generator(function() {
var _len, args, _key, currentCount, _callPlugin, _callPlugin_returnNow, returnNow, returnData, returnType, serverWrapper, servicePromise;
var _arguments = arguments;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
for(_len = _arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = _arguments[_key];
}
loading.value = true;
if (args === null || args === void 0 ? void 0 : args.length) {
params.value = args;
}
status.value = "pending";
count.value++;
currentCount = count.value;
_callPlugin = callPlugin("onBefore", args), _callPlugin_returnNow = _callPlugin.returnNow, returnNow = _callPlugin_returnNow === void 0 ? false : _callPlugin_returnNow, returnData = _callPlugin.returnData, returnType = _callPlugin.returnType;
if (returnData) {
data.value = returnData;
if (returnType === "cache") {
onCache === null || onCache === void 0 ? void 0 : onCache(returnData);
}
}
if (returnNow) {
loading.value = false;
status.value = "settled";
return [
2,
Promise.resolve(returnData)
];
}
onBefore === null || onBefore === void 0 ? void 0 : onBefore(args);
serverWrapper = function() {
return new Promise(function(resolve) {
return resolve(service.apply(void 0, _to_consumable_array(params.value)));
});
};
servicePromise = callPlugin("onInit", serverWrapper).servicePromise;
if (servicePromise) {
serverWrapper = function() {
return servicePromise;
};
}
return [
4,
serverWrapper().then(/*#__PURE__*/ function() {
var _ref = _async_to_generator(function(res) {
var result;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
onRequest === null || onRequest === void 0 ? void 0 : onRequest({
params: args,
response: res,
error: void 0,
abort: currentCount !== count.value
});
if (currentCount !== count.value) {
return [
2
];
}
error.value = void 0;
return [
4,
onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(res, args)
];
case 1:
result = _state.sent();
if (result) {
data.value = result;
} else {
data.value = res;
}
callPlugin("onSuccess", data.value, args);
return [
2,
data.value
];
}
});
});
return function(res) {
return _ref.apply(this, arguments);
};
}()).catch(function(err) {
onRequest === null || onRequest === void 0 ? void 0 : onRequest({
params: args,
response: void 0,
error: err,
abort: currentCount !== count.value
});
if (currentCount !== count.value) {
return;
}
error.value = err;
callPlugin("onError", err, args);
onError === null || onError === void 0 ? void 0 : onError(err, args);
throw err;
}).finally(function() {
loading.value = false;
status.value = "settled";
resolveTick();
if (currentCount !== count.value) {
return;
}
callPlugin("onFinally", args);
onFinally === null || onFinally === void 0 ? void 0 : onFinally();
})
];
case 1:
return [
2,
_state.sent()
];
}
});
});
functionContext.run = function() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
var _functionContext;
(_functionContext = functionContext).runAsync.apply(_functionContext, _to_consumable_array(args)).catch(function(err) {
!onError && console.error(err);
});
};
functionContext.cancel = function() {
count.value--;
loading.value = false;
callPlugin("onCancel");
onCancel === null || onCancel === void 0 ? void 0 : onCancel();
};
functionContext.refresh = function() {
return (_functionContext = functionContext).run.apply(_functionContext, _to_consumable_array(params.value));
};
functionContext.refreshAsync = function() {
return (_functionContext1 = functionContext).runAsync.apply(_functionContext1, _to_consumable_array(params.value));
};
functionContext.mutate = function(v) {
data.value = (v === null || v === void 0 ? void 0 : v.constructor) === Function ? v(data.value) : v;
callPlugin("onMutate", data.value);
};
var requestTick = /*#__PURE__*/ function() {
var _ref = _async_to_generator(function(callback) {
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
if (!(status.value === "pending")) return [
3,
2
];
return [
4,
tickPromise
];
case 1:
_state.sent();
_state.label = 2;
case 2:
callback === null || callback === void 0 ? void 0 : callback();
return [
2
];
}
});
});
return function requestTick(callback) {
return _ref.apply(this, arguments);
};
}();
return {
status: status,
data: data,
params: params,
pollingCount: pollingCount,
loading: loading,
error: error,
plugins: plugins,
requestTick: requestTick,
functionContext: functionContext
};
}
var createInstance_default = createInstance;
// lib/usePlugins.ts
function usePlugins(service) {
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, plugins = arguments.length > 2 ? arguments[2] : void 0;
var _options_manual = options.manual, manual = _options_manual === void 0 ? false : _options_manual, _options_defaultParams = options.defaultParams, defaultParams = _options_defaultParams === void 0 ? [] : _options_defaultParams, rest = _object_without_properties(options, [
"manual",
"defaultParams"
]);
var _defaultParams = unrefParms(defaultParams);
var fetchOptions = _object_spread({
manual: manual,
defaultParams: _defaultParams
}, rest);
var instance = createInstance_default(service, fetchOptions);
instance.plugins.value = plugins.map(function(p) {
return p(instance, fetchOptions);
});
if (!manual) {
var _instance_functionContext;
(_instance_functionContext = instance.functionContext).run.apply(_instance_functionContext, _to_consumable_array(_defaultParams));
}
(0, import_vue3.onUnmounted)(function() {
instance.functionContext.cancel();
});
return _object_spread({
status: instance.status,
loading: instance.loading,
data: instance.data,
error: instance.error,
params: instance.params,
pollingCount: instance.pollingCount,
requestTick: instance.requestTick
}, instance.functionContext);
}
var usePlugins_default = usePlugins;
// lib/plugins/useLoadingDelayPlugin.ts
var import_vue4 = require("vue");
var useLoadingDelayPlugin = function(instance, param) {
var loadingDelay = param.loadingDelay;
var timerRef = (0, import_vue4.ref)();
return {
onBefore: function onBefore() {
if (loadingDelay) {
instance.loading.value = false;
timerRef.value = useDelay(function() {
instance.loading.value = true;
}, loadingDelay);
}
},
onCancel: function onCancel() {
clearTimeout(timerRef.value);
},
onFinally: function onFinally() {
clearTimeout(timerRef.value);
}
};
};
var useLoadingDelayPlugin_default = useLoadingDelayPlugin;
// lib/plugins/usePollingPlugin.ts
var import_vue5 = require("vue");
var usePollingPlugin = function(instance, param) {
var pollingInterval = param.pollingInterval, _param_pollingErrorRetryCount = param.pollingErrorRetryCount, pollingErrorRetryCount = _param_pollingErrorRetryCount === void 0 ? -1 : _param_pollingErrorRetryCount;
var timerRef = (0, import_vue5.ref)();
var countRef = (0, import_vue5.ref)(0);
var pollingIntervalRef = (0, import_vue5.computed)(function() {
return (0, import_vue5.unref)(pollingInterval);
});
var polling = function(callback) {
var timerId;
var canPolling = !isNonZeroFalsy(pollingIntervalRef.value) && pollingIntervalRef.value >= 0;
if (!canPolling) {
return;
}
if (pollingErrorRetryCount === -1 || pollingErrorRetryCount !== -1 && countRef.value <= pollingErrorRetryCount) {
instance.pollingCount.value++;
timerId = useDelay(callback, pollingIntervalRef.value);
} else {
countRef.value = 0;
}
return function() {
return timerId && clearTimeout(timerId);
};
};
(0, import_vue5.watch)(pollingIntervalRef, function() {
if (timerRef.value) {
timerRef.value();
timerRef.value = polling(function() {
return instance.functionContext.refresh();
});
}
});
return {
onBefore: function onBefore() {
var _timerRef_value;
(_timerRef_value = timerRef.value) === null || _timerRef_value === void 0 ? void 0 : _timerRef_value.call(timerRef);
},
onCancel: function onCancel() {
var _timerRef_value;
(_timerRef_value = timerRef.value) === null || _timerRef_value === void 0 ? void 0 : _timerRef_value.call(timerRef);
instance.pollingCount.value = 0;
},
onSuccess: function onSuccess() {
countRef.value = 0;
},
onError: function onError() {
countRef.value++;
},
onFinally: function onFinally() {
timerRef.value = polling(function() {
return instance.functionContext.refresh();
});
}
};
};
var usePollingPlugin_default = usePollingPlugin;
// lib/plugins/useReadyPlugin.ts
var import_vue6 = require("vue");
var useReadyPlugin = function(instance, param) {
var _param_ready = param.ready, ready = _param_ready === void 0 ? true : _param_ready;
return {
onBefore: function onBefore() {
if (!(0, import_vue6.unref)(ready)) {
instance.loading.value = false;
return {
returnNow: true,
returnData: void 0
};
}
}
};
};
var useReadyPlugin_default = useReadyPlugin;
// lib/plugins/useRefreshDepsPlugin.ts
var import_vue7 = require("vue");
var useRefreshDepsPlugin = function(instance, param) {
var manual = param.manual, _param_refreshDeps = param.refreshDeps, refreshDeps = _param_refreshDeps === void 0 ? null : _param_refreshDeps, _param_refreshDepsParams = param.refreshDepsParams, refreshDepsParams = _param_refreshDepsParams === void 0 ? null : _param_refreshDepsParams;
if (refreshDeps) {
(0, import_vue7.watch)(refreshDeps, /*#__PURE__*/ _async_to_generator(function() {
var res, _instance_functionContext, _instance_functionContext1;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
if (!refreshDepsParams) return [
3,
4
];
if (!isFunction(refreshDepsParams)) return [
3,
2
];
return [
4,
refreshDepsParams()
];
case 1:
res = _state.sent();
if (res) {
;
(_instance_functionContext = instance.functionContext).run.apply(_instance_functionContext, _to_consumable_array(unrefParms(res)));
}
return [
3,
3
];
case 2:
(_instance_functionContext1 = instance.functionContext).run.apply(_instance_functionContext1, _to_consumable_array(unrefParms(refreshDepsParams)));
_state.label = 3;
case 3:
return [
3,
5
];
case 4:
!manual && instance.functionContext.refresh();
_state.label = 5;
case 5:
return [
2
];
}
});
}), {
deep: true
});
}
return {};
};
var useRefreshDepsPlugin_default = useRefreshDepsPlugin;
// lib/plugins/useDebouncePlugin.ts
var import_vue8 = require("vue");
var useDebouncePlugin = function(instance, param) {
var debounceWait = param.debounceWait, debounceOptions = param.debounceOptions;
var debouncedRef = (0, import_vue8.ref)();
(0, import_vue8.watchEffect)(function(onCleanup) {
if (!debounceWait) return;
var debounceWaitUnref = (0, import_vue8.unref)(debounceWait);
var debounceOptionsUnref = (0, import_vue8.unref)(debounceOptions);
var originRunAsync = instance.functionContext.runAsync;
debouncedRef.value = debounce_default(function(callback) {
return callback();
}, debounceWaitUnref, debounceOptionsUnref);
instance.functionContext.runAsync = function() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
return new Promise(function(resolve, reject) {
debouncedRef.value(function() {
originRunAsync.apply(void 0, _to_consumable_array(args)).then(resolve).catch(reject);
});
});
};
onCleanup(function() {
var _debouncedRef_value;
(_debouncedRef_value = debouncedRef.value) === null || _debouncedRef_value === void 0 ? void 0 : _debouncedRef_value.cancel();
instance.functionContext.runAsync = originRunAsync;
});
});
return {
onCancel: function onCancel() {
var _debouncedRef_value;
(_debouncedRef_value = debouncedRef.value) === null || _debouncedRef_value === void 0 ? void 0 : _debouncedRef_value.cancel();
}
};
};
var useDebouncePlugin_default = useDebouncePlugin;
// lib/plugins/useThrottlePlugin.ts
var import_vue9 = require("vue");
var useThrottlePlugin = function(instance, param) {
var throttleWait = param.throttleWait, throttleOptions = param.throttleOptions;
var throttleRef = (0, import_vue9.ref)();
(0, import_vue9.watchEffect)(function(onCleanup) {
if (!throttleWait) return;
var throttleWaitUnref = (0, import_vue9.unref)(throttleWait);
var throttleOptionsUnref = (0, import_vue9.unref)(throttleOptions);
var originRunAsync = instance.functionContext.runAsync;
throttleRef.value = throttle_default(function(callback) {
return callback();
}, throttleWaitUnref, throttleOptionsUnref);
instance.functionContext.runAsync = function() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
return new Promise(function(resolve, reject) {
throttleRef.value(function() {
originRunAsync.apply(void 0, _to_consumable_array(args)).then(resolve).catch(reject);
});
});
};
onCleanup(function() {
var _throttleRef_value;
(_throttleRef_value = throttleRef.value) === null || _throttleRef_value === void 0 ? void 0 : _throttleRef_value.cancel();
instance.functionContext.runAsync = originRunAsync;
});
});
return {
onCancel: function onCancel() {
var _throttleRef_value;
(_throttleRef_value = throttleRef.value) === null || _throttleRef_value === void 0 ? void 0 : _throttleRef_value.cancel();
}
};
};
var useThrottlePlugin_default = useThrottlePlugin;
// lib/plugins/useCachePlugin.ts
var import_vue10 = require("vue");
// lib/utils/cachePromise.ts
var cachePromise = /* @__PURE__ */ new Map();
var getCachePromise = function(cacheKey) {
return cachePromise.get(cacheKey);
};
var setCachePromise = function(cacheKey, promise) {
cachePromise.set(cacheKey, promise);
promise.then(function(res) {
cachePromise.delete(cacheKey);
return res;
}).catch(function() {
cachePromise.delete(cacheKey);
});
};
// lib/plugins/useCachePlugin.ts
var useCachePlugin = function(instance, param) {
var customCacheKey = param.cacheKey, _param_cacheTime = param.cacheTime, cacheTime = _param_cacheTime === void 0 ? 5 * 60 * 1e3 : _param_cacheTime, _param_staleTime = param.staleTime, staleTime = _param_staleTime === void 0 ? 0 : _param_staleTime, customGetCache = param.getCache, customSetCache = param.setCache, onCache = param.onCache;
if (!customCacheKey) {
return {};
}
var unSubscribe = function() {};
var currentPromise;
var cacheKey = isFunction(customCacheKey) ? customCacheKey : function() {
return customCacheKey;
};
var _setCache = function(key, cacheData, time) {
if (customSetCache) {
customSetCache(key, cacheData);
} else {
setCache(key, cacheData, time);
}
trigger(key, cacheData.data);
};
var _getCache = function(key) {
if (customGetCache) {
return customGetCache(key);
} else {
return getCache(key);
}
};
var cache2 = _getCache(cacheKey());
if (cache2 && Reflect.has(cache2, "data")) {
instance.data.value = cache2.data;
instance.params.value = cache2.params;
}
var setUnSubscribe = function(params) {
unSubscribe = subscribe(cacheKey(params), function(data) {
instance.data.value = data;
onCache === null || onCache === void 0 ? void 0 : onCache(data);
});
};
setUnSubscribe();
(0, import_vue10.onBeforeUnmount)(function() {
unSubscribe();
});
return {
onBefore: function onBefore(params) {
var _cacheKey = cacheKey(params);
var cache3 = _getCache(_cacheKey);
if (!cache3 || !Reflect.has(cache3, "data")) {
return {};
}
if (staleTime === -1 || /* @__PURE__ */ new Date().getTime() - cache3.time <= staleTime) {
return {
returnNow: true,
returnData: cache3.data,
returnType: "cache"
};
} else {
return {
returnData: cache3.data,
returnType: "cache"
};
}
},
onInit: function onInit(service) {
var params = instance.params.value;
var _cacheKey = cacheKey(params);
var servicePromise = getCachePromise(_cacheKey);
if (servicePromise && servicePromise !== currentPromise) {
return function() {
return servicePromise;
};
}
servicePromise = service();
currentPromise = servicePromise;
setCachePromise(_cacheKey, servicePromise);
return function() {
return servicePromise;
};
},
onSuccess: function onSuccess(data, params) {
var _cacheKey = cacheKey(params);
if (_cacheKey) {
unSubscribe();
_setCache(_cacheKey, {
data: data,
params: params,
time: /* @__PURE__ */ new Date().getTime()
}, cacheTime);
setUnSubscribe(params);
}
},
onMutate: function onMutate(data) {
var params = instance.params.value;
var _cacheKey = cacheKey(params);
if (_cacheKey) {
unSubscribe();
_setCache(_cacheKey, {
data: data,
params: params,
time: /* @__PURE__ */ new Date().getTime()
}, cacheTime);
setUnSubscribe(params);
}
}
};
};
var useCachePlugin_default = useCachePlugin;
// lib/plugins/useRetryPlugin.ts
var import_vue11 = require("vue");
var useRetryPlugin = function(instance, param) {
var retryCount = param.retryCount, retryInterval = param.retryInterval;
var timerRef = (0, import_vue11.ref)();
var countRef = (0, import_vue11.ref)(0);
var triggerByRetry = (0, import_vue11.ref)(false);
if (!retryCount) {
return {};
}
return {
onBefore: function onBefore() {
if (!triggerByRetry.value) {
countRef.value = 0;
}
triggerByRetry.value = false;
if (timerRef.value) {
clearTimeout(timerRef.value);
}
},
onSuccess: function onSuccess() {
countRef.value = 0;
},
onError: function onError() {
countRef.value += 1;
if (retryCount === -1 || countRef.value <= retryCount) {
var timeout = retryInterval !== null && retryInterval !== void 0 ? retryInterval : Math.min(1e3 * Math.pow(2, countRef.value), 3e4);
timerRef.value = setTimeout(function() {
triggerByRetry.value = true;
instance.functionContext.refresh();
}, timeout);
} else {
countRef.value = 0;
}
},
onCancel: function onCancel() {
countRef.value = 0;
if (timerRef.value) {
clearTimeout(timerRef.value);
}
}
};
};
var useRetryPlugin_default = useRetryPlugin;
// lib/plugins/useWindowVisibilityChangePlugin.ts
var import_vue12 = require("vue");
// lib/utils/subscribeVisivilityChange.ts
var refreshListeners = [];
var cancelListeners = [];
function refreshSubscribe(listener) {
refreshListeners.push(listener);
return function unsubscribe() {
var index = refreshListeners.indexOf(listener);
if (index > -1) {
refreshListeners.splice(index, 1);
}
};
}
function cancelSubscribe(listener) {
cancelListeners.push(listener);
return function unsubscribe() {
var index = cancelListeners.indexOf(listener);
if (index > -1) {
cancelListeners.splice(index, 1);
}
};
}
if ((_window = window) === null || _window === void 0 ? void 0 : _window.document) {
var revalidate = function() {
if (document.visibilityState === "visible") {
for(var i = 0; i < refreshListeners.length; i++){
var listener = refreshListeners[i];
listener();
}
} else {
for(var i1 = 0; i1 < cancelListeners.length; i1++){
var listener1 = cancelListeners[i1];
listener1();
}
}
};
window.addEventListener("visibilitychange", revalidate, false);
}
// lib/plugins/useWindowVisibilityChangePlugin.ts
var useWindowVisibilityChangePlugin = function(instance, param) {
var refreshOnWindowFocus = param.refreshOnWindowFocus, cancelOnWindowBlur = param.cancelOnWindowBlur, _param_focusTimespan = param.focusTimespan, focusTimespan = _param_focusTimespan === void 0 ? 5e3 : _param_focusTimespan;
var unRefreshSubscribeRef = (0, import_vue12.ref)();
var unCancelSubscribeRef = (0, import_vue12.ref)();
var stopSubscribe = function() {
var _unRefreshSubscribeRef_value, _unCancelSubscribeRef_value;
(_unRefreshSubscribeRef_value = unRefreshSubscribeRef.value) === null || _unRefreshSubscribeRef_value === void 0 ? void 0 : _unRefreshSubscribeRef_value.call(unRefreshSubscribeRef);
(_unCancelSubscribeRef_value = unCancelSubscribeRef.value) === null || _unCancelSubscribeRef_value === void 0 ? void 0 : _unCancelSubscribeRef_value.call(unCancelSubscribeRef);
};
(0, import_vue12.watchEffect)(function(onCleanup) {
if ((0, import_vue12.unref)(refreshOnWindowFocus)) {
var limitRefresh = limit(instance.functionContext.refresh.bind(instance.functionContext), (0, import_vue12.unref)(focusTimespan));
unRefreshSubscribeRef.value = refreshSubscribe(function() {
limitRefresh();
});
}
if ((0, import_vue12.unref)(cancelOnWindowBlur)) {
unCancelSubscribeRef.value = cancelSubscribe(instance.functionContext.cancel.bind(instance.functionContext));
}
onCleanup(stopSubscribe);
});
(0, import_vue12.onUnmounted)(function() {
stopSubscribe();
});
return {};
};
var useWindowVisibilityChangePlugin_default = useWindowVisibilityChangePlugin;
// lib/index.ts
var BasePlugins = [
useLoadingDelayPlugin_default,
usePollingPlugin_default,
useRefreshDepsPlugin_default,
useReadyPlugin_default,
useDebouncePlugin_default,
useThrottlePlugin_default,
useCachePlugin_default,
useRetryPlugin_default,
useWindowVisibilityChangePlugin_default
];
var Plugins = _to_consumable_array(BasePlugins);
function definePlugins(plugins) {
Plugins = _to_consumable_array(BasePlugins).concat(_to_consumable_array(plugins || []));
}
function useRequest(service, options, plugins) {
definePlugins(plugins);
return usePlugins_default(service, options, Plugins);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
TypeChecker: TypeChecker,
clearCache: clearCache,
debounce: debounce,
definePlugins: definePlugins,
getCac