UNPKG

@hocgin/hkit

Version:
777 lines (763 loc) 39.2 kB
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function (_e) { function e(_x6) { return _e.apply(this, arguments); } e.toString = function () { return _e.toString(); }; return e; }(function (e) { throw e; }), f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function (_e2) { function e(_x7) { return _e2.apply(this, arguments); } e.toString = function () { return _e2.toString(); }; return e; }(function (e) { didErr = true; err = e; }), f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(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(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(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 _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } 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 _asyncToGenerator(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 _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } 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); } import * as _PlatformKit from "./platform"; export { _PlatformKit as PlatformKit }; export var LangKit = /*#__PURE__*/function () { function LangKit() { _classCallCheck(this, LangKit); } _createClass(LangKit, null, [{ key: "substr", value: function substr(str, maxLength) { var s = "".concat(str); return s.substring(0, Math.min(s.length, maxLength)); } }, { key: "isExtension", value: function isExtension() { var protocol = "".concat(window.location.protocol); return !(protocol.startsWith('http') || protocol.startsWith('https')); } }, { key: "isObject", value: function isObject(value) { return value !== null && _typeof(value) === 'object'; } }, { key: "isFunction", value: function isFunction(value) { return typeof value === 'function'; } }, { key: "isString", value: function isString(value) { return typeof value === 'string'; } }, { key: "isBoolean", value: function isBoolean(value) { return typeof value === 'boolean'; } }, { key: "isNumber", value: function isNumber(value) { return typeof value === 'number'; } }, { key: "isUndef", value: function isUndef(value) { return typeof value === 'undefined'; } }, { key: "isArray", value: function isArray(arr) { return Array.isArray(arr); } /** * 合并值 * @param target 基准 * @param arg 高优先级 */ }, { key: "merge", value: function merge(target) { for (var _len = arguments.length, arg = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { arg[_key - 1] = arguments[_key]; } return arg.reduce(function (acc, cur) { return Object.keys(cur).reduce(function (subAcc, key) { var srcVal = cur[key]; if (LangKit.isObject(srcVal)) { subAcc[key] = LangKit.merge(subAcc[key] ? subAcc[key] : {}, srcVal); } else if (LangKit.isArray(srcVal)) { // series: [],下层数组直接赋值 subAcc[key] = srcVal.map(function (item, idx) { if (LangKit.isObject(item)) { var curAccVal = subAcc[key] ? subAcc[key] : []; return LangKit.merge(curAccVal[idx] ? curAccVal[idx] : {}, item); } else { return item; } }); } else { subAcc[key] = srcVal; } return subAcc; }, acc); }, target); } }, { key: "getHostname", value: function getHostname(url) { if (!url) return url; try { return new URL(url).host; } catch (e) { return undefined; } } }, { key: "openUrl", value: function openUrl(url) { var useNewTab = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; window.open(url, useNewTab ? '_blank' : '_self'); } }, { key: "tryCatch", value: function tryCatch(running) { return new Promise(function (resolve, reject) { try { running === null || running === void 0 || running(); resolve(); } catch (e) { reject(e); } }); } }, { key: "getUniqueId", value: function getUniqueId() { var randomPool = new Uint8Array(32); crypto.getRandomValues(randomPool); var hex = ''; for (var i = 0; i < randomPool.length; ++i) { hex += randomPool[i].toString(16); } return hex; } }, { key: "asyncToSync", value: function asyncToSync(async) { var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000; var state = 0; var error; var value; async().then(function (v) { state = 1; value = v; }).catch(function (e) { state = -1; error = e; }); var startTime = new Date().getTime(); while (state === 0) { if (new Date().getTime() - startTime > timeout) { throw new Error('异步转同步获取值超时了'); } } if (state === 1) { return value; } if (state === -1) { throw error; } throw new Error('unknown'); } }, { key: "syncToAsync", value: function () { var _syncToAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(run) { return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: return _context.abrupt("return", run === null || run === void 0 ? void 0 : run()); case 1: case "end": return _context.stop(); } }, _callee); })); function syncToAsync(_x) { return _syncToAsync.apply(this, arguments); } return syncToAsync; }() }, { key: "isBrowser", value: function isBrowser() { return !!(typeof window !== 'undefined' && window.document && window.document.createElement); } }, { key: "getBrowserId", value: function getBrowserId() { if (LangKit.isBrowser()) { try { var _window; return "".concat((_window = window) === null || _window === void 0 || (_window = _window.location) === null || _window === void 0 ? void 0 : _window.host); } catch (e) { console.warn('获取页面标识错误', e); } } return 'unknown'; } /** * to object * @param value * @param tryValue */ }, { key: "parseJSON", value: function parseJSON(value) { var tryValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; try { return this.JSONParse(value); } catch (e) { return tryValue; } } /** * to string * @param value * @param tryValue */ }, { key: "stringifyJSON", value: function stringifyJSON(value) { var tryValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; try { return this.JSONStringify(value); } catch (e) { return tryValue; } } }, { key: "JSONStringify", value: function JSONStringify(obj) { return JSON.stringify(obj, function (key, value) { // the replacer function is looking for some typed arrays. // If found, it replaces it by a trio if (value instanceof Int8Array || value instanceof Uint8Array || value instanceof Uint8ClampedArray || value instanceof Int16Array || value instanceof Uint16Array || value instanceof Int32Array || value instanceof Uint32Array || value instanceof Float32Array || value instanceof Float64Array) { return { constructor: value.constructor.name, data: Array.apply([], value), flag: LangKit.FLAG_TYPED_ARRAY }; } else if (value instanceof ArrayBuffer) { return { constructor: value.constructor.name, data: Array.apply([], new Uint8Array(value)), flag: LangKit.FLAG_TYPED_ARRAY }; } return value; }); } }, { key: "JSONParse", value: function JSONParse(str) { return JSON.parse(str, function (key, value) { // the reviver function looks for the typed array flag try { if ((value === null || value === void 0 ? void 0 : value.flag) === LangKit.FLAG_TYPED_ARRAY) { // console.log('value.data', value.data); if (value.constructor === 'ArrayBuffer') return new Uint8Array(value.data).buffer; if (value.constructor === 'Int8Array') return new Int8Array(value.data); if (value.constructor === 'Uint8Array') return new Uint8Array(value.data); if (value.constructor === 'Uint8ClampedArray') return new Uint8ClampedArray(value.data); if (value.constructor === 'Int16Array') return new Int16Array(value.data); if (value.constructor === 'Uint16Array') return new Uint16Array(value.data); if (value.constructor === 'Int32Array') return new Int32Array(value.data); if (value.constructor === 'Uint32Array') return new Uint32Array(value.data); if (value.constructor === 'Float32Array') return new Float32Array(value.data); if (value.constructor === 'Float64Array') return new Float64Array(value.data); // if found, we convert it back to a typed array } } catch (e) { console.warn('JSONParse.error', e); } // if flag not found no conversion is done return value; }); } }, { key: "toMap", value: function toMap() { var list = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var keyGet = arguments.length > 1 ? arguments[1] : undefined; var valueGet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function (e) { return e; }; var result = {}; list.forEach(function (item) { return result[keyGet === null || keyGet === void 0 ? void 0 : keyGet(item)] = valueGet === null || valueGet === void 0 ? void 0 : valueGet(item); }); return result; } /** * 返回值在上下限范围内 * @param val 值 * @param min 下限 * @param max 上限 */ }, { key: "clamp", value: function clamp(val, min, max) { if (val < min) return min; if (val > max) return max; return val; } /** * 拆分数组 * chunk([1,2,3,4,5], 2) => [[1,2], [3, 4], [5]] * @param array * @param length * @returns {Array} */ }, { key: "chunk", value: function chunk() { var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var length = arguments.length > 1 ? arguments[1] : undefined; var index = 0; var newArray = []; while (index < array.length) { newArray.push(array.slice(index, index += length)); } return newArray; } /** * 切割数据 * - 情况1 * slice([1,2,3,4], 2) * [1,2] * - 情况2 * slice([1], 2) * [1] * @param array * @param max * @returns {*} */ }, { key: "slice", value: function slice(array, max) { if (array.length < max) { max = array.length; } return array.slice(0, max); } /** * 去重 * @param array * @return {*[]} */ }, { key: "distinct", value: function distinct() { var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var keyFun = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (e) { return e; }; return Object.values(LangKit.toMap(array, keyFun, function (e) { return e; })); } /** * 删除指定位置 * @param array * @param index */ }, { key: "delete", value: function _delete() { var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var index = arguments.length > 1 ? arguments[1] : undefined; array.splice(index, 1); return array; } }, { key: "dynamicImport", value: function dynamicImport(importFunc) { var instance; return { get: function get() { return instance !== undefined ? instance : function () { return instance = importFunc(); }(); } }; } }, { key: "getFullFilename", value: function getFullFilename(url) { url = "".concat(url); if (url.includes('/')) { return url.substring(url.lastIndexOf('/') + 1); } return undefined; } }, { key: "toGroup", value: function toGroup(list, keyFn) { var result = new Map(); var _iterator = _createForOfIteratorHelper(list), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _result$get; var _item = _step.value; var key = keyFn(_item); var values = (_result$get = result.get(key)) !== null && _result$get !== void 0 ? _result$get : []; values.push(_item); result.set(key, values); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return result; } }, { key: "asyncFunc", value: function asyncFunc(v) { return /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(p) { return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: return _context2.abrupt("return", v); case 1: case "end": return _context2.stop(); } }, _callee2); })); return function (_x2) { return _ref.apply(this, arguments); }; }(); } /** * 对比版本 * @param prevVersion v1.0.0 or v1.0.0-beta or 1.0.0 * @param nextVersion v1.0.0 or v1.0.0-beta or 1.0.0 */ }, { key: "diffVersion", value: function diffVersion(prevVersion, nextVersion) { var _match$0$split$map, _match, _match$0$split$map2, _match2; var prevVsn = (_match$0$split$map = (_match = "".concat(prevVersion).match(/[\d|\\.]+/)) === null || _match === void 0 ? void 0 : _match[0].split('.').map(function (i) { var value = parseInt(i); return isNaN(value) ? 0 : value; })) !== null && _match$0$split$map !== void 0 ? _match$0$split$map : [], nextVsn = (_match$0$split$map2 = (_match2 = "".concat(nextVersion).match(/[\d|\\.]+/)) === null || _match2 === void 0 ? void 0 : _match2[0].split('.').map(function (i) { var value = parseInt(i); return isNaN(value) ? 0 : value; })) !== null && _match$0$split$map2 !== void 0 ? _match$0$split$map2 : []; // 旧版本 新版本, 2 var _values = []; if (prevVsn.length === nextVsn.length && prevVsn.length === 3) { for (var i = 0; i < prevVsn.length; i++) { _values.push(prevVsn[i] > nextVsn[i] ? -1 : prevVsn[i] < nextVsn[i] ? 1 : 0); } } else { _values = [0, 0, 0]; } return { values: function values() { return _values; }, // 当前为最新版本 isChanged: function isChanged() { return _values.some(function (e) { return e !== 0; }); }, // 当前为新版本 isNew: function isNew() { return _values.some(function (e) { return e > 0; }); }, // 当前为旧版本 isOld: function isOld() { return _values.some(function (e) { return e < 0; }); }, // 当前为大版本变更 isLargeUpdate: function isLargeUpdate() { var _values2; return ((_values2 = _values) === null || _values2 === void 0 ? void 0 : _values2[0]) > 0; }, // 当前为中版本变更 isMediumUpdate: function isMediumUpdate() { var _values3; return ((_values3 = _values) === null || _values3 === void 0 ? void 0 : _values3[1]) > 0; }, // 当前为小版本变更 isSmallUpdate: function isSmallUpdate() { var _values4; return ((_values4 = _values) === null || _values4 === void 0 ? void 0 : _values4[2]) > 0; } }; } /** * 关键字匹配 * @param keyword 输入的关键字 * @param fromKeywords 待匹配的关键字 */ }, { key: "inKeyword", value: function inKeyword(keyword) { if (keyword === undefined) { return true; } for (var _len2 = arguments.length, fromKeywords = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { fromKeywords[_key2 - 1] = arguments[_key2]; } return fromKeywords.map(function (e) { return "".concat(e).toLowerCase(); }).reduce(function (a, b) { return "".concat(a).concat(b); }).includes(keyword.toLowerCase()); } /** * 排序比较,数值大的在前面 * @param a * @param b */ }, { key: "sortDesc", value: function sortDesc(a, b) { if (a > b) { return -1; } else if (a < b) { return 1; } return 0; } /** * desc: 987654333321 * desc: true, false * @param a * @param b * @param isDesc */ }, { key: "sort", value: function sort(a, b) { var isDesc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var result = 0; if (typeof a === 'number') { result = a > b ? -1 : a < b ? 1 : 0; } else if (typeof a === 'boolean') { result = a && b === false ? -1 : !a && b === true ? 1 : 0; } else if (typeof a === 'string') { result = "".concat(a) === "".concat(b) ? 0 : "".concat(a) > "".concat(b) ? 1 : -1; } if (isDesc) { return result; } return !result; } }, { key: "getOrigin", value: function getOrigin(url) { if (!url) return undefined; var regex = /^(\w+:\/\/[^\/?#:]+)(?:[\/?#:]|$)/i; var match = url.match(regex); return match ? match[1] : undefined; } }, { key: "timeToPercent", value: function timeToPercent(time, duration) { if (duration === 0) { return 0; // For some reason would call this } return Math.floor(time * 100 / duration); } }, { key: "getTime", value: function getTime(ms) { if (!ms || isNaN(ms)) { ms = 0; } var s = 1000 * Math.round(ms / 1000); var d = new Date(s); return "".concat(d.getUTCMinutes(), ":").concat(String("0".concat(d.getUTCSeconds())).slice(-2)); } /** * 缓存 await LangKit.useCache(async () => 12, "key") * @param func 函数 * @param key key * @param expired 毫秒, 30秒 => 30 * 1000, -1=不过期 * @param forceExpired 是否强制过期 */ }, { key: "useLocalCache", value: (function () { var _useLocalCache = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(func, key) { var expired, forceExpired, prefix, cacheKey, serialize, deserialization, isNonExpired, get, set, clearExpired, value, _args6 = arguments; return _regeneratorRuntime().wrap(function _callee6$(_context6) { while (1) switch (_context6.prev = _context6.next) { case 0: expired = _args6.length > 2 && _args6[2] !== undefined ? _args6[2] : 30 * 1000; forceExpired = _args6.length > 3 && _args6[3] !== undefined ? _args6[3] : false; prefix = 'CACHE_'; cacheKey = "".concat(prefix).concat(key); serialize = function serialize(v) { return JSON.stringify(v); }, deserialization = function deserialization(v) { return JSON.parse(v); }; // true 未过期 isNonExpired = function isNonExpired(item) { var isNonExpired = (item === null || item === void 0 ? void 0 : item.expiredAt) === -1 || (item === null || item === void 0 ? void 0 : item.expiredAt) && Date.now() < (item === null || item === void 0 ? void 0 : item.expiredAt); return isNonExpired !== null && isNonExpired !== void 0 ? isNonExpired : false; }, get = /*#__PURE__*/function () { var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { var _item2; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: _context3.prev = 0; _item2 = deserialization(localStorage.getItem(cacheKey)); if (!(!forceExpired && isNonExpired(_item2))) { _context3.next = 4; break; } return _context3.abrupt("return", _item2 === null || _item2 === void 0 ? void 0 : _item2.value); case 4: _context3.next = 11; break; case 6: _context3.prev = 6; _context3.t0 = _context3["catch"](0); console.warn('【useCache】清除key', cacheKey, _context3.t0); _context3.next = 11; return localStorage.removeItem(cacheKey); case 11: return _context3.abrupt("return", undefined); case 12: case "end": return _context3.stop(); } }, _callee3, null, [[0, 6]]); })); return function get() { return _ref2.apply(this, arguments); }; }(), set = /*#__PURE__*/function () { var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(value) { return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: try { localStorage.setItem(cacheKey, serialize({ expiredAt: expired === -1 ? -1 : Date.now() + expired, value: value })); } catch (e) {} case 1: case "end": return _context4.stop(); } }, _callee4); })); return function set(_x5) { return _ref3.apply(this, arguments); }; }(), clearExpired = /*#__PURE__*/function () { var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() { var expiredKeys, _iterator2, _step2, expiredKey; return _regeneratorRuntime().wrap(function _callee5$(_context5) { while (1) switch (_context5.prev = _context5.next) { case 0: expiredKeys = Array.from({ length: localStorage.length }).map(function (_, i) { return localStorage.key(i); }).filter(function (key) { return key.startsWith(prefix); }).filter(function (key) { try { var object = deserialization(localStorage.getItem(key)); return !isNonExpired(object); } catch (e) { console.warn('【useCache】清理过期key异常', key, e); return true; } }); if (expiredKeys.length > 0) { _iterator2 = _createForOfIteratorHelper(expiredKeys); try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { expiredKey = _step2.value; localStorage.removeItem(expiredKey); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } case 2: case "end": return _context5.stop(); } }, _callee5); })); return function clearExpired() { return _ref4.apply(this, arguments); }; }(); _context6.next = 8; return get(); case 8: value = _context6.sent; if (value) { _context6.next = 15; break; } _context6.next = 12; return func(); case 12: value = _context6.sent; _context6.next = 15; return set(value); case 15: clearExpired(); return _context6.abrupt("return", value); case 17: case "end": return _context6.stop(); } }, _callee6); })); function useLocalCache(_x3, _x4) { return _useLocalCache.apply(this, arguments); } return useLocalCache; }()) }]); return LangKit; }(); _defineProperty(LangKit, "sleep", function () { var time = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3 * 1000; return new Promise(function (resolve) { return setTimeout(resolve, time); }); }); _defineProperty(LangKit, "FLAG_TYPED_ARRAY", 'FLAG_TYPED_ARRAY');