Hook Ajax

it can hook all ajax

目前为 2021-06-09 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.gf.qytechs.cn/scripts/426753/939010/Hook%20Ajax.js

  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.$hookAjax = {}));
  5. }(this, (function (exports) { 'use strict';
  6.  
  7. function _arrayWithHoles(arr) {
  8. if (Array.isArray(arr)) return arr;
  9. }
  10.  
  11. function _iterableToArrayLimit(arr, i) {
  12. var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]);
  13.  
  14. if (_i == null) return;
  15. var _arr = [];
  16. var _n = true;
  17. var _d = false;
  18.  
  19. var _s, _e;
  20.  
  21. try {
  22. for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
  23. _arr.push(_s.value);
  24.  
  25. if (i && _arr.length === i) break;
  26. }
  27. } catch (err) {
  28. _d = true;
  29. _e = err;
  30. } finally {
  31. try {
  32. if (!_n && _i["return"] != null) _i["return"]();
  33. } finally {
  34. if (_d) throw _e;
  35. }
  36. }
  37.  
  38. return _arr;
  39. }
  40.  
  41. function _arrayLikeToArray$2(arr, len) {
  42. if (len == null || len > arr.length) len = arr.length;
  43.  
  44. for (var i = 0, arr2 = new Array(len); i < len; i++) {
  45. arr2[i] = arr[i];
  46. }
  47.  
  48. return arr2;
  49. }
  50.  
  51. function _unsupportedIterableToArray$2(o, minLen) {
  52. if (!o) return;
  53. if (typeof o === "string") return _arrayLikeToArray$2(o, minLen);
  54. var n = Object.prototype.toString.call(o).slice(8, -1);
  55. if (n === "Object" && o.constructor) n = o.constructor.name;
  56. if (n === "Map" || n === "Set") return Array.from(o);
  57. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen);
  58. }
  59.  
  60. function _nonIterableRest() {
  61. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  62. }
  63.  
  64. function _slicedToArray(arr, i) {
  65. return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray$2(arr, i) || _nonIterableRest();
  66. }
  67.  
  68. function _assertThisInitialized$1(self) {
  69. if (self === void 0) {
  70. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  71. }
  72.  
  73. return self;
  74. }
  75.  
  76. function _setPrototypeOf(o, p) {
  77. _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  78. o.__proto__ = p;
  79. return o;
  80. };
  81.  
  82. return _setPrototypeOf(o, p);
  83. }
  84.  
  85. function _inherits$1(subClass, superClass) {
  86. if (typeof superClass !== "function" && superClass !== null) {
  87. throw new TypeError("Super expression must either be null or a function");
  88. }
  89.  
  90. subClass.prototype = Object.create(superClass && superClass.prototype, {
  91. constructor: {
  92. value: subClass,
  93. writable: true,
  94. configurable: true
  95. }
  96. });
  97. if (superClass) _setPrototypeOf(subClass, superClass);
  98. }
  99.  
  100. function _typeof(obj) {
  101. "@babel/helpers - typeof";
  102.  
  103. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  104. _typeof = function _typeof(obj) {
  105. return typeof obj;
  106. };
  107. } else {
  108. _typeof = function _typeof(obj) {
  109. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  110. };
  111. }
  112.  
  113. return _typeof(obj);
  114. }
  115.  
  116. function _possibleConstructorReturn$1(self, call) {
  117. if (call && (_typeof(call) === "object" || typeof call === "function")) {
  118. return call;
  119. }
  120.  
  121. return _assertThisInitialized$1(self);
  122. }
  123.  
  124. function _getPrototypeOf(o) {
  125. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  126. return o.__proto__ || Object.getPrototypeOf(o);
  127. };
  128. return _getPrototypeOf(o);
  129. }
  130.  
  131. function _classCallCheck$1(instance, Constructor) {
  132. if (!(instance instanceof Constructor)) {
  133. throw new TypeError("Cannot call a class as a function");
  134. }
  135. }
  136.  
  137. function _defineProperties$1(target, props) {
  138. for (var i = 0; i < props.length; i++) {
  139. var descriptor = props[i];
  140. descriptor.enumerable = descriptor.enumerable || false;
  141. descriptor.configurable = true;
  142. if ("value" in descriptor) descriptor.writable = true;
  143. Object.defineProperty(target, descriptor.key, descriptor);
  144. }
  145. }
  146.  
  147. function _createClass$1(Constructor, protoProps, staticProps) {
  148. if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
  149. if (staticProps) _defineProperties$1(Constructor, staticProps);
  150. return Constructor;
  151. }
  152.  
  153. function _defineProperty(obj, key, value) {
  154. if (key in obj) {
  155. Object.defineProperty(obj, key, {
  156. value: value,
  157. enumerable: true,
  158. configurable: true,
  159. writable: true
  160. });
  161. } else {
  162. obj[key] = value;
  163. }
  164.  
  165. return obj;
  166. }
  167.  
  168. function _classCallCheck(instance, Constructor) {
  169. if (!(instance instanceof Constructor)) {
  170. throw new TypeError("Cannot call a class as a function");
  171. }
  172. }
  173.  
  174. var classCallCheck = _classCallCheck;
  175.  
  176. function createCommonjsModule(fn, module) {
  177. return module = {
  178. exports: {}
  179. }, fn(module, module.exports), module.exports;
  180. }
  181.  
  182. var setPrototypeOf = createCommonjsModule(function (module) {
  183. function _setPrototypeOf(o, p) {
  184. module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  185. o.__proto__ = p;
  186. return o;
  187. };
  188.  
  189. return _setPrototypeOf(o, p);
  190. }
  191.  
  192. module.exports = _setPrototypeOf;
  193. });
  194.  
  195. function _inherits(subClass, superClass) {
  196. if (typeof superClass !== "function" && superClass !== null) {
  197. throw new TypeError("Super expression must either be null or a function");
  198. }
  199.  
  200. subClass.prototype = Object.create(superClass && superClass.prototype, {
  201. constructor: {
  202. value: subClass,
  203. writable: true,
  204. configurable: true
  205. }
  206. });
  207. if (superClass) setPrototypeOf(subClass, superClass);
  208. }
  209.  
  210. var inherits = _inherits;
  211.  
  212. var _typeof_1 = createCommonjsModule(function (module) {
  213. function _typeof(obj) {
  214. "@babel/helpers - typeof";
  215.  
  216. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  217. module.exports = _typeof = function _typeof(obj) {
  218. return typeof obj;
  219. };
  220. } else {
  221. module.exports = _typeof = function _typeof(obj) {
  222. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  223. };
  224. }
  225.  
  226. return _typeof(obj);
  227. }
  228.  
  229. module.exports = _typeof;
  230. });
  231.  
  232. function _assertThisInitialized(self) {
  233. if (self === void 0) {
  234. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  235. }
  236.  
  237. return self;
  238. }
  239.  
  240. var assertThisInitialized = _assertThisInitialized;
  241.  
  242. function _possibleConstructorReturn(self, call) {
  243. if (call && (_typeof_1(call) === "object" || typeof call === "function")) {
  244. return call;
  245. }
  246.  
  247. return assertThisInitialized(self);
  248. }
  249.  
  250. var possibleConstructorReturn = _possibleConstructorReturn;
  251. var getPrototypeOf = createCommonjsModule(function (module) {
  252. function _getPrototypeOf(o) {
  253. module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  254. return o.__proto__ || Object.getPrototypeOf(o);
  255. };
  256. return _getPrototypeOf(o);
  257. }
  258.  
  259. module.exports = _getPrototypeOf;
  260. });
  261.  
  262. function _arrayLikeToArray$1(arr, len) {
  263. if (len == null || len > arr.length) len = arr.length;
  264.  
  265. for (var i = 0, arr2 = new Array(len); i < len; i++) {
  266. arr2[i] = arr[i];
  267. }
  268.  
  269. return arr2;
  270. }
  271.  
  272. var arrayLikeToArray = _arrayLikeToArray$1;
  273.  
  274. function _arrayWithoutHoles(arr) {
  275. if (Array.isArray(arr)) return arrayLikeToArray(arr);
  276. }
  277.  
  278. var arrayWithoutHoles = _arrayWithoutHoles;
  279.  
  280. function _iterableToArray(iter) {
  281. if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
  282. }
  283.  
  284. var iterableToArray = _iterableToArray;
  285.  
  286. function _unsupportedIterableToArray$1(o, minLen) {
  287. if (!o) return;
  288. if (typeof o === "string") return arrayLikeToArray(o, minLen);
  289. var n = Object.prototype.toString.call(o).slice(8, -1);
  290. if (n === "Object" && o.constructor) n = o.constructor.name;
  291. if (n === "Map" || n === "Set") return Array.from(o);
  292. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
  293. }
  294.  
  295. var unsupportedIterableToArray = _unsupportedIterableToArray$1;
  296.  
  297. function _nonIterableSpread() {
  298. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  299. }
  300.  
  301. var nonIterableSpread = _nonIterableSpread;
  302.  
  303. function _toConsumableArray(arr) {
  304. return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
  305. }
  306.  
  307. var toConsumableArray = _toConsumableArray;
  308.  
  309. function _defineProperties(target, props) {
  310. for (var i = 0; i < props.length; i++) {
  311. var descriptor = props[i];
  312. descriptor.enumerable = descriptor.enumerable || false;
  313. descriptor.configurable = true;
  314. if ("value" in descriptor) descriptor.writable = true;
  315. Object.defineProperty(target, descriptor.key, descriptor);
  316. }
  317. }
  318.  
  319. function _createClass(Constructor, protoProps, staticProps) {
  320. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  321. if (staticProps) _defineProperties(Constructor, staticProps);
  322. return Constructor;
  323. }
  324.  
  325. var createClass = _createClass;
  326.  
  327. function _superPropBase(object, property) {
  328. while (!Object.prototype.hasOwnProperty.call(object, property)) {
  329. object = getPrototypeOf(object);
  330. if (object === null) break;
  331. }
  332.  
  333. return object;
  334. }
  335.  
  336. var superPropBase = _superPropBase;
  337. var get = createCommonjsModule(function (module) {
  338. function _get(target, property, receiver) {
  339. if (typeof Reflect !== "undefined" && Reflect.get) {
  340. module.exports = _get = Reflect.get;
  341. } else {
  342. module.exports = _get = function _get(target, property, receiver) {
  343. var base = superPropBase(target, property);
  344. if (!base) return;
  345. var desc = Object.getOwnPropertyDescriptor(base, property);
  346.  
  347. if (desc.get) {
  348. return desc.get.call(receiver);
  349. }
  350.  
  351. return desc.value;
  352. };
  353. }
  354.  
  355. return _get(target, property, receiver || target);
  356. }
  357.  
  358. module.exports = _get;
  359. });
  360.  
  361. function _isNativeFunction(fn) {
  362. return Function.toString.call(fn).indexOf("[native code]") !== -1;
  363. }
  364.  
  365. var isNativeFunction = _isNativeFunction;
  366.  
  367. function _isNativeReflectConstruct$1() {
  368. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  369. if (Reflect.construct.sham) return false;
  370. if (typeof Proxy === "function") return true;
  371.  
  372. try {
  373. Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
  374. return true;
  375. } catch (e) {
  376. return false;
  377. }
  378. }
  379.  
  380. var isNativeReflectConstruct = _isNativeReflectConstruct$1;
  381. var construct = createCommonjsModule(function (module) {
  382. function _construct(Parent, args, Class) {
  383. if (isNativeReflectConstruct()) {
  384. module.exports = _construct = Reflect.construct;
  385. } else {
  386. module.exports = _construct = function _construct(Parent, args, Class) {
  387. var a = [null];
  388. a.push.apply(a, args);
  389. var Constructor = Function.bind.apply(Parent, a);
  390. var instance = new Constructor();
  391. if (Class) setPrototypeOf(instance, Class.prototype);
  392. return instance;
  393. };
  394. }
  395.  
  396. return _construct.apply(null, arguments);
  397. }
  398.  
  399. module.exports = _construct;
  400. });
  401. var wrapNativeSuper = createCommonjsModule(function (module) {
  402. function _wrapNativeSuper(Class) {
  403. var _cache = typeof Map === "function" ? new Map() : undefined;
  404.  
  405. module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) {
  406. if (Class === null || !isNativeFunction(Class)) return Class;
  407.  
  408. if (typeof Class !== "function") {
  409. throw new TypeError("Super expression must either be null or a function");
  410. }
  411.  
  412. if (typeof _cache !== "undefined") {
  413. if (_cache.has(Class)) return _cache.get(Class);
  414.  
  415. _cache.set(Class, Wrapper);
  416. }
  417.  
  418. function Wrapper() {
  419. return construct(Class, arguments, getPrototypeOf(this).constructor);
  420. }
  421.  
  422. Wrapper.prototype = Object.create(Class.prototype, {
  423. constructor: {
  424. value: Wrapper,
  425. enumerable: false,
  426. writable: true,
  427. configurable: true
  428. }
  429. });
  430. return setPrototypeOf(Wrapper, Class);
  431. };
  432.  
  433. return _wrapNativeSuper(Class);
  434. }
  435.  
  436. module.exports = _wrapNativeSuper;
  437. });
  438. /**
  439. * Assign the target's prototype to the origin object
  440. * @param origin{Object} The origin object
  441. * @param target{Object} The target object
  442. * @param initMethod{string=} The method name will be called from origin while assigned, default to be 'initAssign'
  443. * @return {*} The origin object assigned
  444. */
  445.  
  446. function assignInstance(origin, target) {
  447. var initMethod = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'initAssign';
  448. var prototype = Object.getPrototypeOf(target);
  449. Object.setPrototypeOf(origin, prototype);
  450.  
  451. if (typeof prototype[initMethod] === 'function') {
  452. prototype[initMethod].call(origin, target);
  453. }
  454.  
  455. return origin;
  456. }
  457. /**
  458. * Assign the target class prototype to the origin object
  459. * @param origin{Object} The origin object
  460. * @param targetType{Function} The target class object
  461. * @param initMethod{string=} The method name will be called from origin while assigned, default to be 'initAssign'
  462. * @return {*} The origin object assigned
  463. */
  464.  
  465.  
  466. function assignPrototype(origin, targetType) {
  467. var initMethod = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'initAssign';
  468. var prototype = targetType.prototype;
  469. Object.setPrototypeOf(origin, prototype);
  470.  
  471. if (typeof prototype[initMethod] === 'function') {
  472. prototype[initMethod].call(origin);
  473. }
  474.  
  475. return origin;
  476. }
  477.  
  478. function createCommonjsModule$1(fn, module) {
  479. return module = {
  480. exports: {}
  481. }, fn(module, module.exports), module.exports;
  482. }
  483.  
  484. createCommonjsModule$1(function (module) {
  485. function _typeof(obj) {
  486. "@babel/helpers - typeof";
  487.  
  488. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  489. module.exports = _typeof = function _typeof(obj) {
  490. return typeof obj;
  491. };
  492. } else {
  493. module.exports = _typeof = function _typeof(obj) {
  494. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  495. };
  496. }
  497.  
  498. return _typeof(obj);
  499. }
  500.  
  501. module.exports = _typeof;
  502. });
  503. /**
  504. * Get an unique id
  505. * @param length{number=} the id length
  506. * @return {string} the unique id
  507. */
  508.  
  509. function genID(length) {
  510. return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
  511. }
  512. /**
  513. * Assign the origin's property to target object by property key.
  514. * @param target The target object
  515. * @param origin The origin object
  516. * @param key The property key
  517. * @param defaultValue{*=} If there's not existing value from origin object, the default
  518. */
  519.  
  520.  
  521. function assignProperty(target, origin, key, defaultValue) {
  522. if (origin && origin[key] !== undefined) {
  523. target[key] = origin[key];
  524. } else if (typeof defaultValue === 'function') {
  525. target[key] = defaultValue();
  526. }
  527. }
  528.  
  529. function _createSuper$1(Derived) {
  530. var hasNativeReflectConstruct = _isNativeReflectConstruct$1$1();
  531.  
  532. return function _createSuperInternal() {
  533. var Super = getPrototypeOf(Derived),
  534. result;
  535.  
  536. if (hasNativeReflectConstruct) {
  537. var NewTarget = getPrototypeOf(this).constructor;
  538. result = Reflect.construct(Super, arguments, NewTarget);
  539. } else {
  540. result = Super.apply(this, arguments);
  541. }
  542.  
  543. return possibleConstructorReturn(this, result);
  544. };
  545. }
  546.  
  547. function _isNativeReflectConstruct$1$1() {
  548. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  549. if (Reflect.construct.sham) return false;
  550. if (typeof Proxy === "function") return true;
  551.  
  552. try {
  553. Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
  554. return true;
  555. } catch (e) {
  556. return false;
  557. }
  558. }
  559. /**
  560. * @class The class included the function's extra methods
  561. * @augments Function
  562. * @property id {string} the id only for this instance
  563. * @property uniqueId {string} the id for the chain of method called
  564. */
  565.  
  566.  
  567. var FuncInstance = /*#__PURE__*/function (_Function) {
  568. inherits(FuncInstance, _Function);
  569.  
  570. var _super = _createSuper$1(FuncInstance);
  571.  
  572. function FuncInstance() {
  573. classCallCheck(this, FuncInstance);
  574. return _super.apply(this, arguments);
  575. }
  576.  
  577. createClass(FuncInstance, [{
  578. key: "initAssign",
  579.  
  580. /**
  581. * Just a callback with the resolve params
  582. * @callback resolveCallback
  583. * @param res{*=} the callback param
  584. */
  585.  
  586. /**
  587. * Callback when using before method
  588. * @callback beforeCallback
  589. * @param params{Object=} Params for before callback
  590. * @param params.origin{Function=} The origin method of the AOP method
  591. * @param params.args{Array<*>=} The args of the AOP method
  592. * @param params.preventDefault{Function=} The method if called will prevent method executing,
  593. * and using this callback return value instead of APO method return value
  594. * @param params.trans{Object=} The temp storage place from the APO method, you can set the property in the before method
  595. * @return {*} If preventDefault event called, the return value will be the AOP method's return value
  596. */
  597.  
  598. /**
  599. * Callback when using after method
  600. * @callback afterCallback
  601. * @param params{Object=} Params for after callback
  602. * @param params.origin{Function=} The origin method of the AOP method
  603. * @param params.args{Array<*>=} The args of the AOP method
  604. * @param params.lastValue{*=} The value returned from AOP method by default
  605. * @param params.trans{Object=} The temp storage place from the APO method,
  606. * you can get the property from before method, or set the property
  607. */
  608.  
  609. /**
  610. * Callback when using error method
  611. * @callback errorCallback
  612. * @param params{Object=} Params for error callback
  613. * @param params.origin{Function=} The origin method of the AOP method
  614. * @param params.args{Array<*>=} The args of the AOP method
  615. * @param params.error{*=} The error object | error message
  616. * @param params.resolve{resolveCallback=} When this method called the AOP method will use the params as return value
  617. * @param params.trans{Object=} The temp storage place from the APO method,
  618. * you can get the property from before or after method
  619. */
  620.  
  621. /**
  622. * @private
  623. * @param target{FuncInstance}
  624. */
  625. value: function initAssign(target) {
  626. this.id = genID(7); // all func from FuncInstance has the uniqueId
  627.  
  628. assignProperty(this, target, 'uniqueId', function () {
  629. return genID(7);
  630. });
  631. }
  632. /**
  633. * For a given function, creates a bound function that has the same body as the original function.
  634. * The this object of the bound function is associated with the specified object, and has the specified initial parameters.
  635. * @param context An object to which the this keyword can refer inside the new function.
  636. * @param argArray {Array=} A list of arguments to be passed to the new function.
  637. * @return {FuncInstance | Function}
  638. */
  639.  
  640. }, {
  641. key: "bind",
  642. value: function bind(context) {
  643. var _get2;
  644.  
  645. var argArray = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  646. return assignInstance((_get2 = get(getPrototypeOf(FuncInstance.prototype), "bind", this)).call.apply(_get2, [this, context].concat(toConsumableArray(argArray))), this);
  647. }
  648. /**
  649. * Making something called before the AOP method
  650. * @param cb{beforeCallback} The callback called before the AOP method calling
  651. * @param adaptAsync{boolean=} If equals true & callback returned a Promise result,
  652. * the AOP method will called after the Promise finished.
  653. * @return {FuncInstance|Function}
  654. */
  655.  
  656. }, {
  657. key: "before",
  658. value: function before(cb) {
  659. var adaptAsync = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  660. return this.surround({
  661. before: cb,
  662. adaptAsync: adaptAsync
  663. });
  664. }
  665. /**
  666. * Making something called after the AOP method
  667. * @param cb{afterCallback} The callback called after the AOP method calling
  668. * @param adaptAsync{boolean=} If equals true & AOP method returned a Promise result,
  669. * the after method will called after the Promise finished.
  670. * @return {FuncInstance|Function}
  671. */
  672.  
  673. }, {
  674. key: "after",
  675. value: function after(cb) {
  676. var adaptAsync = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  677. return this.surround({
  678. after: cb,
  679. adaptAsync: adaptAsync
  680. });
  681. }
  682. /**
  683. * Making something called surround the APO method
  684. * @param options{Object} options for surround method
  685. * @param options.before{beforeCallback=} The callback called before the AOP method calling
  686. * @param options.after{afterCallback=} The callback called after the AOP method calling
  687. * @param options.onError{errorCallback=} The callback called while an error happening from the AOP method calling
  688. * @param options.adaptAsync{boolean=} If equals TRUE, all surround methods will waiting the last Promise result
  689. * @return {FuncInstance|Function}
  690. */
  691.  
  692. }, {
  693. key: "surround",
  694. value: function surround(_ref) {
  695. var _ref$before = _ref.before,
  696. before = _ref$before === void 0 ? undefined : _ref$before,
  697. _ref$after = _ref.after,
  698. after = _ref$after === void 0 ? undefined : _ref$after,
  699. _ref$onError = _ref.onError,
  700. onError = _ref$onError === void 0 ? undefined : _ref$onError,
  701. _ref$adaptAsync = _ref.adaptAsync,
  702. adaptAsync = _ref$adaptAsync === void 0 ? false : _ref$adaptAsync;
  703. var lastOrigin = this;
  704.  
  705. if (typeof lastOrigin !== 'function') {
  706. return lastOrigin;
  707. }
  708.  
  709. return assignInstance(function () {
  710. var _this2 = this;
  711.  
  712. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  713. args[_key] = arguments[_key];
  714. }
  715.  
  716. var trans = {};
  717. var baseParams = {
  718. origin: lastOrigin,
  719. args: args,
  720. trans: trans
  721. };
  722. var validErrorMethod = typeof onError === 'function';
  723.  
  724. try {
  725. var _preventDefault = false; // parsing before
  726.  
  727. var beforeResult;
  728.  
  729. if (typeof before === 'function') {
  730. beforeResult = before.call(this, Object.assign({}, baseParams, {
  731. preventDefault: function preventDefault() {
  732. _preventDefault = true;
  733. }
  734. }));
  735.  
  736. if (_preventDefault) {
  737. return beforeResult;
  738. }
  739. }
  740.  
  741. var returnValue;
  742.  
  743. if (beforeResult instanceof Promise && adaptAsync) {
  744. returnValue = beforeResult.then(function () {
  745. return lastOrigin.apply(_this2, args);
  746. });
  747. } else {
  748. returnValue = lastOrigin.apply(this, args);
  749. } // parsing origin
  750.  
  751.  
  752. if (typeof after === 'function') {
  753. if (returnValue instanceof Promise && adaptAsync) {
  754. returnValue = returnValue.then(function (value) {
  755. return after.call(_this2, Object.assign({}, baseParams, {
  756. lastValue: value
  757. }));
  758. });
  759. } else {
  760. returnValue = after.call(this, Object.assign({}, baseParams, {
  761. lastValue: returnValue
  762. }));
  763. }
  764. }
  765.  
  766. if (returnValue instanceof Promise && adaptAsync && validErrorMethod) {
  767. return returnValue["catch"](function (error) {
  768. var isSolved = false;
  769. var message = '';
  770.  
  771. var resolve = function resolve(msg) {
  772. message = msg;
  773. isSolved = true;
  774. };
  775.  
  776. return Promise.resolve(onError.call(_this2, Object.assign({}, baseParams, {
  777. error: error,
  778. resolve: resolve
  779. }))).then(function (solution) {
  780. if (!isSolved) {
  781. throw error;
  782. }
  783.  
  784. return message || solution;
  785. });
  786. });
  787. }
  788.  
  789. return returnValue;
  790. } catch (error) {
  791. if (!validErrorMethod) {
  792. throw error;
  793. }
  794.  
  795. var isSolved = false;
  796. var message = '';
  797.  
  798. var resolve = function resolve(msg) {
  799. message = msg;
  800. isSolved = true;
  801. };
  802.  
  803. var result = onError.call(this, Object.assign({}, baseParams, {
  804. error: error,
  805. resolve: resolve
  806. }));
  807.  
  808. if (!isSolved) {
  809. throw error;
  810. }
  811.  
  812. return message || result;
  813. }
  814. }, this);
  815. }
  816. /**
  817. * Making an async method call then method
  818. * @param cb{resolveCallback=}
  819. * @return {FuncInstance|Function}
  820. */
  821.  
  822. }, {
  823. key: "then",
  824. value: function then(cb) {
  825. var _this = this;
  826.  
  827. return assignInstance(function () {
  828. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  829. args[_key2] = arguments[_key2];
  830. }
  831.  
  832. var result = _this.apply(this, args);
  833.  
  834. return Promise.resolve(result).then(cb);
  835. }, this);
  836. }
  837. /**
  838. * Making an async method call catch method
  839. * @param cb{resolveCallback=}
  840. * @return {FuncInstance|Function}
  841. */
  842.  
  843. }, {
  844. key: "catch",
  845. value: function _catch(cb) {
  846. var _this = this;
  847.  
  848. return assignInstance(function () {
  849. var result;
  850.  
  851. try {
  852. for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  853. args[_key3] = arguments[_key3];
  854. }
  855.  
  856. result = _this.apply(this, args);
  857.  
  858. if (result instanceof Promise) {
  859. return result["catch"](cb);
  860. }
  861. } catch (e) {
  862. result = cb.call(this, e);
  863. }
  864.  
  865. return result;
  866. }, this);
  867. }
  868. /**
  869. * Making an async method call finally method
  870. * @param cb{resolveCallback=}
  871. * @return {FuncInstance|Function}
  872. */
  873.  
  874. }, {
  875. key: "finally",
  876. value: function _finally(cb) {
  877. var _this = this;
  878.  
  879. return assignInstance(function () {
  880. var doIgnoreCallback = function doIgnoreCallback() {
  881. try {
  882. cb.call(this);
  883. } catch (e) {// ignore
  884. }
  885. };
  886.  
  887. try {
  888. for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  889. args[_key4] = arguments[_key4];
  890. }
  891.  
  892. var result = _this.apply(this, args);
  893.  
  894. if (result instanceof Promise) {
  895. if (typeof result["finally"] === 'function') {
  896. return result["finally"](function () {
  897. return doIgnoreCallback();
  898. });
  899. }
  900.  
  901. return result["catch"](function (e) {
  902. return e;
  903. }).then(function (e) {
  904. doIgnoreCallback();
  905.  
  906. if (e instanceof Error) {
  907. throw e;
  908. }
  909. });
  910. } else {
  911. doIgnoreCallback();
  912. }
  913.  
  914. return result;
  915. } catch (e) {
  916. doIgnoreCallback();
  917. throw e;
  918. }
  919. }, this);
  920. }
  921. /**
  922. * Making result method could using all of registered functions
  923. * @param funcMap {Object} An object with function property, those function will be used as callable method for FuncInstance
  924. * @return {FuncInstance|Function}
  925. */
  926.  
  927. }, {
  928. key: "register",
  929. value: function register() {
  930. var funcMap = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  931. return this.registerClass(function (instance) {
  932. var result = /*#__PURE__*/function (_instance) {
  933. inherits(result, _instance);
  934.  
  935. var _super2 = _createSuper$1(result);
  936.  
  937. function result() {
  938. classCallCheck(this, result);
  939. return _super2.apply(this, arguments);
  940. }
  941.  
  942. return result;
  943. }(instance);
  944.  
  945. Object.assign(result.prototype, funcMap);
  946. return result;
  947. });
  948. }
  949. /**
  950. * Register for registerClass function
  951. * @callback funcInstanceRegister
  952. * @param instanceType {FuncInstance|Function=} Latest one class extends @link{FuncInstance}
  953. * @return {FuncInstance|Function} Result func instance, must extends params - `instanceType`
  954. */
  955.  
  956. /**
  957. * Making result method could using all of registered functions
  958. * @param register{funcInstanceRegister}
  959. * @return {FuncInstance|Function}
  960. */
  961.  
  962. }, {
  963. key: "registerClass",
  964. value: function registerClass(register) {
  965. var instanceType = register(this.constructor);
  966. var resultFunc = this.bind(this);
  967. Object.setPrototypeOf(resultFunc, instanceType.prototype);
  968.  
  969. if (typeof instanceType !== 'function' || !(resultFunc instanceof this.constructor)) {
  970. throw new Error('Registered class must extend FunctionInstance');
  971. }
  972.  
  973. return resultFunc;
  974. }
  975. }]);
  976. return FuncInstance;
  977. }( /*#__PURE__*/wrapNativeSuper(Function));
  978.  
  979. var defaultOptions = {
  980. instanceType: FuncInstance
  981. };
  982. /**
  983. * Making the function to be FuncInstance
  984. * @param func {Function} The function to convert
  985. * @param options {Object=} The options for this giving
  986. * @param options.instanceType {Function=} The class type of instance default to be FuncInstance
  987. * @return {FuncInstance | Function}
  988. */
  989.  
  990. function give(func, options) {
  991. options = Object.assign({}, defaultOptions, options);
  992.  
  993. var resultFunc = function resultFunc() {
  994. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  995. args[_key] = arguments[_key];
  996. }
  997.  
  998. return (func || function () {
  999. return undefined;
  1000. }).apply(this, args);
  1001. };
  1002.  
  1003. assignPrototype(resultFunc, options.instanceType);
  1004. return resultFunc;
  1005. }
  1006. /**
  1007. * How to hook method
  1008. * @callback doHookThings
  1009. * @param method {FuncInstance}
  1010. * @return {Function} result function
  1011. */
  1012.  
  1013. /**
  1014. * @typedef HookOptions
  1015. * @type {{protect: boolean, syncDesc: boolean, native: boolean}}
  1016. */
  1017.  
  1018.  
  1019. var defaultHookOptions = {
  1020. protect: false,
  1021. syncDesc: true,
  1022. "native": false
  1023. };
  1024. var defineProperty = Object.defineProperty;
  1025. var defineProperties = Object.defineProperties;
  1026. /**
  1027. * Hook a method
  1028. * @param parent {Object}
  1029. * @param methodName {string|Symbol}
  1030. * @param doHookThings {doHookThings}
  1031. * @param options {HookOptions=}
  1032. * @return {void}
  1033. */
  1034.  
  1035. function hook(parent, methodName, doHookThings) {
  1036. var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  1037. var origin = parent[methodName];
  1038.  
  1039. if (typeof origin !== 'function') {
  1040. return;
  1041. }
  1042.  
  1043. var hookOptions = Object.assign({}, defaultHookOptions, options);
  1044. var _native = hookOptions["native"];
  1045. var targetMethod = doHookThings(_native ? origin : give(origin));
  1046. parent[methodName] = _native ? targetMethod : function () {
  1047. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  1048. args[_key] = arguments[_key];
  1049. }
  1050.  
  1051. try {
  1052. return targetMethod.apply(this, args);
  1053. } catch (e) {
  1054. console.warn('[Hook JS]', 'Hooks running lost once.');
  1055. return origin.apply(this, args);
  1056. }
  1057. };
  1058. var protect = hookOptions.protect,
  1059. syncDesc = hookOptions.syncDesc;
  1060.  
  1061. if (protect) {
  1062. protectMethod(parent, methodName);
  1063. }
  1064.  
  1065. if (syncDesc) {
  1066. syncToString(origin, parent[methodName]);
  1067. }
  1068. }
  1069. /**
  1070. * Hook target function to replace, not to using func-js instance
  1071. * @param parent {object} Parent object
  1072. * @param methodName {string | symbol} Target method name to replace
  1073. * @param replace {function} To return a new function to replace origin method
  1074. * @param options
  1075. * @return {void}
  1076. */
  1077.  
  1078.  
  1079. function hookReplace(parent, methodName, replace) {
  1080. var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  1081. return hook(parent, methodName, replace, Object.assign({}, options, {
  1082. "native": true
  1083. }));
  1084. }
  1085. /**
  1086. * Protect method from modified
  1087. * @param parent {object}
  1088. * @param methodName {string}
  1089. */
  1090.  
  1091.  
  1092. function protectMethod(parent, methodName) {
  1093. defineProperty.call(Object, parent, methodName, {
  1094. writable: false
  1095. });
  1096. }
  1097. /**
  1098. * Sync the toString method from origin to target
  1099. * @param from {any}
  1100. * @param to {any}
  1101. */
  1102.  
  1103.  
  1104. function syncToString(from, to) {
  1105. defineProperties.call(Object, to, {
  1106. toString: {
  1107. enumerable: false,
  1108. writable: true,
  1109. value: function value() {
  1110. return from.toString();
  1111. }
  1112. },
  1113. toLocaleString: {
  1114. enumerable: false,
  1115. writable: true,
  1116. value: function value() {
  1117. return from.toLocaleString();
  1118. }
  1119. }
  1120. });
  1121. }
  1122.  
  1123. 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(_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 e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
  1124.  
  1125. 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); }
  1126.  
  1127. 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; }
  1128.  
  1129. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
  1130.  
  1131. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
  1132. var id = 0;
  1133.  
  1134. function getUniqueId() {
  1135. return id++;
  1136. }
  1137.  
  1138. /**
  1139. * Using to intercept ajax request, new Instance to start hook
  1140. */
  1141. var AjaxInterceptor = /*#__PURE__*/function () {
  1142. function AjaxInterceptor() {
  1143. _classCallCheck$1(this, AjaxInterceptor);
  1144.  
  1145. _defineProperty(this, "urlHooks", {});
  1146.  
  1147. _defineProperty(this, "responseHooks", {});
  1148.  
  1149. _defineProperty(this, "sendHooks", {});
  1150.  
  1151. var _this = this;
  1152.  
  1153. hookReplace(window, 'XMLHttpRequest', function (D) {
  1154. return /*#__PURE__*/function (_D) {
  1155. _inherits$1(XMLHttpRequest, _D);
  1156.  
  1157. var _super = _createSuper(XMLHttpRequest);
  1158.  
  1159. function XMLHttpRequest() {
  1160. var _this2;
  1161.  
  1162. _classCallCheck$1(this, XMLHttpRequest);
  1163.  
  1164. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  1165. args[_key] = arguments[_key];
  1166. }
  1167.  
  1168. _this2 = _super.call.apply(_super, [this].concat(args));
  1169.  
  1170. _defineProperty(_assertThisInitialized$1(_this2), "id", void 0);
  1171.  
  1172. _this2.id = getUniqueId();
  1173.  
  1174. _this2.addEventListener('readystatechange', function () {
  1175. if (_this2.readyState == 4 || [200, 304, 201, 202, 203].includes(_this2.state)) {
  1176. _this.onResponse(_assertThisInitialized$1(_this2));
  1177. }
  1178. });
  1179.  
  1180. return _this2;
  1181. }
  1182.  
  1183. return XMLHttpRequest;
  1184. }(D);
  1185. });
  1186. hook(window.XMLHttpRequest.prototype, 'open', this.getHookedRequestHandler());
  1187. hook(window.XMLHttpRequest.prototype, 'send', function (origin) {
  1188. return origin.before(function (_ref) {
  1189. var args = _ref.args,
  1190. prevent = _ref.preventDefault;
  1191. return _this.onSend(this, args, prevent);
  1192. });
  1193. });
  1194. }
  1195.  
  1196. _createClass$1(AjaxInterceptor, [{
  1197. key: "getHookedRequestHandler",
  1198. value: function getHookedRequestHandler() {
  1199. var _this = this;
  1200.  
  1201. return function (origin) {
  1202. return origin.before(function (_ref2) {
  1203. var args = _ref2.args,
  1204. prevent = _ref2.preventDefault;
  1205. return _this.onRequest(this, args, prevent);
  1206. });
  1207. };
  1208. }
  1209. }, {
  1210. key: "onSend",
  1211. value: function onSend(xhr, args, prevent) {
  1212. var sendHandlers = this.sendHooks[xhr.id] || [];
  1213. var result;
  1214.  
  1215. var _iterator = _createForOfIteratorHelper(sendHandlers),
  1216. _step;
  1217.  
  1218. try {
  1219. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  1220. var sendHandler = _step.value;
  1221.  
  1222. if (typeof sendHandler === 'function') {
  1223. var _params = {
  1224. args: args,
  1225. prevent: prevent
  1226. };
  1227. result = sendHandler.call(xhr, _params) || result;
  1228. }
  1229. }
  1230. } catch (err) {
  1231. _iterator.e(err);
  1232. } finally {
  1233. _iterator.f();
  1234. }
  1235.  
  1236. this.clearSendHooks(xhr.id);
  1237. return result;
  1238. }
  1239. }, {
  1240. key: "onRequest",
  1241. value: function onRequest(xhr, args, prevent) {
  1242. var _args = _slicedToArray(args, 2),
  1243. url = _args[1];
  1244.  
  1245. var result;
  1246.  
  1247. for (var hookUrl in this.urlHooks) {
  1248. if (new RegExp(hookUrl).test(url)) {
  1249. var _params2 = {
  1250. args: args,
  1251. prevent: prevent
  1252. };
  1253. var hooks = this.urlHooks[hookUrl];
  1254.  
  1255. if (typeof hooks.onRequest === 'function') {
  1256. result = hooks.onRequest.call(xhr, _params2) || result;
  1257. }
  1258.  
  1259. this.signResponseHooks(xhr.id, hooks);
  1260. this.signSendHooks(xhr.id, hooks);
  1261. }
  1262. }
  1263.  
  1264. return result;
  1265. }
  1266. }, {
  1267. key: "onResponse",
  1268. value: function onResponse(xhr) {
  1269. if (xhr.readyState === 4 || [200, 201, 202, 304].includes(xhr.status)) {
  1270. var _replace = function _replace(response) {
  1271. if (typeof response !== 'string') {
  1272. response = JSON.stringify(response);
  1273. }
  1274.  
  1275. Object.defineProperties(xhr, {
  1276. response: {
  1277. writable: false,
  1278. configurable: true,
  1279. value: response
  1280. },
  1281. responseText: {
  1282. writable: false,
  1283. configurable: true,
  1284. value: response
  1285. }
  1286. });
  1287. };
  1288.  
  1289. var originResponse = ['', 'text'].includes(xhr.responseType) ? xhr.responseText : xhr.response;
  1290.  
  1291. var _response;
  1292.  
  1293. try {
  1294. _response = JSON.parse(originResponse);
  1295. } catch (e) {
  1296. _response = originResponse;
  1297. }
  1298.  
  1299. var _params3 = {
  1300. response: _response,
  1301. originResponse: originResponse,
  1302. replace: function replace(response) {
  1303. _params3.response = response;
  1304. },
  1305. define: function define(property, value) {
  1306. Object.defineProperty(xhr, property, {
  1307. writable: false,
  1308. configurable: true,
  1309. value: value
  1310. });
  1311. }
  1312. };
  1313. var _id = xhr.id;
  1314. var targetResponseHooks = this.responseHooks[_id] || [];
  1315.  
  1316. var _iterator2 = _createForOfIteratorHelper(targetResponseHooks),
  1317. _step2;
  1318.  
  1319. try {
  1320. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  1321. var targetResponseHook = _step2.value;
  1322.  
  1323. if (targetResponseHook && typeof targetResponseHook === 'function') {
  1324. targetResponseHook.call(xhr, _params3);
  1325.  
  1326. _replace(_params3.response);
  1327. }
  1328. }
  1329. } catch (err) {
  1330. _iterator2.e(err);
  1331. } finally {
  1332. _iterator2.f();
  1333. }
  1334.  
  1335. this.clearResponseHooks(_id);
  1336. }
  1337. }
  1338. }, {
  1339. key: "signResponseHooks",
  1340. value: function signResponseHooks(id, hooks) {
  1341. if (hooks.onResponse && typeof hooks.onResponse === 'function') {
  1342. var exists = this.responseHooks[id] || [];
  1343. exists.push(hooks.onResponse);
  1344. this.responseHooks[id] = exists;
  1345. }
  1346. }
  1347. }, {
  1348. key: "signSendHooks",
  1349. value: function signSendHooks(id, hooks) {
  1350. if (hooks.onSend && typeof hooks.onSend === 'function') {
  1351. var exists = this.sendHooks[id] || [];
  1352. exists.push(hooks.onSend);
  1353. this.sendHooks[id] = exists;
  1354. }
  1355. }
  1356. }, {
  1357. key: "clearResponseHooks",
  1358. value: function clearResponseHooks(id) {
  1359. this.responseHooks[id] = [];
  1360. }
  1361. }, {
  1362. key: "clearSendHooks",
  1363. value: function clearSendHooks(id) {
  1364. this.sendHooks[id] = [];
  1365. }
  1366. /**
  1367. * Register from url RegExp
  1368. * @param url
  1369. * @param hooks
  1370. */
  1371.  
  1372. }, {
  1373. key: "register",
  1374. value: function register(url, hooks) {
  1375. this.urlHooks[url] = hooks;
  1376. }
  1377. }]);
  1378.  
  1379. return AjaxInterceptor;
  1380. }();
  1381.  
  1382. exports.AjaxInterceptor = AjaxInterceptor;
  1383.  
  1384. Object.defineProperty(exports, '__esModule', { value: true });
  1385.  
  1386. })));

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址