vue-debug-helper

Vue components debug helper

As of 2022-05-19. See the latest version.

  1. // ==UserScript==
  2. // @name vue-debug-helper
  3. // @name:en vue-debug-helper
  4. // @name:zh Vue调试分析助手
  5. // @name:zh-TW Vue調試分析助手
  6. // @name:ja Vueデバッグ分析アシスタント
  7. // @namespace https://github.com/xxxily/vue-debug-helper
  8. // @homepage https://github.com/xxxily/vue-debug-helper
  9. // @version 0.0.19
  10. // @description Vue components debug helper
  11. // @description:en Vue components debug helper
  12. // @description:zh Vue组件探测、统计、分析辅助脚本
  13. // @description:zh-TW Vue組件探測、統計、分析輔助腳本
  14. // @description:ja Vueコンポーネントの検出、統計、分析補助スクリプト
  15. // @author ankvps
  16. // @icon https://cdn.jsdelivr.net/gh/xxxily/vue-debug-helper@main/logo.png
  17. // @match http://*/*
  18. // @match https://*/*
  19. // @grant unsafeWindow
  20. // @grant GM_getResourceText
  21. // @grant GM_addStyle
  22. // @grant GM_setValue
  23. // @grant GM_getValue
  24. // @grant GM_deleteValue
  25. // @grant GM_listValues
  26. // @grant GM_addValueChangeListener
  27. // @grant GM_removeValueChangeListener
  28. // @grant GM_registerMenuCommand
  29. // @grant GM_unregisterMenuCommand
  30. // @grant GM_getTab
  31. // @grant GM_saveTab
  32. // @grant GM_getTabs
  33. // @grant GM_openInTab
  34. // @grant GM_download
  35. // @grant GM_xmlhttpRequest
  36. // @require https://cdn.jsdelivr.net/npm/localforage@1.10.0/dist/localforage.min.js
  37. // @require https://cdn.jsdelivr.net/npm/crypto-js@4.1.1/core.js
  38. // @require https://cdn.jsdelivr.net/npm/crypto-js@4.1.1/md5.js
  39. // @require https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js
  40. // @require https://cdn.jsdelivr.net/npm/jquery-contextmenu@2.9.2/dist/jquery.contextMenu.min.js
  41. // @require https://cdn.jsdelivr.net/npm/jquery-contextmenu@2.9.2/dist/jquery.ui.position.min.js
  42. // @resource contextMenuCss https://cdn.jsdelivr.net/npm/jquery-contextmenu@2.9.2/dist/jquery.contextMenu.min.css
  43. // @run-at document-start
  44. // @connect 127.0.0.1
  45. // @license GPL
  46. // ==/UserScript==
  47. (function (w) { if (w) { w._vueDebugHelper_ = 'https://github.com/xxxily/vue-debug-helper'; } })();
  48.  
  49. class AssertionError extends Error {}
  50. AssertionError.prototype.name = 'AssertionError';
  51.  
  52. /**
  53. * Minimal assert function
  54. * @param {any} t Value to check if falsy
  55. * @param {string=} m Optional assertion error message
  56. * @throws {AssertionError}
  57. */
  58. function assert (t, m) {
  59. if (!t) {
  60. var err = new AssertionError(m);
  61. if (Error.captureStackTrace) Error.captureStackTrace(err, assert);
  62. throw err
  63. }
  64. }
  65.  
  66. /* eslint-env browser */
  67.  
  68. let ls;
  69. if (typeof window === 'undefined' || typeof window.localStorage === 'undefined') {
  70. // A simple localStorage interface so that lsp works in SSR contexts. Not for persistant storage in node.
  71. const _nodeStorage = {};
  72. ls = {
  73. getItem (name) {
  74. return _nodeStorage[name] || null
  75. },
  76. setItem (name, value) {
  77. if (arguments.length < 2) throw new Error('Failed to execute \'setItem\' on \'Storage\': 2 arguments required, but only 1 present.')
  78. _nodeStorage[name] = (value).toString();
  79. },
  80. removeItem (name) {
  81. delete _nodeStorage[name];
  82. }
  83. };
  84. } else {
  85. ls = window.localStorage;
  86. }
  87.  
  88. var localStorageProxy = (name, opts = {}) => {
  89. assert(name, 'namepace required');
  90. const {
  91. defaults = {},
  92. lspReset = false,
  93. storageEventListener = true
  94. } = opts;
  95.  
  96. const state = new EventTarget();
  97. try {
  98. const restoredState = JSON.parse(ls.getItem(name)) || {};
  99. if (restoredState.lspReset !== lspReset) {
  100. ls.removeItem(name);
  101. for (const [k, v] of Object.entries({
  102. ...defaults
  103. })) {
  104. state[k] = v;
  105. }
  106. } else {
  107. for (const [k, v] of Object.entries({
  108. ...defaults,
  109. ...restoredState
  110. })) {
  111. state[k] = v;
  112. }
  113. }
  114. } catch (e) {
  115. console.error(e);
  116. ls.removeItem(name);
  117. }
  118.  
  119. state.lspReset = lspReset;
  120.  
  121. if (storageEventListener && typeof window !== 'undefined' && typeof window.addEventListener !== 'undefined') {
  122. state.addEventListener('storage', (ev) => {
  123. // Replace state with whats stored on localStorage... it is newer.
  124. for (const k of Object.keys(state)) {
  125. delete state[k];
  126. }
  127. const restoredState = JSON.parse(ls.getItem(name)) || {};
  128. for (const [k, v] of Object.entries({
  129. ...defaults,
  130. ...restoredState
  131. })) {
  132. state[k] = v;
  133. }
  134. opts.lspReset = restoredState.lspReset;
  135. state.dispatchEvent(new Event('update'));
  136. });
  137. }
  138.  
  139. function boundHandler (rootRef) {
  140. return {
  141. get (obj, prop) {
  142. if (typeof obj[prop] === 'object' && obj[prop] !== null) {
  143. return new Proxy(obj[prop], boundHandler(rootRef))
  144. } else if (typeof obj[prop] === 'function' && obj === rootRef && prop !== 'constructor') {
  145. // this returns bound EventTarget functions
  146. return obj[prop].bind(obj)
  147. } else {
  148. return obj[prop]
  149. }
  150. },
  151. set (obj, prop, value) {
  152. obj[prop] = value;
  153. try {
  154. ls.setItem(name, JSON.stringify(rootRef));
  155. rootRef.dispatchEvent(new Event('update'));
  156. return true
  157. } catch (e) {
  158. console.error(e);
  159. return false
  160. }
  161. }
  162. }
  163. }
  164.  
  165. return new Proxy(state, boundHandler(state))
  166. };
  167.  
  168. /**
  169. * 对特定数据结构的对象进行排序
  170. * @param {object} obj 一个对象,其结构应该类似于:{key1: [], key2: []}
  171. * @param {boolean} reverse -可选 是否反转、降序排列,默认为false
  172. * @param {object} opts -可选 指定数组的配置项,默认为{key: 'key', value: 'value'}
  173. * @param {object} opts.key -可选 指定对象键名的别名,默认为'key'
  174. * @param {object} opts.value -可选 指定对象值的别名,默认为'value'
  175. * @returns {array} 返回一个数组,其结构应该类似于:[{key: key1, value: []}, {key: key2, value: []}]
  176. */
  177. const objSort = (obj, reverse, opts = { key: 'key', value: 'value' }) => {
  178. const arr = [];
  179. for (const key in obj) {
  180. if (Object.prototype.hasOwnProperty.call(obj, key) && Array.isArray(obj[key])) {
  181. const tmpObj = {};
  182. tmpObj[opts.key] = key;
  183. tmpObj[opts.value] = obj[key];
  184. arr.push(tmpObj);
  185. }
  186. }
  187.  
  188. arr.sort((a, b) => {
  189. return a[opts.value].length - b[opts.value].length
  190. });
  191.  
  192. reverse && arr.reverse();
  193. return arr
  194. };
  195.  
  196. /**
  197. * 根据指定长度创建空白数据
  198. * @param {number} size -可选 指str的重复次数,默认为1024次,如果str为单个单字节字符,则意味着默认产生1Mb的空白数据
  199. * @param {string|number|any} str - 可选 指定数据的字符串,默认为'd'
  200. */
  201. function createEmptyData (count = 1024, str = 'd') {
  202. const arr = [];
  203. arr.length = count + 1;
  204. return arr.join(str)
  205. }
  206.  
  207. /**
  208. * 将字符串分隔的过滤器转换为数组形式的过滤器
  209. * @param {string|array} filter - 必选 字符串或数组,字符串支持使用 , |符号对多个项进行分隔
  210. * @returns {array}
  211. */
  212. function toArrFilters (filter) {
  213. filter = filter || [];
  214.  
  215. /* 如果是字符串,则支持通过, | 两个符号来指定多个组件名称的过滤器 */
  216. if (typeof filter === 'string') {
  217. /* 移除前后的, |分隔符,防止出现空字符的过滤规则 */
  218. filter.replace(/^(,|\|)/, '').replace(/(,|\|)$/, '');
  219.  
  220. if (/\|/.test(filter)) {
  221. filter = filter.split('|');
  222. } else {
  223. filter = filter.split(',');
  224. }
  225. }
  226.  
  227. filter = filter.map(item => item.trim());
  228.  
  229. return filter
  230. }
  231.  
  232. /**
  233. * 将某个过滤器的字符串添加到指定的过滤器集合里
  234. * @param {object} obj helper.config
  235. * @param {string} filtersName
  236. * @param {string} str
  237. * @returns
  238. */
  239. function addToFilters (obj, filtersName, str) {
  240. const strType = typeof str;
  241. if (!obj || !filtersName || !str || !(strType === 'string' || strType === 'number')) {
  242. return
  243. }
  244.  
  245. const filters = obj[filtersName];
  246. if (!filters) {
  247. obj[filtersName] = [str];
  248. } else if (Array.isArray(filters)) {
  249. if (filters.includes(str)) {
  250. /* 将str提到最后 */
  251. const index = filters.indexOf(str);
  252. filters.splice(index, 1);
  253. filters.push(str);
  254. } else {
  255. filters.push(str);
  256. }
  257.  
  258. /* 去重 */
  259. obj[filtersName] = Array.from(new Set(filters));
  260. }
  261. }
  262.  
  263. /**
  264. * 字符串过滤器和字符串的匹配方法
  265. * @param {string} filter -必选 过滤器的字符串
  266. * @param {string} str -必选 要跟过滤字符串进行匹配的字符串
  267. * @returns
  268. */
  269. function stringMatch (filter, str) {
  270. let isMatch = false;
  271.  
  272. if (!filter || !str) {
  273. return isMatch
  274. }
  275.  
  276. filter = String(filter);
  277. str = String(str);
  278.  
  279. /* 带星表示进行模糊匹配,且不区分大小写 */
  280. if (/\*/.test(filter)) {
  281. filter = filter.replace(/\*/g, '').toLocaleLowerCase();
  282. if (str.toLocaleLowerCase().indexOf(filter) > -1) {
  283. isMatch = true;
  284. }
  285. } else if (str.includes(filter)) {
  286. isMatch = true;
  287. }
  288.  
  289. return isMatch
  290. }
  291.  
  292. /**
  293. * 判断某个字符串是否跟filters相匹配
  294. * @param {array|string} filters - 必选 字符串或数组,字符串支持使用 , |符号对多个项进行分隔
  295. * @param {string|number} str - 必选 一个字符串或数字,用于跟过滤器进行匹配判断
  296. */
  297. function filtersMatch (filters, str) {
  298. if (!filters || !str) {
  299. return false
  300. }
  301.  
  302. filters = Array.isArray(filters) ? filters : toArrFilters(filters);
  303. str = String(str);
  304.  
  305. let result = false;
  306. for (let i = 0; i < filters.length; i++) {
  307. const filter = String(filters[i]);
  308.  
  309. if (stringMatch(filter, str)) {
  310. result = true;
  311. break
  312. }
  313. }
  314.  
  315. return result
  316. }
  317.  
  318. const inBrowser = typeof window !== 'undefined';
  319.  
  320. function getVueDevtools () {
  321. return inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__
  322. }
  323.  
  324. function copyToClipboard (text) {
  325. if (inBrowser) {
  326. const input = document.createElement('input');
  327. input.value = text;
  328. document.body.appendChild(input);
  329. input.select();
  330. document.execCommand('copy');
  331. document.body.removeChild(input);
  332. }
  333. }
  334.  
  335. window.vueDebugHelper = {
  336. /* 存储全部未被销毁的组件对象 */
  337. components: {},
  338. /* 存储全部创建过的组件的概要信息,即使销毁了概要信息依然存在 */
  339. componentsSummary: {},
  340. /* 基于componentsSummary的组件情况统计 */
  341. componentsSummaryStatistics: {},
  342. /* 已销毁的组件概要信息列表 */
  343. destroyList: [],
  344. /* 基于destroyList的组件情况统计 */
  345. destroyStatistics: {},
  346.  
  347. config: {
  348. inspect: {
  349. enabled: false
  350. },
  351.  
  352. performanceObserver: {
  353. enabled: false,
  354. // https://runebook.dev/zh-CN/docs/dom/performanceentry/entrytype
  355. entryTypes: ['element', 'navigation', 'resource', 'mark', 'measure', 'paint', 'longtask']
  356. },
  357.  
  358. /* 控制接口缓存 */
  359. ajaxCache: {
  360. enabled: false,
  361. filters: ['*'],
  362.  
  363. /* 设置缓存多久失效,默认为1天 */
  364. expires: 1000 * 60 * 60 * 24
  365. },
  366.  
  367. /* 测量选择器时间差 */
  368. measureSelectorInterval: {
  369. selector1: '',
  370. selector2: ''
  371. },
  372.  
  373. /* 是否在控制台打印组件生命周期的相关信息 */
  374. lifecycle: {
  375. show: false,
  376. filters: ['created'],
  377. componentFilters: []
  378. },
  379.  
  380. /* 查找组件的过滤器配置 */
  381. findComponentsFilters: [],
  382.  
  383. /* 阻止组件创建的过滤器 */
  384. blockFilters: [],
  385.  
  386. devtools: true,
  387.  
  388. /* 改写Vue.component */
  389. hackVueComponent: false,
  390.  
  391. /* 给组件注入空白数据的配置信息 */
  392. dd: {
  393. enabled: false,
  394. filters: [],
  395. count: 1024
  396. }
  397. }
  398. };
  399.  
  400. const helper = window.vueDebugHelper;
  401.  
  402. /* 配置信息跟localStorage联动 */
  403. const state = localStorageProxy('vueDebugHelperConfig', {
  404. defaults: helper.config,
  405. lspReset: false,
  406. storageEventListener: false
  407. });
  408. helper.config = state;
  409.  
  410. const methods = {
  411. objSort,
  412. createEmptyData,
  413. /* 清除全部helper的全部记录数据,以便重新统计 */
  414. clearAll () {
  415. helper.components = {};
  416. helper.componentsSummary = {};
  417. helper.componentsSummaryStatistics = {};
  418. helper.destroyList = [];
  419. helper.destroyStatistics = {};
  420. },
  421.  
  422. /**
  423. * 对当前的helper.components进行统计与排序
  424. * 如果一直没运行过清理函数,则表示统计页面创建至今依然存活的组件对象
  425. * 运行过清理函数,则表示统计清理后新创建且至今依然存活的组件对象
  426. */
  427. componentsStatistics (reverse = true) {
  428. const tmpObj = {};
  429.  
  430. Object.keys(helper.components).forEach(key => {
  431. const component = helper.components[key];
  432.  
  433. tmpObj[component._componentName]
  434. ? tmpObj[component._componentName].push(component)
  435. : (tmpObj[component._componentName] = [component]);
  436. });
  437.  
  438. return objSort(tmpObj, reverse, {
  439. key: 'componentName',
  440. value: 'componentInstance'
  441. })
  442. },
  443.  
  444. /**
  445. * 对componentsSummaryStatistics进行排序输出,以便可以直观查看组件的创建情况
  446. */
  447. componentsSummaryStatisticsSort (reverse = true) {
  448. return objSort(helper.componentsSummaryStatistics, reverse, {
  449. key: 'componentName',
  450. value: 'componentsSummary'
  451. })
  452. },
  453.  
  454. /**
  455. * 对destroyList进行排序输出,以便可以直观查看组件的销毁情况
  456. */
  457. destroyStatisticsSort (reverse = true) {
  458. return objSort(helper.destroyStatistics, reverse, {
  459. key: 'componentName',
  460. value: 'destroyList'
  461. })
  462. },
  463.  
  464. /**
  465. * 对destroyList进行排序输出,以便可以直观查看组件的销毁情况
  466. */
  467. getDestroyByDuration (duration = 1000) {
  468. const destroyList = helper.destroyList;
  469. const destroyListLength = destroyList.length;
  470. const destroyListDuration = destroyList.map(item => item.duration).sort();
  471. const maxDuration = Math.max(...destroyListDuration);
  472. const minDuration = Math.min(...destroyListDuration);
  473. const avgDuration = destroyListDuration.reduce((a, b) => a + b, 0) / destroyListLength;
  474. const durationRange = maxDuration - minDuration;
  475. const durationRangePercent = (duration - minDuration) / durationRange;
  476.  
  477. return {
  478. destroyList,
  479. destroyListLength,
  480. destroyListDuration,
  481. maxDuration,
  482. minDuration,
  483. avgDuration,
  484. durationRange,
  485. durationRangePercent
  486. }
  487. },
  488.  
  489. initComponentInfo (vm) {
  490. if (vm && !vm._componentTag) {
  491. const tag = vm.$vnode?.tag || vm.$options?._componentTag || vm._uid;
  492. vm._componentTag = tag;
  493. vm._componentName = isNaN(Number(tag)) ? tag.replace(/^vue-component-\d+-/, '') : 'anonymous-component';
  494. vm._componentChain = this.getComponentChain(vm);
  495.  
  496. /* 判断是否为函数式组件,函数式组件无状态 (没有响应式数据),也没有实例,也没生命周期概念 */
  497. if (vm._componentName === 'anonymous-component' && !vm.$parent && !vm.$vnode) {
  498. vm._componentName = 'functional-component';
  499. }
  500. }
  501. },
  502.  
  503. /**
  504. * 获取组件的调用链信息
  505. */
  506. getComponentChain (component, moreDetail = false) {
  507. const result = [];
  508. let current = component;
  509. let deep = 0;
  510.  
  511. while (current && deep < 50) {
  512. deep++;
  513.  
  514. /**
  515. * 由于脚本注入的运行时间会比应用创建时间晚,所以会导致部分先创建的组件缺少相关信息
  516. * 这里尝试对部分信息进行修复,以便更好的查看组件的创建情况
  517. */
  518. if (!current._componentTag) {
  519. const tag = current.$vnode?.tag || current.$options?._componentTag || current._uid;
  520. current._componentTag = tag;
  521. current._componentName = isNaN(Number(tag)) ? tag.replace(/^vue-component-\d+-/, '') : 'anonymous-component';
  522. }
  523.  
  524. if (moreDetail) {
  525. result.push({
  526. tag: current._componentTag,
  527. name: current._componentName,
  528. componentsSummary: helper.componentsSummary[current._uid] || null
  529. });
  530. } else {
  531. result.push(current._componentName);
  532. }
  533.  
  534. current = current.$parent;
  535. }
  536.  
  537. if (moreDetail) {
  538. return result
  539. } else {
  540. return result.join(' -> ')
  541. }
  542. },
  543.  
  544. printLifeCycleInfo (lifecycleFilters, componentFilters) {
  545. lifecycleFilters = toArrFilters(lifecycleFilters);
  546. componentFilters = toArrFilters(componentFilters);
  547.  
  548. helper.config.lifecycle = {
  549. show: true,
  550. filters: lifecycleFilters,
  551. componentFilters: componentFilters
  552. };
  553. },
  554. notPrintLifeCycleInfo () {
  555. helper.config.lifecycle.show = false;
  556. },
  557.  
  558. /**
  559. * 查找组件
  560. * @param {string|array} filters 组件名称或组件uid的过滤器,可以是字符串或者数组,如果是字符串多个过滤选可用,或|分隔
  561. * 如果过滤项是数字,则跟组件的id进行精确匹配,如果是字符串,则跟组件的tag信息进行模糊匹配
  562. * @returns {object} {components: [], componentNames: []}
  563. */
  564. findComponents (filters) {
  565. filters = toArrFilters(filters);
  566.  
  567. /* 对filters进行预处理,如果为纯数字则表示通过id查找组件 */
  568. filters = filters.map(filter => {
  569. if (/^\d+$/.test(filter)) {
  570. return Number(filter)
  571. } else {
  572. return filter
  573. }
  574. });
  575.  
  576. helper.config.findComponentsFilters = filters;
  577.  
  578. const result = {
  579. components: [],
  580. globalComponents: [],
  581. destroyedComponents: []
  582. };
  583.  
  584. /* 在helper.components里进行组件查找 */
  585. const components = helper.components;
  586. const keys = Object.keys(components);
  587. for (let i = 0; i < keys.length; i++) {
  588. const component = components[keys[i]];
  589.  
  590. for (let j = 0; j < filters.length; j++) {
  591. const filter = filters[j];
  592.  
  593. if (typeof filter === 'number' && component._uid === filter) {
  594. result.components.push(component);
  595. break
  596. } else if (typeof filter === 'string') {
  597. const { _componentTag, _componentName } = component;
  598.  
  599. if (stringMatch(filter, _componentTag) || stringMatch(filter, _componentName)) {
  600. result.components.push(component);
  601. break
  602. }
  603. }
  604. }
  605. }
  606.  
  607. /* 进行全局组件查找 */
  608. const globalComponentsKeys = Object.keys(helper.Vue.options.components);
  609. for (let i = 0; i < globalComponentsKeys.length; i++) {
  610. const key = String(globalComponentsKeys[i]);
  611. const component = helper.Vue.options.components[globalComponentsKeys[i]];
  612.  
  613. if (filtersMatch(filters, key)) {
  614. const tmpObj = {};
  615. tmpObj[key] = component;
  616. result.globalComponents.push(tmpObj);
  617. }
  618. }
  619.  
  620. helper.destroyList.forEach(item => {
  621. for (let j = 0; j < filters.length; j++) {
  622. const filter = filters[j];
  623.  
  624. if (typeof filter === 'number' && item.uid === filter) {
  625. result.destroyedComponents.push(item);
  626. break
  627. } else if (typeof filter === 'string') {
  628. if (stringMatch(filter, item.tag) || stringMatch(filter, item.name)) {
  629. result.destroyedComponents.push(item);
  630. break
  631. }
  632. }
  633. }
  634. });
  635.  
  636. return result
  637. },
  638.  
  639. findNotContainElementComponents () {
  640. const result = [];
  641. const keys = Object.keys(helper.components);
  642. keys.forEach(key => {
  643. const component = helper.components[key];
  644. const elStr = Object.prototype.toString.call(component.$el);
  645. if (!/(HTML|Comment)/.test(elStr)) {
  646. result.push(component);
  647. }
  648. });
  649.  
  650. return result
  651. },
  652.  
  653. /**
  654. * 阻止组件的创建
  655. * @param {string|array} filters 组件名称过滤器,可以是字符串或者数组,如果是字符串多个过滤选可用,或|分隔
  656. */
  657. blockComponents (filters) {
  658. filters = toArrFilters(filters);
  659. helper.config.blockFilters = filters;
  660. },
  661.  
  662. /**
  663. * 给指定组件注入大量空数据,以便观察组件的内存泄露情况
  664. * @param {Array|string} filter -必选 指定组件的名称,如果为空则表示注入所有组件
  665. * @param {number} count -可选 指定注入空数据的大小,单位Kb,默认为1024Kb,即1Mb
  666. * @returns
  667. */
  668. dd (filter, count = 1024) {
  669. filter = toArrFilters(filter);
  670. helper.config.dd = {
  671. enabled: true,
  672. filters: filter,
  673. count
  674. };
  675. },
  676. /* 禁止给组件注入空数据 */
  677. undd () {
  678. helper.config.dd = {
  679. enabled: false,
  680. filters: [],
  681. count: 1024
  682. };
  683.  
  684. /* 删除之前注入的数据 */
  685. Object.keys(helper.components).forEach(key => {
  686. const component = helper.components[key];
  687. component.$data && delete component.$data.__dd__;
  688. });
  689. },
  690.  
  691. toggleDevtools () {
  692. helper.config.devtools = !helper.config.devtools;
  693. }
  694. };
  695.  
  696. helper.methods = methods;
  697.  
  698. class Debug {
  699. constructor (msg, printTime = false) {
  700. const t = this;
  701. msg = msg || 'debug message:';
  702. t.log = t.createDebugMethod('log', null, msg);
  703. t.error = t.createDebugMethod('error', null, msg);
  704. t.info = t.createDebugMethod('info', null, msg);
  705. t.warn = t.createDebugMethod('warn', null, msg);
  706. }
  707.  
  708. create (msg) {
  709. return new Debug(msg)
  710. }
  711.  
  712. createDebugMethod (name, color, tipsMsg) {
  713. name = name || 'info';
  714.  
  715. const bgColorMap = {
  716. info: '#2274A5',
  717. log: '#95B46A',
  718. warn: '#F5A623',
  719. error: '#D33F49'
  720. };
  721.  
  722. const printTime = this.printTime;
  723.  
  724. return function () {
  725. if (!window._debugMode_) {
  726. return false
  727. }
  728.  
  729. const msg = tipsMsg || 'debug message:';
  730.  
  731. const arg = Array.from(arguments);
  732. arg.unshift(`color: white; background-color: ${color || bgColorMap[name] || '#95B46A'}`);
  733.  
  734. if (printTime) {
  735. const curTime = new Date();
  736. const H = curTime.getHours();
  737. const M = curTime.getMinutes();
  738. const S = curTime.getSeconds();
  739. arg.unshift(`%c [${H}:${M}:${S}] ${msg} `);
  740. } else {
  741. arg.unshift(`%c ${msg} `);
  742. }
  743.  
  744. window.console[name].apply(window.console, arg);
  745. }
  746. }
  747.  
  748. isDebugMode () {
  749. return Boolean(window._debugMode_)
  750. }
  751. }
  752.  
  753. var Debug$1 = new Debug();
  754.  
  755. var debug = Debug$1.create('vueDebugHelper:');
  756.  
  757. /**
  758. * 打印生命周期信息
  759. * @param {Vue} vm vue组件实例
  760. * @param {string} lifeCycle vue生命周期名称
  761. * @returns
  762. */
  763. function printLifeCycle (vm, lifeCycle) {
  764. const lifeCycleConf = helper.config.lifecycle || { show: false, filters: ['created'], componentFilters: [] };
  765.  
  766. if (!vm || !lifeCycle || !lifeCycleConf.show) {
  767. return false
  768. }
  769.  
  770. const file = vm.options?.__file || vm.$options?.__file || '';
  771.  
  772. const { _componentTag, _componentName, _componentChain, _createdHumanTime, _uid } = vm;
  773. let info = `[${lifeCycle}] tag: ${_componentTag}, uid: ${_uid}, createdTime: ${_createdHumanTime}, chain: ${_componentChain}`;
  774.  
  775. if (file) {
  776. info += `, file: ${file}`;
  777. }
  778.  
  779. const matchComponentFilters = lifeCycleConf.componentFilters.length === 0 || filtersMatch(lifeCycleConf.componentFilters, _componentName);
  780. if (lifeCycleConf.filters.includes(lifeCycle) && matchComponentFilters) {
  781. debug.log(info);
  782. }
  783. }
  784.  
  785. function mixinRegister (Vue) {
  786. if (!Vue || !Vue.mixin) {
  787. debug.error('未检查到VUE对象,请检查是否引入了VUE,且将VUE对象挂载到全局变量window.Vue上');
  788. return false
  789. }
  790.  
  791. Vue.mixin({
  792. beforeCreate: function () {
  793. // const tag = this.$options?._componentTag || this.$vnode?.tag || this._uid
  794. helper.methods.initComponentInfo(this);
  795.  
  796. this._createdTime = Date.now();
  797. /* 增加人类方便查看的时间信息 */
  798. const timeObj = new Date(this._createdTime);
  799. this._createdHumanTime = `${timeObj.getHours()}:${timeObj.getMinutes()}:${timeObj.getSeconds()}`;
  800.  
  801. helper.components[this._uid] = this;
  802.  
  803. /**
  804. * 收集所有创建过的组件信息,此处只存储组件的基础信息,没销毁的组件会包含组件实例
  805. * 严禁对组件内其它对象进行引用,否则会导致组件实列无法被正常回收
  806. */
  807. const componentSummary = {
  808. uid: this._uid,
  809. name: this._componentName,
  810. tag: this._componentTag,
  811. createdTime: this._createdTime,
  812. createdHumanTime: this._createdHumanTime,
  813. // 0 表示还没被销毁
  814. destroyTime: 0,
  815. // 0 表示还没被销毁,duration可持续当当前查看时间
  816. duration: 0,
  817. component: this,
  818. chain: this._componentChain
  819. };
  820. helper.componentsSummary[this._uid] = componentSummary;
  821.  
  822. /* 添加到componentsSummaryStatistics里,生成统计信息 */
  823. Array.isArray(helper.componentsSummaryStatistics[this._componentName])
  824. ? helper.componentsSummaryStatistics[this._componentName].push(componentSummary)
  825. : (helper.componentsSummaryStatistics[this._componentName] = [componentSummary]);
  826.  
  827. printLifeCycle(this, 'beforeCreate');
  828. },
  829. created: function () {
  830. /* 增加空白数据,方便观察内存泄露情况 */
  831. if (helper.config.dd.enabled) {
  832. let needDd = false;
  833.  
  834. if (helper.config.dd.filters.length === 0) {
  835. needDd = true;
  836. } else {
  837. for (let index = 0; index < helper.config.dd.filters.length; index++) {
  838. const filter = helper.config.dd.filters[index];
  839. if (filter === this._componentName || String(this._componentName).endsWith(filter)) {
  840. needDd = true;
  841. break
  842. }
  843. }
  844. }
  845.  
  846. if (needDd) {
  847. const count = helper.config.dd.count * 1024;
  848. const componentInfo = `tag: ${this._componentTag}, uid: ${this._uid}, createdTime: ${this._createdHumanTime}`;
  849.  
  850. /* 此处必须使用JSON.stringify对产生的字符串进行消费,否则没法将内存占用上去 */
  851. this.$data.__dd__ = JSON.stringify(componentInfo + ' ' + helper.methods.createEmptyData(count, this._uid));
  852.  
  853. console.log(`[dd success] ${componentInfo} chain: ${this._componentChain}`);
  854. }
  855. }
  856.  
  857. printLifeCycle(this, 'created');
  858. },
  859. beforeMount: function () {
  860. printLifeCycle(this, 'beforeMount');
  861. },
  862. mounted: function () {
  863. printLifeCycle(this, 'mounted');
  864. },
  865. beforeUpdate: function () {
  866. printLifeCycle(this, 'beforeUpdate');
  867. },
  868. activated: function () {
  869. printLifeCycle(this, 'activated');
  870. },
  871. deactivated: function () {
  872. printLifeCycle(this, 'deactivated');
  873. },
  874. updated: function () {
  875. printLifeCycle(this, 'updated');
  876. },
  877. beforeDestroy: function () {
  878. printLifeCycle(this, 'beforeDestroy');
  879. },
  880. destroyed: function () {
  881. printLifeCycle(this, 'destroyed');
  882.  
  883. if (this._componentTag) {
  884. const uid = this._uid;
  885. const name = this._componentName;
  886. const destroyTime = Date.now();
  887.  
  888. /* helper里的componentSummary有可能通过调用clear函数而被清除掉,所以需进行判断再更新赋值 */
  889. const componentSummary = helper.componentsSummary[this._uid];
  890. if (componentSummary) {
  891. /* 补充/更新组件信息 */
  892. componentSummary.destroyTime = destroyTime;
  893. componentSummary.duration = destroyTime - this._createdTime;
  894.  
  895. helper.destroyList.push(componentSummary);
  896.  
  897. /* 统计被销毁的组件信息 */
  898. Array.isArray(helper.destroyStatistics[name])
  899. ? helper.destroyStatistics[name].push(componentSummary)
  900. : (helper.destroyStatistics[name] = [componentSummary]);
  901.  
  902. /* 删除已销毁的组件实例 */
  903. delete componentSummary.component;
  904. }
  905.  
  906. // 解除引用关系
  907. delete this._componentTag;
  908. delete this._componentChain;
  909. delete this._componentName;
  910. delete this._createdTime;
  911. delete this._createdHumanTime;
  912. delete this.$data.__dd__;
  913. delete helper.components[uid];
  914. } else {
  915. console.error('存在未被正常标记的组件,请检查组件采集逻辑是否需完善', this);
  916. }
  917. }
  918. });
  919. }
  920.  
  921. /*!
  922. * @name menuCommand.js
  923. * @version 0.0.1
  924. * @author Blaze
  925. * @date 2019/9/21 14:22
  926. */
  927.  
  928. const monkeyMenu = {
  929. on (title, fn, accessKey) {
  930. return window.GM_registerMenuCommand && window.GM_registerMenuCommand(title, fn, accessKey)
  931. },
  932. off (id) {
  933. return window.GM_unregisterMenuCommand && window.GM_unregisterMenuCommand(id)
  934. },
  935. /* 切换类型的菜单功能 */
  936. switch (title, fn, defVal) {
  937. const t = this;
  938. t.on(title, fn);
  939. }
  940. };
  941.  
  942. /**
  943. * 简单的i18n库
  944. */
  945.  
  946. class I18n {
  947. constructor (config) {
  948. this._languages = {};
  949. this._locale = this.getClientLang();
  950. this._defaultLanguage = '';
  951. this.init(config);
  952. }
  953.  
  954. init (config) {
  955. if (!config) return false
  956.  
  957. const t = this;
  958. t._locale = config.locale || t._locale;
  959. /* 指定当前要是使用的语言环境,默认无需指定,会自动读取 */
  960. t._languages = config.languages || t._languages;
  961. t._defaultLanguage = config.defaultLanguage || t._defaultLanguage;
  962. }
  963.  
  964. use () {}
  965.  
  966. t (path) {
  967. const t = this;
  968. let result = t.getValByPath(t._languages[t._locale] || {}, path);
  969.  
  970. /* 版本回退 */
  971. if (!result && t._locale !== t._defaultLanguage) {
  972. result = t.getValByPath(t._languages[t._defaultLanguage] || {}, path);
  973. }
  974.  
  975. return result || ''
  976. }
  977.  
  978. /* 当前语言值 */
  979. language () {
  980. return this._locale
  981. }
  982.  
  983. languages () {
  984. return this._languages
  985. }
  986.  
  987. changeLanguage (locale) {
  988. if (this._languages[locale]) {
  989. this._languages = locale;
  990. return locale
  991. } else {
  992. return false
  993. }
  994. }
  995.  
  996. /**
  997. * 根据文本路径获取对象里面的值
  998. * @param obj {Object} -必选 要操作的对象
  999. * @param path {String} -必选 路径信息
  1000. * @returns {*}
  1001. */
  1002. getValByPath (obj, path) {
  1003. path = path || '';
  1004. const pathArr = path.split('.');
  1005. let result = obj;
  1006.  
  1007. /* 递归提取结果值 */
  1008. for (let i = 0; i < pathArr.length; i++) {
  1009. if (!result) break
  1010. result = result[pathArr[i]];
  1011. }
  1012.  
  1013. return result
  1014. }
  1015.  
  1016. /* 获取客户端当前的语言环境 */
  1017. getClientLang () {
  1018. return navigator.languages ? navigator.languages[0] : navigator.language
  1019. }
  1020. }
  1021.  
  1022. var zhCN = {
  1023. about: '关于',
  1024. issues: '反馈',
  1025. setting: '设置',
  1026. hotkeys: '快捷键',
  1027. donate: '赞赏',
  1028. quit: '退出',
  1029. refreshPage: '刷新页面',
  1030. debugHelper: {
  1031. viewVueDebugHelperObject: 'vueDebugHelper对象',
  1032. componentsStatistics: '当前存活组件统计',
  1033. destroyStatisticsSort: '已销毁组件统计',
  1034. componentsSummaryStatisticsSort: '全部组件混合统计',
  1035. getDestroyByDuration: '组件存活时间信息',
  1036. clearAll: '清空统计信息',
  1037. printLifeCycleInfo: '打印组件生命周期信息',
  1038. notPrintLifeCycleInfo: '取消组件生命周期信息打印',
  1039. printLifeCycleInfoPrompt: {
  1040. lifecycleFilters: '输入要打印的生命周期名称,多个可用,或|分隔,支持的值:beforeCreate|created|beforeMount|mounted|beforeUpdate|updated|activated|deactivated|beforeDestroy|destroyed',
  1041. componentFilters: '输入要打印的组件名称,多个可用,或|分隔,不输入则打印所有组件,字符串后面加*可执行模糊匹配'
  1042. },
  1043. findComponents: '查找组件',
  1044. findComponentsPrompt: {
  1045. filters: '输入要查找的组件名称,或uid,多个可用,或|分隔,字符串后面加*可执行模糊匹配'
  1046. },
  1047. findNotContainElementComponents: '查找不包含DOM对象的组件',
  1048. blockComponents: '阻断组件的创建',
  1049. blockComponentsPrompt: {
  1050. filters: '输入要阻断的组件名称,多个可用,或|分隔,输入为空则取消阻断,字符串后面加*可执行模糊匹配'
  1051. },
  1052. dd: '数据注入(dd)',
  1053. undd: '取消数据注入(undd)',
  1054. ddPrompt: {
  1055. filter: '组件过滤器(如果为空,则对所有组件注入)',
  1056. count: '指定注入数据的重复次数(默认1024)'
  1057. },
  1058. toggleHackVueComponent: '改写/还原Vue.component',
  1059. hackVueComponent: {
  1060. hack: '改写Vue.component',
  1061. unhack: '还原Vue.component'
  1062. },
  1063. toggleInspect: '切换Inspect',
  1064. inspectStatus: {
  1065. on: '开启Inspect',
  1066. off: '关闭Inspect'
  1067. },
  1068. togglePerformanceObserver: '开启/关闭性能观察',
  1069. performanceObserverStatus: {
  1070. on: '开启性能观察',
  1071. off: '关闭性能观察'
  1072. },
  1073. performanceObserverPrompt: {
  1074. entryTypes: '输入要观察的类型,多个类型可用,或|分隔,支持的类型有:element,navigation,resource,mark,measure,paint,longtask',
  1075. notSupport: '当前浏览器不支持性能观察'
  1076. },
  1077. enableAjaxCacheTips: '接口缓存功能已开启',
  1078. disableAjaxCacheTips: '接口缓存功能已关闭',
  1079. toggleAjaxCache: '开启/关闭接口缓存',
  1080. ajaxCacheStatus: {
  1081. on: '开启接口缓存',
  1082. off: '关闭接口缓存'
  1083. },
  1084. clearAjaxCache: '清空接口缓存数据',
  1085. clearAjaxCacheTips: '接口缓存数据已清空',
  1086. jaxCachePrompt: {
  1087. filters: '输入要缓存的接口地址,多个可用,或|分隔,字符串后面加*可执行模糊匹配',
  1088. expires: '输入缓存过期时间,单位为分钟,默认为1440分钟(即24小时)'
  1089. },
  1090. measureSelectorInterval: '测量选择器时间差',
  1091. measureSelectorIntervalPrompt: {
  1092. selector1: '输入起始选择器',
  1093. selector2: '输入结束选择器'
  1094. },
  1095. selectorReadyTips: '元素已就绪',
  1096. devtools: {
  1097. enabled: '自动开启vue-devtools',
  1098. disable: '禁止开启vue-devtools'
  1099. }
  1100. },
  1101. contextMenu: {
  1102. consoleComponent: '查看组件',
  1103. consoleComponentData: '查看组件数据',
  1104. consoleComponentProps: '查看组件props',
  1105. consoleComponentChain: '查看组件调用链',
  1106. consoleParentComponent: '查看父组件',
  1107. componentAction: '相关操作',
  1108. copyFilePath: '复制文件路径',
  1109. copyComponentName: '复制组件名称',
  1110. copyComponentData: '复制组件$data',
  1111. copyComponentProps: '复制组件$props',
  1112. copyComponentTag: '复制组件标签',
  1113. copyComponentUid: '复制组件uid',
  1114. copyComponentChian: '复制组件调用链',
  1115. findComponents: '查找组件',
  1116. printLifeCycleInfo: '打印生命周期信息',
  1117. blockComponents: '阻断组件'
  1118. }
  1119. };
  1120.  
  1121. var enUS = {
  1122. about: 'about',
  1123. issues: 'feedback',
  1124. setting: 'settings',
  1125. hotkeys: 'Shortcut keys',
  1126. donate: 'donate',
  1127. quit: 'quit',
  1128. refreshPage: 'Refresh the page',
  1129. debugHelper: {
  1130. viewVueDebugHelperObject: 'vueDebugHelper object',
  1131. componentsStatistics: 'Current surviving component statistics',
  1132. destroyStatisticsSort: 'Destroyed component statistics',
  1133. componentsSummaryStatisticsSort: 'All components mixed statistics',
  1134. getDestroyByDuration: 'Component survival time information',
  1135. clearAll: 'Clear statistics',
  1136. printLifeCycleInfo: 'Print component life cycle information',
  1137. notPrintLifeCycleInfo: 'Cancel the printing of component life cycle information',
  1138. printLifeCycleInfoPrompt: {
  1139. lifecycleFilters: 'Enter the lifecycle name to be printed, multiple available, or | separated, supported values: beforeCreate|created|beforeMount|mounted|beforeUpdate|updated|activated|deactivated|beforeDestroy|destroyed',
  1140. componentFilters: 'Enter the name of the component to be printed, multiple available, or | separated, if not input, print all components, add * after the string to perform fuzzy matching'
  1141. },
  1142. findComponents: 'Find Components',
  1143. findComponentsPrompt: {
  1144. filters: 'Enter the name of the component to find, or uid, multiple available, or | separated, followed by * to perform fuzzy matching'
  1145. },
  1146. findNotContainElementComponents: 'Find components that do not contain DOM objects',
  1147. blockComponents: 'Block the creation of components',
  1148. blockComponentsPrompt: {
  1149. filters: 'Enter the name of the component to be blocked, multiple available, or | separated, the input is empty to cancel the blocking, add * after the string to perform fuzzy matching'
  1150. },
  1151. dd: 'Data injection (dd)',
  1152. undd: 'Cancel data injection (undd)',
  1153. ddPrompt: {
  1154. filter: 'Component filter (if empty, inject all components)',
  1155. count: 'Specify the number of repetitions of injected data (default 1024)'
  1156. },
  1157. toggleHackVueComponent: 'Rewrite/restore Vue.component',
  1158. hackVueComponent: {
  1159. hack: 'Rewrite Vue.component',
  1160. unhack: 'Restore Vue.component'
  1161. },
  1162. toggleInspect: 'Toggle Inspect',
  1163. inspectStatus: {
  1164. on: 'Enable Inspect',
  1165. off: 'Turn off Inspect'
  1166. },
  1167. togglePerformanceObserver: 'Turn on/off performance observation',
  1168. performanceObserverStatus: {
  1169. on: 'Enable performance observation',
  1170. off: 'Turn off performance observation'
  1171. },
  1172. performanceObserverPrompt: {
  1173. entryTypes: 'Enter the type to be observed, multiple types are available, or | separated, the supported types are: element, navigation, resource, mark, measure, paint, longtask',
  1174. notSupport: 'The current browser does not support performance observation'
  1175. },
  1176. enableAjaxCacheTips: 'The interface cache function is enabled',
  1177. disableAjaxCacheTips: 'The interface cache function has been closed',
  1178. toggleAjaxCache: 'Enable/disable interface cache',
  1179. ajaxCacheStatus: {
  1180. on: 'Enable interface cache',
  1181. off: 'Turn off the interface cache'
  1182. },
  1183. clearAjaxCache: 'Clear interface cache data',
  1184. clearAjaxCacheTips: 'The interface cache data has been cleared',
  1185. jaxCachePrompt: {
  1186. filters: 'Enter the interface address to be cached, multiple available, or | separated, followed by * to perform fuzzy matching',
  1187. expires: 'Enter the cache expiration time in minutes, the default is 1440 minutes (ie 24 hours)'
  1188. },
  1189. measureSelectorInterval: 'Measure selector time difference',
  1190. measureSelectorIntervalPrompt: {
  1191. selector1: 'input start selector',
  1192. selector2: 'input end selector'
  1193. },
  1194. selectorReadyTips: 'The element is ready',
  1195. devtools: {
  1196. enabled: 'Automatically enable vue-devtools',
  1197. disable: 'Disable to enable vue-devtools'
  1198. }
  1199. },
  1200. contextMenu: {
  1201. consoleComponent: 'View component',
  1202. consoleComponentData: 'View component data',
  1203. consoleComponentProps: 'View component props',
  1204. consoleComponentChain: 'View the component call chain',
  1205. consoleParentComponent: 'View parent component',
  1206. componentAction: 'Related actions',
  1207. copyFilePath: 'Copy file path',
  1208. copyComponentName: 'Copy component name',
  1209. copyComponentData: 'Copy component $data',
  1210. copyComponentProps: 'Copy component $props',
  1211. copyComponentTag: 'Copy component tag',
  1212. copyComponentUid: 'Copy component uid',
  1213. copyComponentChian: 'Copy component call chain',
  1214. findComponents: 'Find Components',
  1215. printLifeCycleInfo: 'Print life cycle information',
  1216. blockComponents: 'Block Components'
  1217. }
  1218. };
  1219.  
  1220. var zhTW = {
  1221. about: '關於',
  1222. issues: '反饋',
  1223. setting: '設置',
  1224. hotkeys: '快捷鍵',
  1225. donate: '讚賞',
  1226. quit: '退出',
  1227. refreshPage: '刷新頁面',
  1228. debugHelper: {
  1229. viewVueDebugHelperObject: 'vueDebugHelper對象',
  1230. componentsStatistics: '當前存活組件統計',
  1231. destroyStatisticsSort: '已銷毀組件統計',
  1232. componentsSummaryStatisticsSort: '全部組件混合統計',
  1233. getDestroyByDuration: '組件存活時間信息',
  1234. clearAll: '清空統計信息',
  1235. printLifeCycleInfo: '打印組件生命週期信息',
  1236. notPrintLifeCycleInfo: '取消組件生命週期信息打印',
  1237. printLifeCycleInfoPrompt: {
  1238. lifecycleFilters: '輸入要打印的生命週期名稱,多個可用,或|分隔,支持的值:beforeCreate|created|beforeMount|mounted|beforeUpdate|updated|activated|deactivated|beforeDestroy|destroyed',
  1239. componentFilters: '輸入要打印的組件名稱,多個可用,或|分隔,不輸入則打印所有組件,字符串後面加*可執行模糊匹配'
  1240. },
  1241. findComponents: '查找組件',
  1242. findComponentsPrompt: {
  1243. filters: '輸入要查找的組件名稱,或uid,多個可用,或|分隔,字符串後面加*可執行模糊匹配'
  1244. },
  1245. findNotContainElementComponents: '查找不包含DOM對象的組件',
  1246. blockComponents: '阻斷組件的創建',
  1247. blockComponentsPrompt: {
  1248. filters: '輸入要阻斷的組件名稱,多個可用,或|分隔,輸入為空則取消阻斷,字符串後面加*可執行模糊匹配'
  1249. },
  1250. dd: '數據注入(dd)',
  1251. undd: '取消數據注入(undd)',
  1252. ddPrompt: {
  1253. filter: '組件過濾器(如果為空,則對所有組件注入)',
  1254. count: '指定注入數據的重複次數(默認1024)'
  1255. },
  1256. toggleHackVueComponent: '改寫/還原Vue.component',
  1257. hackVueComponent: {
  1258. hack: '改寫Vue.component',
  1259. unhack: '還原Vue.component'
  1260. },
  1261. toggleInspect: '切換Inspect',
  1262. inspectStatus: {
  1263. on: '開啟Inspect',
  1264. off: '關閉Inspect'
  1265. },
  1266. togglePerformanceObserver: '開啟/關閉性能觀察',
  1267. performanceObserverStatus: {
  1268. on: '開啟性能觀察',
  1269. off: '關閉性能觀察'
  1270. },
  1271. performanceObserverPrompt: {
  1272. entryTypes: '輸入要觀察的類型,多個類型可用,或|分隔,支持的類型有:element,navigation,resource,mark,measure,paint,longtask',
  1273. notSupport: '當前瀏覽器不支持性能觀察'
  1274. },
  1275. enableAjaxCacheTips: '接口緩存功能已開啟',
  1276. disableAjaxCacheTips: '接口緩存功能已關閉',
  1277. toggleAjaxCache: '開啟/關閉接口緩存',
  1278. ajaxCacheStatus: {
  1279. on: '開啟接口緩存',
  1280. off: '關閉接口緩存'
  1281. },
  1282. clearAjaxCache: '清空接口緩存數據',
  1283. clearAjaxCacheTips: '接口緩存數據已清空',
  1284. jaxCachePrompt: {
  1285. filters: '輸入要緩存的接口地址,多個可用,或|分隔,字符串後面加*可執行模糊匹配',
  1286. expires: '輸入緩存過期時間,單位為分鐘,默認為1440分鐘(即24小時)'
  1287. },
  1288. measureSelectorInterval: '測量選擇器時間差',
  1289. measureSelectorIntervalPrompt: {
  1290. selector1: '輸入起始選擇器',
  1291. selector2: '輸入結束選擇器'
  1292. },
  1293. selectorReadyTips: '元素已就緒',
  1294. devtools: {
  1295. enabled: '自動開啟vue-devtools',
  1296. disable: '禁止開啟vue-devtools'
  1297. }
  1298. },
  1299. contextMenu: {
  1300. consoleComponent: '查看組件',
  1301. consoleComponentData: '查看組件數據',
  1302. consoleComponentProps: '查看組件props',
  1303. consoleComponentChain: '查看組件調用鏈',
  1304. consoleParentComponent: '查看父組件',
  1305. componentAction: '相關操作',
  1306. copyFilePath: '複製文件路徑',
  1307. copyComponentName: '複製組件名稱',
  1308. copyComponentData: '複製組件$data',
  1309. copyComponentProps: '複製組件$props',
  1310. copyComponentTag: '複製組件標籤',
  1311. copyComponentUid: '複製組件uid',
  1312. copyComponentChian: '複製組件調用鏈',
  1313. findComponents: '查找組件',
  1314. printLifeCycleInfo: '打印生命週期信息',
  1315. blockComponents: '阻斷組件'
  1316. }
  1317. };
  1318.  
  1319. const messages = {
  1320. 'zh-CN': zhCN,
  1321. zh: zhCN,
  1322. 'zh-HK': zhTW,
  1323. 'zh-TW': zhTW,
  1324. 'en-US': enUS,
  1325. en: enUS,
  1326. };
  1327.  
  1328. /*!
  1329. * @name i18n.js
  1330. * @description vue-debug-helper的国际化配置
  1331. * @version 0.0.1
  1332. * @author xxxily
  1333. * @date 2022/04/26 14:56
  1334. * @github https://github.com/xxxily
  1335. */
  1336.  
  1337. const i18n = new I18n({
  1338. defaultLanguage: 'en',
  1339. /* 指定当前要是使用的语言环境,默认无需指定,会自动读取 */
  1340. // locale: 'zh-TW',
  1341. languages: messages
  1342. });
  1343.  
  1344. /*!
  1345. * @name index.js
  1346. * @description hookJs JS AOP切面编程辅助库
  1347. * @version 0.0.1
  1348. * @author Blaze
  1349. * @date 2020/10/22 17:40
  1350. * @github https://github.com/xxxily
  1351. */
  1352.  
  1353. const win = typeof window === 'undefined' ? global : window;
  1354. const toStr = Function.prototype.call.bind(Object.prototype.toString);
  1355. /* 特殊场景,如果把Boolean也hook了,很容易导致调用溢出,所以是需要使用原生Boolean */
  1356. const toBoolean = Boolean.originMethod ? Boolean.originMethod : Boolean;
  1357. const util = {
  1358. toStr,
  1359. isObj: obj => toStr(obj) === '[object Object]',
  1360. /* 判断是否为引用类型,用于更宽泛的场景 */
  1361. isRef: obj => typeof obj === 'object',
  1362. isReg: obj => toStr(obj) === '[object RegExp]',
  1363. isFn: obj => obj instanceof Function,
  1364. isAsyncFn: fn => toStr(fn) === '[object AsyncFunction]',
  1365. isPromise: obj => toStr(obj) === '[object Promise]',
  1366. firstUpperCase: str => str.replace(/^\S/, s => s.toUpperCase()),
  1367. toArr: arg => Array.from(Array.isArray(arg) ? arg : [arg]),
  1368.  
  1369. debug: {
  1370. log () {
  1371. let log = win.console.log;
  1372. /* 如果log也被hook了,则使用未被hook前的log函数 */
  1373. if (log.originMethod) { log = log.originMethod; }
  1374. if (win._debugMode_) {
  1375. log.apply(win.console, arguments);
  1376. }
  1377. }
  1378. },
  1379. /* 获取包含自身、继承、可枚举、不可枚举的键名 */
  1380. getAllKeys (obj) {
  1381. const tmpArr = [];
  1382. for (const key in obj) { tmpArr.push(key); }
  1383. const allKeys = Array.from(new Set(tmpArr.concat(Reflect.ownKeys(obj))));
  1384. return allKeys
  1385. }
  1386. };
  1387.  
  1388. class HookJs {
  1389. constructor (useProxy) {
  1390. this.useProxy = useProxy || false;
  1391. this.hookPropertiesKeyName = '_hookProperties' + Date.now();
  1392. }
  1393.  
  1394. hookJsPro () {
  1395. return new HookJs(true)
  1396. }
  1397.  
  1398. _addHook (hookMethod, fn, type, classHook) {
  1399. const hookKeyName = type + 'Hooks';
  1400. const hookMethodProperties = hookMethod[this.hookPropertiesKeyName];
  1401. if (!hookMethodProperties[hookKeyName]) {
  1402. hookMethodProperties[hookKeyName] = [];
  1403. }
  1404.  
  1405. /* 注册(储存)要被调用的hook函数,同时防止重复注册 */
  1406. let hasSameHook = false;
  1407. for (let i = 0; i < hookMethodProperties[hookKeyName].length; i++) {
  1408. if (fn === hookMethodProperties[hookKeyName][i]) {
  1409. hasSameHook = true;
  1410. break
  1411. }
  1412. }
  1413.  
  1414. if (!hasSameHook) {
  1415. fn.classHook = classHook || false;
  1416. hookMethodProperties[hookKeyName].push(fn);
  1417. }
  1418. }
  1419.  
  1420. _runHooks (parentObj, methodName, originMethod, hookMethod, target, ctx, args, classHook, hookPropertiesKeyName) {
  1421. const hookMethodProperties = hookMethod[hookPropertiesKeyName];
  1422. const beforeHooks = hookMethodProperties.beforeHooks || [];
  1423. const afterHooks = hookMethodProperties.afterHooks || [];
  1424. const errorHooks = hookMethodProperties.errorHooks || [];
  1425. const hangUpHooks = hookMethodProperties.hangUpHooks || [];
  1426. const replaceHooks = hookMethodProperties.replaceHooks || [];
  1427. const execInfo = {
  1428. result: null,
  1429. error: null,
  1430. args: args,
  1431. type: ''
  1432. };
  1433.  
  1434. function runHooks (hooks, type) {
  1435. let hookResult = null;
  1436. execInfo.type = type || '';
  1437. if (Array.isArray(hooks)) {
  1438. hooks.forEach(fn => {
  1439. if (util.isFn(fn) && classHook === fn.classHook) {
  1440. hookResult = fn(args, parentObj, methodName, originMethod, execInfo, ctx);
  1441. }
  1442. });
  1443. }
  1444. return hookResult
  1445. }
  1446.  
  1447. const runTarget = (function () {
  1448. if (classHook) {
  1449. return function () {
  1450. // eslint-disable-next-line new-cap
  1451. return new target(...args)
  1452. }
  1453. } else {
  1454. return function () {
  1455. return target.apply(ctx, args)
  1456. }
  1457. }
  1458. })();
  1459.  
  1460. const beforeHooksResult = runHooks(beforeHooks, 'before');
  1461. /* 支持终止后续调用的指令 */
  1462. if (beforeHooksResult && beforeHooksResult === 'STOP-INVOKE') {
  1463. return beforeHooksResult
  1464. }
  1465.  
  1466. if (hangUpHooks.length || replaceHooks.length) {
  1467. /**
  1468. * 当存在hangUpHooks或replaceHooks的时候是不会触发原来函数的
  1469. * 本质上来说hangUpHooks和replaceHooks是一样的,只是外部的定义描述不一致和分类不一致而已
  1470. */
  1471. runHooks(hangUpHooks, 'hangUp');
  1472. runHooks(replaceHooks, 'replace');
  1473. } else {
  1474. if (errorHooks.length) {
  1475. try {
  1476. execInfo.result = runTarget();
  1477. } catch (err) {
  1478. execInfo.error = err;
  1479. const errorHooksResult = runHooks(errorHooks, 'error');
  1480. /* 支持执行错误后不抛出异常的指令 */
  1481. if (errorHooksResult && errorHooksResult === 'SKIP-ERROR') ; else {
  1482. throw err
  1483. }
  1484. }
  1485. } else {
  1486. execInfo.result = runTarget();
  1487. }
  1488. }
  1489.  
  1490. /**
  1491. * 执行afterHooks,如果返回的是Promise,理论上应该进行进一步的细分处理
  1492. * 但添加细分处理逻辑后发现性能下降得比较厉害,且容易出现各种异常,所以决定不在hook里处理Promise情况
  1493. * 下面是原Promise处理逻辑,添加后会导致以下网站卡死或无法访问:
  1494. * wenku.baidu.com
  1495. * https://pubs.rsc.org/en/content/articlelanding/2021/sc/d1sc01881g#!divAbstract
  1496. * https://www.elsevier.com/connect/coronavirus-information-center
  1497. */
  1498. // if (execInfo.result && execInfo.result.then && util.isPromise(execInfo.result)) {
  1499. // execInfo.result.then(function (data) {
  1500. // execInfo.result = data
  1501. // runHooks(afterHooks, 'after')
  1502. // return Promise.resolve.apply(ctx, arguments)
  1503. // }).catch(function (err) {
  1504. // execInfo.error = err
  1505. // runHooks(errorHooks, 'error')
  1506. // return Promise.reject.apply(ctx, arguments)
  1507. // })
  1508. // }
  1509.  
  1510. runHooks(afterHooks, 'after');
  1511.  
  1512. return execInfo.result
  1513. }
  1514.  
  1515. _proxyMethodcGenerator (parentObj, methodName, originMethod, classHook, context, proxyHandler) {
  1516. const t = this;
  1517. const useProxy = t.useProxy;
  1518. let hookMethod = null;
  1519.  
  1520. /* 存在缓存则使用缓存的hookMethod */
  1521. if (t.isHook(originMethod)) {
  1522. hookMethod = originMethod;
  1523. } else if (originMethod[t.hookPropertiesKeyName] && t.isHook(originMethod[t.hookPropertiesKeyName].hookMethod)) {
  1524. hookMethod = originMethod[t.hookPropertiesKeyName].hookMethod;
  1525. }
  1526.  
  1527. if (hookMethod) {
  1528. if (!hookMethod[t.hookPropertiesKeyName].isHook) {
  1529. /* 重新标注被hook状态 */
  1530. hookMethod[t.hookPropertiesKeyName].isHook = true;
  1531. util.debug.log(`[hook method] ${util.toStr(parentObj)} ${methodName}`);
  1532. }
  1533. return hookMethod
  1534. }
  1535.  
  1536. /* 使用Proxy模式进行hook可以获得更多特性,但性能也会稍差一些 */
  1537. if (useProxy && Proxy) {
  1538. /* 注意:使用Proxy代理,hookMethod和originMethod将共用同一对象 */
  1539. const handler = { ...proxyHandler };
  1540.  
  1541. /* 下面的写法确定了proxyHandler是无法覆盖construct和apply操作的 */
  1542. if (classHook) {
  1543. handler.construct = function (target, args, newTarget) {
  1544. context = context || this;
  1545. return t._runHooks(parentObj, methodName, originMethod, hookMethod, target, context, args, true, t.hookPropertiesKeyName)
  1546. };
  1547. } else {
  1548. handler.apply = function (target, ctx, args) {
  1549. ctx = context || ctx;
  1550. return t._runHooks(parentObj, methodName, originMethod, hookMethod, target, ctx, args, false, t.hookPropertiesKeyName)
  1551. };
  1552. }
  1553.  
  1554. hookMethod = new Proxy(originMethod, handler);
  1555. } else {
  1556. hookMethod = function () {
  1557. /**
  1558. * 注意此处不能通过 context = context || this
  1559. * 然后通过把context当ctx传递过去
  1560. * 这将导致ctx引用错误
  1561. */
  1562. const ctx = context || this;
  1563. return t._runHooks(parentObj, methodName, originMethod, hookMethod, originMethod, ctx, arguments, classHook, t.hookPropertiesKeyName)
  1564. };
  1565.  
  1566. /* 确保子对象和原型链跟originMethod保持一致 */
  1567. const keys = Reflect.ownKeys(originMethod);
  1568. keys.forEach(keyName => {
  1569. try {
  1570. Object.defineProperty(hookMethod, keyName, {
  1571. get: function () {
  1572. return originMethod[keyName]
  1573. },
  1574. set: function (val) {
  1575. originMethod[keyName] = val;
  1576. }
  1577. });
  1578. } catch (err) {
  1579. // 设置defineProperty的时候出现异常,可能导致hookMethod部分功能确实,也可能不受影响
  1580. util.debug.log(`[proxyMethodcGenerator] hookMethod defineProperty abnormal. hookMethod:${methodName}, definePropertyName:${keyName}`, err);
  1581. }
  1582. });
  1583. hookMethod.prototype = originMethod.prototype;
  1584. }
  1585.  
  1586. const hookMethodProperties = hookMethod[t.hookPropertiesKeyName] = {};
  1587.  
  1588. hookMethodProperties.originMethod = originMethod;
  1589. hookMethodProperties.hookMethod = hookMethod;
  1590. hookMethodProperties.isHook = true;
  1591. hookMethodProperties.classHook = classHook;
  1592.  
  1593. util.debug.log(`[hook method] ${util.toStr(parentObj)} ${methodName}`);
  1594.  
  1595. return hookMethod
  1596. }
  1597.  
  1598. _getObjKeysByRule (obj, rule) {
  1599. let excludeRule = null;
  1600. let result = rule;
  1601.  
  1602. if (util.isObj(rule) && rule.include) {
  1603. excludeRule = rule.exclude;
  1604. rule = rule.include;
  1605. result = rule;
  1606. }
  1607.  
  1608. /**
  1609. * for in、Object.keys与Reflect.ownKeys的区别见:
  1610. * https://es6.ruanyifeng.com/#docs/object#%E5%B1%9E%E6%80%A7%E7%9A%84%E9%81%8D%E5%8E%86
  1611. */
  1612. if (rule === '*') {
  1613. result = Object.keys(obj);
  1614. } else if (rule === '**') {
  1615. result = Reflect.ownKeys(obj);
  1616. } else if (rule === '***') {
  1617. result = util.getAllKeys(obj);
  1618. } else if (util.isReg(rule)) {
  1619. result = util.getAllKeys(obj).filter(keyName => rule.test(keyName));
  1620. }
  1621.  
  1622. /* 如果存在排除规则,则需要进行排除 */
  1623. if (excludeRule) {
  1624. result = Array.isArray(result) ? result : [result];
  1625. if (util.isReg(excludeRule)) {
  1626. result = result.filter(keyName => !excludeRule.test(keyName));
  1627. } else if (Array.isArray(excludeRule)) {
  1628. result = result.filter(keyName => !excludeRule.includes(keyName));
  1629. } else {
  1630. result = result.filter(keyName => excludeRule !== keyName);
  1631. }
  1632. }
  1633.  
  1634. return util.toArr(result)
  1635. }
  1636.  
  1637. /**
  1638. * 判断某个函数是否已经被hook
  1639. * @param fn {Function} -必选 要判断的函数
  1640. * @returns {boolean}
  1641. */
  1642. isHook (fn) {
  1643. if (!fn || !fn[this.hookPropertiesKeyName]) {
  1644. return false
  1645. }
  1646. const hookMethodProperties = fn[this.hookPropertiesKeyName];
  1647. return util.isFn(hookMethodProperties.originMethod) && fn !== hookMethodProperties.originMethod
  1648. }
  1649.  
  1650. /**
  1651. * 判断对象下的某个值是否具备hook的条件
  1652. * 注意:具备hook条件和能否直接修改值是两回事,
  1653. * 在进行hook的时候还要检查descriptor.writable是否为false
  1654. * 如果为false则要修改成true才能hook成功
  1655. * @param parentObj
  1656. * @param keyName
  1657. * @returns {boolean}
  1658. */
  1659. isAllowHook (parentObj, keyName) {
  1660. /* 有些对象会设置getter,让读取值的时候就抛错,所以需要try catch 判断能否正常读取属性 */
  1661. try { if (!parentObj[keyName]) return false } catch (e) { return false }
  1662. const descriptor = Object.getOwnPropertyDescriptor(parentObj, keyName);
  1663. return !(descriptor && descriptor.configurable === false)
  1664. }
  1665.  
  1666. /**
  1667. * hook 核心函数
  1668. * @param parentObj {Object} -必选 被hook函数依赖的父对象
  1669. * @param hookMethods {Object|Array|RegExp|string} -必选 被hook函数的函数名或函数名的匹配规则
  1670. * @param fn {Function} -必选 hook之后的回调方法
  1671. * @param type {String} -可选 默认before,指定运行hook函数回调的时机,可选字符串:before、after、replace、error、hangUp
  1672. * @param classHook {Boolean} -可选 默认false,指定是否为针对new(class)操作的hook
  1673. * @param context {Object} -可选 指定运行被hook函数时的上下文对象
  1674. * @param proxyHandler {Object} -可选 仅当用Proxy进行hook时有效,默认使用的是Proxy的apply handler进行hook,如果你有特殊需求也可以配置自己的handler以实现更复杂的功能
  1675. * 附注:不使用Proxy进行hook,可以获得更高性能,但也意味着通用性更差些,对于要hook HTMLElement.prototype、EventTarget.prototype这些对象里面的非实例的函数往往会失败而导致被hook函数执行出错
  1676. * @returns {boolean}
  1677. */
  1678. hook (parentObj, hookMethods, fn, type, classHook, context, proxyHandler) {
  1679. classHook = toBoolean(classHook);
  1680. type = type || 'before';
  1681.  
  1682. if ((!util.isRef(parentObj) && !util.isFn(parentObj)) || !util.isFn(fn) || !hookMethods) {
  1683. return false
  1684. }
  1685.  
  1686. const t = this;
  1687.  
  1688. hookMethods = t._getObjKeysByRule(parentObj, hookMethods);
  1689. hookMethods.forEach(methodName => {
  1690. if (!t.isAllowHook(parentObj, methodName)) {
  1691. util.debug.log(`${util.toStr(parentObj)} [${methodName}] does not support modification`);
  1692. return false
  1693. }
  1694.  
  1695. const descriptor = Object.getOwnPropertyDescriptor(parentObj, methodName);
  1696. if (descriptor && descriptor.writable === false) {
  1697. Object.defineProperty(parentObj, methodName, { writable: true });
  1698. }
  1699.  
  1700. const originMethod = parentObj[methodName];
  1701. let hookMethod = null;
  1702.  
  1703. /* 非函数无法进行hook操作 */
  1704. if (!util.isFn(originMethod)) {
  1705. return false
  1706. }
  1707.  
  1708. hookMethod = t._proxyMethodcGenerator(parentObj, methodName, originMethod, classHook, context, proxyHandler);
  1709.  
  1710. const hookMethodProperties = hookMethod[t.hookPropertiesKeyName];
  1711. if (hookMethodProperties.classHook !== classHook) {
  1712. util.debug.log(`${util.toStr(parentObj)} [${methodName}] Cannot support functions hook and classes hook at the same time `);
  1713. return false
  1714. }
  1715.  
  1716. /* 使用hookMethod接管需要被hook的方法 */
  1717. if (parentObj[methodName] !== hookMethod) {
  1718. parentObj[methodName] = hookMethod;
  1719. }
  1720.  
  1721. t._addHook(hookMethod, fn, type, classHook);
  1722. });
  1723. }
  1724.  
  1725. /* 专门针对new操作的hook,本质上是hook函数的别名,可以少传classHook这个参数,并且明确语义 */
  1726. hookClass (parentObj, hookMethods, fn, type, context, proxyHandler) {
  1727. return this.hook(parentObj, hookMethods, fn, type, true, context, proxyHandler)
  1728. }
  1729.  
  1730. /**
  1731. * 取消对某个函数的hook
  1732. * @param parentObj {Object} -必选 要取消被hook函数依赖的父对象
  1733. * @param hookMethods {Object|Array|RegExp|string} -必选 要取消被hook函数的函数名或函数名的匹配规则
  1734. * @param type {String} -可选 默认before,指定要取消的hook类型,可选字符串:before、after、replace、error、hangUp,如果不指定该选项则取消所有类型下的所有回调
  1735. * @param fn {Function} -必选 取消指定的hook回调函数,如果不指定该选项则取消对应type类型下的所有回调
  1736. * @returns {boolean}
  1737. */
  1738. unHook (parentObj, hookMethods, type, fn) {
  1739. if (!util.isRef(parentObj) || !hookMethods) {
  1740. return false
  1741. }
  1742.  
  1743. const t = this;
  1744. hookMethods = t._getObjKeysByRule(parentObj, hookMethods);
  1745. hookMethods.forEach(methodName => {
  1746. if (!t.isAllowHook(parentObj, methodName)) {
  1747. return false
  1748. }
  1749.  
  1750. const hookMethod = parentObj[methodName];
  1751.  
  1752. if (!t.isHook(hookMethod)) {
  1753. return false
  1754. }
  1755.  
  1756. const hookMethodProperties = hookMethod[t.hookPropertiesKeyName];
  1757. const originMethod = hookMethodProperties.originMethod;
  1758.  
  1759. if (type) {
  1760. const hookKeyName = type + 'Hooks';
  1761. const hooks = hookMethodProperties[hookKeyName] || [];
  1762.  
  1763. if (fn) {
  1764. /* 删除指定类型下的指定hook函数 */
  1765. for (let i = 0; i < hooks.length; i++) {
  1766. if (fn === hooks[i]) {
  1767. hookMethodProperties[hookKeyName].splice(i, 1);
  1768. util.debug.log(`[unHook ${hookKeyName} func] ${util.toStr(parentObj)} ${methodName}`, fn);
  1769. break
  1770. }
  1771. }
  1772. } else {
  1773. /* 删除指定类型下的所有hook函数 */
  1774. if (Array.isArray(hookMethodProperties[hookKeyName])) {
  1775. hookMethodProperties[hookKeyName] = [];
  1776. util.debug.log(`[unHook all ${hookKeyName}] ${util.toStr(parentObj)} ${methodName}`);
  1777. }
  1778. }
  1779. } else {
  1780. /* 彻底还原被hook的函数 */
  1781. if (util.isFn(originMethod)) {
  1782. parentObj[methodName] = originMethod;
  1783. delete parentObj[methodName][t.hookPropertiesKeyName];
  1784.  
  1785. // Object.keys(hookMethod).forEach(keyName => {
  1786. // if (/Hooks$/.test(keyName) && Array.isArray(hookMethod[keyName])) {
  1787. // hookMethod[keyName] = []
  1788. // }
  1789. // })
  1790. //
  1791. // hookMethod.isHook = false
  1792. // parentObj[methodName] = originMethod
  1793. // delete parentObj[methodName].originMethod
  1794. // delete parentObj[methodName].hookMethod
  1795. // delete parentObj[methodName].isHook
  1796. // delete parentObj[methodName].isClassHook
  1797.  
  1798. util.debug.log(`[unHook method] ${util.toStr(parentObj)} ${methodName}`);
  1799. }
  1800. }
  1801. });
  1802. }
  1803.  
  1804. /* 源函数运行前的hook */
  1805. before (obj, hookMethods, fn, classHook, context, proxyHandler) {
  1806. return this.hook(obj, hookMethods, fn, 'before', classHook, context, proxyHandler)
  1807. }
  1808.  
  1809. /* 源函数运行后的hook */
  1810. after (obj, hookMethods, fn, classHook, context, proxyHandler) {
  1811. return this.hook(obj, hookMethods, fn, 'after', classHook, context, proxyHandler)
  1812. }
  1813.  
  1814. /* 替换掉要hook的函数,不再运行源函数,换成运行其他逻辑 */
  1815. replace (obj, hookMethods, fn, classHook, context, proxyHandler) {
  1816. return this.hook(obj, hookMethods, fn, 'replace', classHook, context, proxyHandler)
  1817. }
  1818.  
  1819. /* 源函数运行出错时的hook */
  1820. error (obj, hookMethods, fn, classHook, context, proxyHandler) {
  1821. return this.hook(obj, hookMethods, fn, 'error', classHook, context, proxyHandler)
  1822. }
  1823.  
  1824. /* 底层实现逻辑与replace一样,都是替换掉要hook的函数,不再运行源函数,只不过是为了明确语义,将源函数挂起不再执行,原则上也不再执行其他逻辑,如果要执行其他逻辑请使用replace hook */
  1825. hangUp (obj, hookMethods, fn, classHook, context, proxyHandler) {
  1826. return this.hook(obj, hookMethods, fn, 'hangUp', classHook, context, proxyHandler)
  1827. }
  1828. }
  1829.  
  1830. var hookJs = new HookJs();
  1831.  
  1832. /*!
  1833. * @name vueHooks.js
  1834. * @description 对Vue对象进行的hooks封装
  1835. * @version 0.0.1
  1836. * @author xxxily
  1837. * @date 2022/05/10 14:11
  1838. * @github https://github.com/xxxily
  1839. */
  1840.  
  1841. const hookJsPro = hookJs.hookJsPro();
  1842.  
  1843. let vueComponentHook = null;
  1844.  
  1845. const vueHooks = {
  1846. /* 对extend进行hooks封装,以便进行组件阻断 */
  1847. blockComponents (Vue, config) {
  1848. hookJsPro.before(Vue, 'extend', (args, parentObj, methodName, originMethod, execInfo, ctx) => {
  1849. const extendOpts = args[0];
  1850. // extendOpts.__file && debug.info(`[extendOptions:${extendOpts.name}]`, extendOpts.__file)
  1851.  
  1852. const hasBlockFilter = config.blockFilters && config.blockFilters.length;
  1853. if (hasBlockFilter && extendOpts.name && filtersMatch(config.blockFilters, extendOpts.name)) {
  1854. debug.info(`[block component]: name: ${extendOpts.name}`);
  1855. return 'STOP-INVOKE'
  1856. }
  1857. });
  1858.  
  1859. /* 禁止因为阻断组件的创建而导致的错误提示输出,减少不必要的信息噪音 */
  1860. hookJsPro.before(Vue.util, 'warn', (args) => {
  1861. const msg = args[0];
  1862. if (msg.includes('STOP-INVOKE')) {
  1863. return 'STOP-INVOKE'
  1864. }
  1865. });
  1866. },
  1867.  
  1868. hackVueComponent (Vue, callback) {
  1869. if (vueComponentHook) {
  1870. debug.warn('[Vue.component] you have already hacked');
  1871. return
  1872. }
  1873.  
  1874. vueComponentHook = (args, parentObj, methodName, originMethod, execInfo, ctx) => {
  1875. const name = args[0];
  1876. const opts = args[1];
  1877.  
  1878. if (callback instanceof Function) {
  1879. callback.apply(Vue, args);
  1880. } else {
  1881. /* 打印全局组件的注册信息 */
  1882. if (Vue.options.components[name]) {
  1883. debug.warn(`[Vue.component][REPEAT][old-cid:${Vue.options.components[name].cid}]`, name, opts);
  1884. } else {
  1885. debug.log('[Vue.component]', name, opts);
  1886. }
  1887. }
  1888. };
  1889.  
  1890. hookJsPro.before(Vue, 'component', vueComponentHook);
  1891. debug.log(i18n.t('debugHelper.hackVueComponent.hack') + ' (success)');
  1892. },
  1893.  
  1894. unHackVueComponent (Vue) {
  1895. if (vueComponentHook) {
  1896. hookJsPro.unHook(Vue, 'component', 'before', vueComponentHook);
  1897. vueComponentHook = null;
  1898. debug.log(i18n.t('debugHelper.hackVueComponent.unhack') + ' (success)');
  1899. } else {
  1900. debug.warn('[Vue.component] you have not hack vue component, not need to unhack');
  1901. }
  1902. },
  1903.  
  1904. hackVueUpdate () {
  1905. //
  1906. }
  1907. };
  1908.  
  1909. /*
  1910. * author: wendux
  1911. * email: 824783146@qq.com
  1912. * source code: https://github.com/wendux/Ajax-hook
  1913. */
  1914.  
  1915. // Save original XMLHttpRequest as _rxhr
  1916. var realXhr = '_rxhr';
  1917.  
  1918. var events = ['load', 'loadend', 'timeout', 'error', 'readystatechange', 'abort'];
  1919.  
  1920. function configEvent (event, xhrProxy) {
  1921. var e = {};
  1922. for (var attr in event) e[attr] = event[attr];
  1923. // xhrProxy instead
  1924. e.target = e.currentTarget = xhrProxy;
  1925. return e
  1926. }
  1927.  
  1928. function hook (proxy, win) {
  1929. win = win || window;
  1930. // Avoid double hookAjax
  1931. win[realXhr] = win[realXhr] || win.XMLHttpRequest;
  1932.  
  1933. win.XMLHttpRequest = function () {
  1934. // We shouldn't hookAjax XMLHttpRequest.prototype because we can't
  1935. // guarantee that all attributes are on the prototype。
  1936. // Instead, hooking XMLHttpRequest instance can avoid this problem.
  1937.  
  1938. var xhr = new win[realXhr]();
  1939.  
  1940. // Generate all callbacks(eg. onload) are enumerable (not undefined).
  1941. for (var i = 0; i < events.length; ++i) {
  1942. if (xhr[events[i]] === undefined) xhr[events[i]] = null;
  1943. }
  1944.  
  1945. for (var attr in xhr) {
  1946. var type = '';
  1947. try {
  1948. type = typeof xhr[attr]; // May cause exception on some browser
  1949. } catch (e) {
  1950. }
  1951. if (type === 'function') {
  1952. // hookAjax methods of xhr, such as `open`、`send` ...
  1953. this[attr] = hookFunction(attr);
  1954. } else {
  1955. Object.defineProperty(this, attr, {
  1956. get: getterFactory(attr),
  1957. set: setterFactory(attr),
  1958. enumerable: true
  1959. });
  1960. }
  1961. }
  1962. var that = this;
  1963. xhr.getProxy = function () {
  1964. return that
  1965. };
  1966. this.xhr = xhr;
  1967. };
  1968.  
  1969. Object.assign(win.XMLHttpRequest, { UNSENT: 0, OPENED: 1, HEADERS_RECEIVED: 2, LOADING: 3, DONE: 4 });
  1970.  
  1971. // Generate getter for attributes of xhr
  1972. function getterFactory (attr) {
  1973. return function () {
  1974. var v = this.hasOwnProperty(attr + '_') ? this[attr + '_'] : this.xhr[attr];
  1975. var attrGetterHook = (proxy[attr] || {}).getter;
  1976. return attrGetterHook && attrGetterHook(v, this) || v
  1977. }
  1978. }
  1979.  
  1980. // Generate setter for attributes of xhr; by this we have an opportunity
  1981. // to hookAjax event callbacks (eg: `onload`) of xhr;
  1982. function setterFactory (attr) {
  1983. return function (v) {
  1984. var xhr = this.xhr;
  1985. var that = this;
  1986. var hook = proxy[attr];
  1987. // hookAjax event callbacks such as `onload`、`onreadystatechange`...
  1988. if (attr.substring(0, 2) === 'on') {
  1989. that[attr + '_'] = v;
  1990. xhr[attr] = function (e) {
  1991. e = configEvent(e, that);
  1992. var ret = proxy[attr] && proxy[attr].call(that, xhr, e);
  1993. ret || v.call(that, e);
  1994. };
  1995. } else {
  1996. // If the attribute isn't writable, generate proxy attribute
  1997. var attrSetterHook = (hook || {}).setter;
  1998. v = attrSetterHook && attrSetterHook(v, that) || v;
  1999. this[attr + '_'] = v;
  2000. try {
  2001. // Not all attributes of xhr are writable(setter may undefined).
  2002. xhr[attr] = v;
  2003. } catch (e) {
  2004. }
  2005. }
  2006. }
  2007. }
  2008.  
  2009. // Hook methods of xhr.
  2010. function hookFunction (fun) {
  2011. return function () {
  2012. var args = [].slice.call(arguments);
  2013. if (proxy[fun]) {
  2014. var ret = proxy[fun].call(this, args, this.xhr);
  2015. // If the proxy return value exists, return it directly,
  2016. // otherwise call the function of xhr.
  2017. if (ret) return ret
  2018. }
  2019. return this.xhr[fun].apply(this.xhr, args)
  2020. }
  2021. }
  2022.  
  2023. // Return the real XMLHttpRequest
  2024. return win[realXhr]
  2025. }
  2026.  
  2027. function unHook (win) {
  2028. win = win || window;
  2029. if (win[realXhr]) win.XMLHttpRequest = win[realXhr];
  2030. win[realXhr] = undefined;
  2031. }
  2032.  
  2033. /*
  2034. * author: wendux
  2035. * email: 824783146@qq.com
  2036. * source code: https://github.com/wendux/Ajax-hook
  2037. */
  2038.  
  2039. var eventLoad = events[0];
  2040. var eventLoadEnd = events[1];
  2041. var eventTimeout = events[2];
  2042. var eventError = events[3];
  2043. var eventReadyStateChange = events[4];
  2044. var eventAbort = events[5];
  2045.  
  2046. var singleton;
  2047. var prototype = 'prototype';
  2048.  
  2049. function proxy (proxy, win) {
  2050. if (singleton) {
  2051. throw new Error('Proxy already exists')
  2052. }
  2053.  
  2054. singleton = new Proxy$1(proxy, win);
  2055. return singleton
  2056. }
  2057.  
  2058. function unProxy (win) {
  2059. singleton = null;
  2060. unHook(win);
  2061. }
  2062.  
  2063. function trim (str) {
  2064. return str.replace(/^\s+|\s+$/g, '')
  2065. }
  2066.  
  2067. function getEventTarget (xhr) {
  2068. return xhr.watcher || (xhr.watcher = document.createElement('a'))
  2069. }
  2070.  
  2071. function triggerListener (xhr, name) {
  2072. var xhrProxy = xhr.getProxy();
  2073. var callback = 'on' + name + '_';
  2074. var event = configEvent({ type: name }, xhrProxy);
  2075. xhrProxy[callback] && xhrProxy[callback](event);
  2076. var evt;
  2077. if (typeof (Event) === 'function') {
  2078. evt = new Event(name, { bubbles: false });
  2079. } else {
  2080. // https://stackoverflow.com/questions/27176983/dispatchevent-not-working-in-ie11
  2081. evt = document.createEvent('Event');
  2082. evt.initEvent(name, false, true);
  2083. }
  2084. getEventTarget(xhr).dispatchEvent(evt);
  2085. }
  2086.  
  2087. function Handler (xhr) {
  2088. this.xhr = xhr;
  2089. this.xhrProxy = xhr.getProxy();
  2090. }
  2091.  
  2092. Handler[prototype] = Object.create({
  2093. resolve: function resolve (response) {
  2094. var xhrProxy = this.xhrProxy;
  2095. var xhr = this.xhr;
  2096. xhrProxy.readyState = 4;
  2097. xhr.resHeader = response.headers;
  2098. xhrProxy.response = xhrProxy.responseText = response.response;
  2099. xhrProxy.statusText = response.statusText;
  2100. xhrProxy.status = response.status;
  2101. triggerListener(xhr, eventReadyStateChange);
  2102. triggerListener(xhr, eventLoad);
  2103. triggerListener(xhr, eventLoadEnd);
  2104. },
  2105. reject: function reject (error) {
  2106. this.xhrProxy.status = 0;
  2107. triggerListener(this.xhr, error.type);
  2108. triggerListener(this.xhr, eventLoadEnd);
  2109. }
  2110. });
  2111.  
  2112. function makeHandler (next) {
  2113. function sub (xhr) {
  2114. Handler.call(this, xhr);
  2115. }
  2116.  
  2117. sub[prototype] = Object.create(Handler[prototype]);
  2118. sub[prototype].next = next;
  2119. return sub
  2120. }
  2121.  
  2122. var RequestHandler = makeHandler(function (rq) {
  2123. var xhr = this.xhr;
  2124. rq = rq || xhr.config;
  2125. xhr.withCredentials = rq.withCredentials;
  2126. xhr.open(rq.method, rq.url, rq.async !== false, rq.user, rq.password);
  2127. for (var key in rq.headers) {
  2128. xhr.setRequestHeader(key, rq.headers[key]);
  2129. }
  2130. xhr.send(rq.body);
  2131. });
  2132.  
  2133. var ResponseHandler = makeHandler(function (response) {
  2134. this.resolve(response);
  2135. });
  2136.  
  2137. var ErrorHandler = makeHandler(function (error) {
  2138. this.reject(error);
  2139. });
  2140.  
  2141. function Proxy$1 (proxy, win) {
  2142. var onRequest = proxy.onRequest;
  2143. var onResponse = proxy.onResponse;
  2144. var onError = proxy.onError;
  2145.  
  2146. function handleResponse (xhr, xhrProxy) {
  2147. var handler = new ResponseHandler(xhr);
  2148. var ret = {
  2149. response: xhrProxy.response,
  2150. status: xhrProxy.status,
  2151. statusText: xhrProxy.statusText,
  2152. config: xhr.config,
  2153. headers: xhr.resHeader || xhr.getAllResponseHeaders().split('\r\n').reduce(function (ob, str) {
  2154. if (str === '') return ob
  2155. var m = str.split(':');
  2156. ob[m.shift()] = trim(m.join(':'));
  2157. return ob
  2158. }, {})
  2159. };
  2160. if (!onResponse) return handler.resolve(ret)
  2161. onResponse(ret, handler);
  2162. }
  2163.  
  2164. function onerror (xhr, xhrProxy, error, errorType) {
  2165. var handler = new ErrorHandler(xhr);
  2166. error = { config: xhr.config, error: error, type: errorType };
  2167. if (onError) {
  2168. onError(error, handler);
  2169. } else {
  2170. handler.next(error);
  2171. }
  2172. }
  2173.  
  2174. function preventXhrProxyCallback () {
  2175. return true
  2176. }
  2177.  
  2178. function errorCallback (errorType) {
  2179. return function (xhr, e) {
  2180. onerror(xhr, this, e, errorType);
  2181. return true
  2182. }
  2183. }
  2184.  
  2185. function stateChangeCallback (xhr, xhrProxy) {
  2186. if (xhr.readyState === 4 && xhr.status !== 0) {
  2187. handleResponse(xhr, xhrProxy);
  2188. } else if (xhr.readyState !== 4) {
  2189. triggerListener(xhr, eventReadyStateChange);
  2190. }
  2191. return true
  2192. }
  2193.  
  2194. return hook({
  2195. onload: preventXhrProxyCallback,
  2196. onloadend: preventXhrProxyCallback,
  2197. onerror: errorCallback(eventError),
  2198. ontimeout: errorCallback(eventTimeout),
  2199. onabort: errorCallback(eventAbort),
  2200. onreadystatechange: function (xhr) {
  2201. return stateChangeCallback(xhr, this)
  2202. },
  2203. open: function open (args, xhr) {
  2204. var _this = this;
  2205. var config = xhr.config = { headers: {} };
  2206. config.method = args[0];
  2207. config.url = args[1];
  2208. config.async = args[2];
  2209. config.user = args[3];
  2210. config.password = args[4];
  2211. config.xhr = xhr;
  2212. var evName = 'on' + eventReadyStateChange;
  2213. if (!xhr[evName]) {
  2214. xhr[evName] = function () {
  2215. return stateChangeCallback(xhr, _this)
  2216. };
  2217. }
  2218.  
  2219. // 如果有请求拦截器,则在调用onRequest后再打开链接。因为onRequest最佳调用时机是在send前,
  2220. // 所以我们在send拦截函数中再手动调用open,因此返回true阻止xhr.open调用。
  2221. //
  2222. // 如果没有请求拦截器,则不用阻断xhr.open调用
  2223. if (onRequest) return true
  2224. },
  2225. send: function (args, xhr) {
  2226. var config = xhr.config;
  2227. config.withCredentials = xhr.withCredentials;
  2228. config.body = args[0];
  2229. if (onRequest) {
  2230. // In 'onRequest', we may call XHR's event handler, such as `xhr.onload`.
  2231. // However, XHR's event handler may not be set until xhr.send is called in
  2232. // the user's code, so we use `setTimeout` to avoid this situation
  2233. var req = function () {
  2234. onRequest(config, new RequestHandler(xhr));
  2235. };
  2236. config.async === false ? req() : setTimeout(req);
  2237. return true
  2238. }
  2239. },
  2240. setRequestHeader: function (args, xhr) {
  2241. // Collect request headers
  2242. xhr.config.headers[args[0].toLowerCase()] = args[1];
  2243. return true
  2244. },
  2245. addEventListener: function (args, xhr) {
  2246. var _this = this;
  2247. if (events.indexOf(args[0]) !== -1) {
  2248. var handler = args[1];
  2249. getEventTarget(xhr).addEventListener(args[0], function (e) {
  2250. var event = configEvent(e, _this);
  2251. event.type = args[0];
  2252. event.isTrusted = true;
  2253. handler.call(_this, event);
  2254. });
  2255. return true
  2256. }
  2257. },
  2258. getAllResponseHeaders: function (_, xhr) {
  2259. var headers = xhr.resHeader;
  2260. if (headers) {
  2261. var header = '';
  2262. for (var key in headers) {
  2263. header += key + ': ' + headers[key] + '\r\n';
  2264. }
  2265. return header
  2266. }
  2267. },
  2268. getResponseHeader: function (args, xhr) {
  2269. var headers = xhr.resHeader;
  2270. if (headers) {
  2271. return headers[(args[0] || '').toLowerCase()]
  2272. }
  2273. }
  2274. }, win)
  2275. }
  2276.  
  2277. /*!
  2278. * @name cacheStore.js
  2279. * @description 接口请求缓存存储管理模块
  2280. * @version 0.0.1
  2281. * @author xxxily
  2282. * @date 2022/05/13 09:36
  2283. * @github https://github.com/xxxily
  2284. */
  2285. const localforage = window.localforage;
  2286. const CryptoJS = window.CryptoJS;
  2287.  
  2288. function md5 (str) {
  2289. return CryptoJS.MD5(str).toString()
  2290. }
  2291.  
  2292. function createHash (config) {
  2293. if (config._hash_) {
  2294. return config._hash_
  2295. }
  2296.  
  2297. let url = config.url || '';
  2298.  
  2299. /**
  2300. * 如果检测到url使用了时间戳来防止缓存,则进行替换,进行缓存
  2301. * TODO
  2302. * 注意,这很可能会导致误伤,例如url上的时间戳并不是用来清理缓存的,而是某个时间点的参数
  2303. */
  2304. if (/=\d{13}/.test(url)) {
  2305. url = url.replace(/=\d{13}/, '=cache');
  2306. }
  2307.  
  2308. let hashStr = url;
  2309.  
  2310. if (config.method.toUpperCase() === 'POST') {
  2311. hashStr += JSON.stringify(config.data) + JSON.stringify(config.body);
  2312. }
  2313.  
  2314. const hash = md5(hashStr);
  2315. config._hash_ = hash;
  2316.  
  2317. return hash
  2318. }
  2319.  
  2320. class CacheStore {
  2321. constructor (opts = {
  2322. localforageConfig: {}
  2323. }) {
  2324. this.store = localforage.createInstance(Object.assign({
  2325. name: 'vue-debug-helper-cache',
  2326. storeName: 'ajax-cache'
  2327. }, opts.localforageConfig));
  2328.  
  2329. /* 外部应该使用同样的hash生成方法,否则无法正常命中缓存规则 */
  2330. this.createHash = createHash;
  2331. }
  2332.  
  2333. async getCache (config) {
  2334. const hash = createHash(config);
  2335. const data = await this.store.getItem(hash);
  2336. return data
  2337. }
  2338.  
  2339. async setCache (response, filter) {
  2340. const headers = response.headers || {};
  2341. if (String(headers['content-type']).includes(filter || 'application/json')) {
  2342. const hash = createHash(response.config);
  2343. await this.store.setItem(hash, response.response);
  2344.  
  2345. /* 设置缓存的时候顺便更新缓存相关的基础信息,注意,该信息并不能100%被同步到本地 */
  2346. await this.updateCacheInfo(response.config);
  2347.  
  2348. debug.log(`[cacheStore setCache] ${response.config.url}`, response);
  2349. }
  2350. }
  2351.  
  2352. async getCacheInfo (config) {
  2353. const hash = config ? this.createHash(config) : '';
  2354. if (this._cacheInfo_) {
  2355. return hash ? this._cacheInfo_[hash] : this._cacheInfo_
  2356. }
  2357.  
  2358. /* 在没将cacheInfo加载到内存前,只能单线程获取cacheInfo,防止多线程获取cacheInfo时出现问题 */
  2359. if (this._takeingCacheInfo_) {
  2360. const getCacheInfoHanderList = this._getCacheInfoHanderList_ || [];
  2361. const P = new Promise((resolve, reject) => {
  2362. getCacheInfoHanderList.push({
  2363. resolve,
  2364. config
  2365. });
  2366. });
  2367. this._getCacheInfoHanderList_ = getCacheInfoHanderList;
  2368. return P
  2369. }
  2370.  
  2371. this._takeingCacheInfo_ = true;
  2372. const cacheInfo = await this.store.getItem('ajaxCacheInfo') || {};
  2373. this._cacheInfo_ = cacheInfo;
  2374.  
  2375. delete this._takeingCacheInfo_;
  2376. if (this._getCacheInfoHanderList_) {
  2377. this._getCacheInfoHanderList_.forEach(async (handler) => {
  2378. handler.resolve(await this.getCacheInfo(handler.config));
  2379. });
  2380. delete this._getCacheInfoHanderList_;
  2381. }
  2382.  
  2383. return hash ? cacheInfo[hash] : cacheInfo
  2384. }
  2385.  
  2386. async updateCacheInfo (config) {
  2387. const cacheInfo = await this.getCacheInfo();
  2388.  
  2389. if (config) {
  2390. const hash = createHash(config);
  2391. if (hash && config) {
  2392. const info = {
  2393. url: config.url,
  2394. cacheTime: Date.now()
  2395. };
  2396.  
  2397. // 增加或更新缓存的基本信息
  2398. cacheInfo[hash] = info;
  2399. }
  2400. }
  2401.  
  2402. if (!this._updateCacheInfoIsWorking_) {
  2403. this._updateCacheInfoIsWorking_ = true;
  2404. await this.store.setItem('ajaxCacheInfo', cacheInfo);
  2405. this._updateCacheInfoIsWorking_ = false;
  2406. }
  2407. }
  2408.  
  2409. /**
  2410. * 清理已过期的缓存数据
  2411. * @param {number} expires 指定过期时间,单位:毫秒
  2412. * @returns
  2413. */
  2414. async cleanCache (expires) {
  2415. if (!expires) {
  2416. return
  2417. }
  2418.  
  2419. const cacheInfo = await this.getCacheInfo();
  2420. const cacheInfoKeys = Object.keys(cacheInfo);
  2421. const now = Date.now();
  2422.  
  2423. const storeKeys = await this.store.keys();
  2424.  
  2425. const needKeepKeys = cacheInfoKeys.filter(key => now - cacheInfo[key].cacheTime < expires);
  2426. needKeepKeys.push('ajaxCacheInfo');
  2427.  
  2428. const clearResult = [];
  2429.  
  2430. /* 清理不需要的数据 */
  2431. storeKeys.forEach((key) => {
  2432. if (!needKeepKeys.includes(key)) {
  2433. clearResult.push(this._cacheInfo_[key] || key);
  2434.  
  2435. this.store.removeItem(key);
  2436. delete this._cacheInfo_[key];
  2437. }
  2438. });
  2439.  
  2440. /* 更新缓存信息 */
  2441. if (clearResult.length) {
  2442. await this.updateCacheInfo();
  2443. debug.log('[cacheStore cleanCache] clearResult:', clearResult);
  2444. }
  2445. }
  2446.  
  2447. async get (key) {
  2448. const data = await this.store.getItem(key);
  2449. debug.log('[cacheStore]', key, data);
  2450. return data
  2451. }
  2452.  
  2453. async set (key, data) {
  2454. await this.store.setItem(key, data);
  2455. debug.log('[cacheStore]', key, data);
  2456. }
  2457.  
  2458. async remove (key) {
  2459. await this.store.removeItem(key);
  2460. debug.log('[cacheStore]', key);
  2461. }
  2462.  
  2463. async clear () {
  2464. await this.store.clear();
  2465. debug.log('[cacheStore] clear');
  2466. }
  2467.  
  2468. async keys () {
  2469. const keys = await this.store.keys();
  2470. debug.log('[cacheStore] keys', keys);
  2471. return keys
  2472. }
  2473. }
  2474.  
  2475. var cacheStore = new CacheStore();
  2476.  
  2477. /*!
  2478. * @name ajaxHooks.js
  2479. * @description 底层请求hook
  2480. * @version 0.0.1
  2481. * @author xxxily
  2482. * @date 2022/05/12 17:46
  2483. * @github https://github.com/xxxily
  2484. */
  2485.  
  2486. /**
  2487. * 判断是否符合进行缓存控制操作的条件
  2488. * @param {object} config
  2489. * @returns {boolean}
  2490. */
  2491. function useCache (config) {
  2492. const ajaxCache = helper.config.ajaxCache;
  2493. if (ajaxCache.enabled) {
  2494. return filtersMatch(ajaxCache.filters, config.url)
  2495. } else {
  2496. return false
  2497. }
  2498. }
  2499.  
  2500. let ajaxHooksWin = window;
  2501.  
  2502. const ajaxHooks = {
  2503. hook (win = ajaxHooksWin) {
  2504. proxy({
  2505. onRequest: async (config, handler) => {
  2506. let hitCache = false;
  2507.  
  2508. if (useCache(config)) {
  2509. const cacheInfo = await cacheStore.getCacheInfo(config);
  2510. const cache = await cacheStore.getCache(config);
  2511.  
  2512. if (cache && cacheInfo) {
  2513. const isExpires = Date.now() - cacheInfo.cacheTime > helper.config.ajaxCache.expires;
  2514.  
  2515. if (!isExpires) {
  2516. handler.resolve({
  2517. config: config,
  2518. status: 200,
  2519. headers: { 'content-type': 'application/json' },
  2520. response: cache
  2521. });
  2522.  
  2523. hitCache = true;
  2524. }
  2525. }
  2526. }
  2527.  
  2528. if (hitCache) {
  2529. debug.warn(`[ajaxHooks] use cache:${config.method} ${config.url}`, config);
  2530. } else {
  2531. handler.next(config);
  2532. }
  2533. },
  2534.  
  2535. onError: (err, handler) => {
  2536. handler.next(err);
  2537. },
  2538.  
  2539. onResponse: async (response, handler) => {
  2540. if (useCache(response.config)) {
  2541. // 加入缓存
  2542. cacheStore.setCache(response, 'application/json');
  2543. }
  2544.  
  2545. handler.next(response);
  2546. }
  2547. }, win);
  2548. },
  2549.  
  2550. unHook (win = ajaxHooksWin) {
  2551. unProxy(win);
  2552. },
  2553.  
  2554. init (win) {
  2555. ajaxHooksWin = win;
  2556.  
  2557. if (helper.config.ajaxCache.enabled) {
  2558. ajaxHooks.hook(ajaxHooksWin);
  2559. }
  2560.  
  2561. // hookJs.before(win, 'fetch', (args, parentObj, methodName, originMethod, execInfo, ctx) => {
  2562. // debug.log('[ajaxHooks] fetch', args)
  2563. // })
  2564.  
  2565. // hookJs.after(win, 'fetch', async (args, parentObj, methodName, originMethod, execInfo, ctx) => {
  2566. // debug.log('[ajaxHooks] fetch after', args, execInfo, await execInfo.result)
  2567. // })
  2568.  
  2569. /* 定时清除接口的缓存数据,防止不断堆积 */
  2570. setTimeout(() => {
  2571. cacheStore.cleanCache(helper.config.ajaxCache.expires);
  2572. }, 1000 * 10);
  2573. }
  2574. };
  2575.  
  2576. /*!
  2577. * @name performanceObserver.js
  2578. * @description 进行性能监测结果的打印
  2579. * @version 0.0.1
  2580. * @author xxxily
  2581. * @date 2022/05/11 10:39
  2582. * @github https://github.com/xxxily
  2583. */
  2584.  
  2585. const performanceObserver = {
  2586. observer: null,
  2587. init () {
  2588. if (typeof PerformanceObserver === 'undefined') {
  2589. debug.log(i18n.t('debugHelper.performanceObserver.notSupport'));
  2590. return false
  2591. }
  2592.  
  2593. if (performanceObserver.observer && performanceObserver.observer.disconnect) {
  2594. performanceObserver.observer.disconnect();
  2595. }
  2596.  
  2597. /* 不进行性能观察 */
  2598. if (!helper.config.performanceObserver.enabled) {
  2599. performanceObserver.observer = null;
  2600. return false
  2601. }
  2602.  
  2603. // https://developer.mozilla.org/zh-CN/docs/Web/API/PerformanceObserver/observe
  2604. performanceObserver.observer = new PerformanceObserver(function (list, observer) {
  2605. if (!helper.config.performanceObserver.enabled) {
  2606. return
  2607. }
  2608.  
  2609. const entries = list.getEntries();
  2610. for (let i = 0; i < entries.length; i++) {
  2611. const entry = entries[i];
  2612. debug.info(`[performanceObserver ${entry.entryType}]`, entry);
  2613. }
  2614. });
  2615.  
  2616. // https://runebook.dev/zh-CN/docs/dom/performanceentry/entrytype
  2617. performanceObserver.observer.observe({ entryTypes: helper.config.performanceObserver.entryTypes });
  2618. }
  2619. };
  2620.  
  2621. /*!
  2622. * @name inspect.js
  2623. * @description vue组件审查模块
  2624. * @version 0.0.1
  2625. * @author xxxily
  2626. * @date 2022/05/10 18:25
  2627. * @github https://github.com/xxxily
  2628. */
  2629.  
  2630. const overlaySelector = 'vue-debugger-overlay';
  2631. const $ = window.$;
  2632. let currentComponent = null;
  2633.  
  2634. const inspect = {
  2635. findComponentsByElement (el) {
  2636. let result = null;
  2637. let deep = 0;
  2638. let parent = el;
  2639. while (parent) {
  2640. if (deep >= 50) {
  2641. break
  2642. }
  2643.  
  2644. if (parent.__vue__) {
  2645. result = parent;
  2646. break
  2647. }
  2648.  
  2649. deep++;
  2650. parent = parent.parentNode;
  2651. }
  2652.  
  2653. return result
  2654. },
  2655.  
  2656. initContextMenu () {
  2657. if (this._hasInitContextMenu_) {
  2658. return
  2659. }
  2660.  
  2661. function createComponentMenuItem (vueComponent, deep = 0) {
  2662. let componentMenu = {};
  2663. if (vueComponent) {
  2664. helper.methods.initComponentInfo(vueComponent);
  2665.  
  2666. componentMenu = {
  2667. consoleComponent: {
  2668. name: `${i18n.t('contextMenu.consoleComponent')} <${vueComponent._componentName}>`,
  2669. icon: 'fa-eye',
  2670. callback: function (key, options) {
  2671. debug.log(`[vueComponent] ${vueComponent._componentTag}`, vueComponent);
  2672. }
  2673. },
  2674. consoleComponentData: {
  2675. name: `${i18n.t('contextMenu.consoleComponentData')} <${vueComponent._componentName}>`,
  2676. icon: 'fa-eye',
  2677. callback: function (key, options) {
  2678. debug.log(`[vueComponentData] ${vueComponent._componentTag}`, vueComponent.$data);
  2679. }
  2680. },
  2681. consoleComponentProps: {
  2682. name: `${i18n.t('contextMenu.consoleComponentProps')} <${vueComponent._componentName}>`,
  2683. icon: 'fa-eye',
  2684. callback: function (key, options) {
  2685. debug.log(`[vueComponentProps] ${vueComponent._componentTag}`, vueComponent.$props);
  2686. }
  2687. }
  2688. // consoleComponentChain: {
  2689. // name: `${i18n.t('contextMenu.consoleComponentChain')} <${vueComponent._componentName}>`,
  2690. // icon: 'fa-eye',
  2691. // callback: function (key, options) {
  2692. // debug.log(`[vueComponentMethods] ${vueComponent._componentTag}`, vueComponent._componentChain)
  2693. // }
  2694. // }
  2695. };
  2696. }
  2697.  
  2698. if (vueComponent.$parent && deep <= 5) {
  2699. componentMenu.parentComponent = {
  2700. name: `${i18n.t('contextMenu.consoleParentComponent')} <${vueComponent.$parent._componentName}>`,
  2701. icon: 'fa-eye',
  2702. items: createComponentMenuItem(vueComponent.$parent, deep + 1)
  2703. };
  2704. }
  2705.  
  2706. const file = vueComponent.options?.__file || vueComponent.$options?.__file || '';
  2707. let copyFilePath = {};
  2708. if (file) {
  2709. copyFilePath = {
  2710. copyFilePath: {
  2711. name: `${i18n.t('contextMenu.copyFilePath')}`,
  2712. icon: 'fa-copy',
  2713. callback: function (key, options) {
  2714. debug.log(`[componentFilePath ${vueComponent._componentName}] ${file}`);
  2715. copyToClipboard(file);
  2716. }
  2717. }
  2718. };
  2719. }
  2720.  
  2721. componentMenu.componentAction = {
  2722. name: `${i18n.t('contextMenu.componentAction')} <${vueComponent._componentName}>`,
  2723. icon: 'fa-cog',
  2724. items: {
  2725. ...copyFilePath,
  2726. copyComponentName: {
  2727. name: `${i18n.t('contextMenu.copyComponentName')} <${vueComponent._componentName}>`,
  2728. icon: 'fa-copy',
  2729. callback: function (key, options) {
  2730. copyToClipboard(vueComponent._componentName);
  2731. }
  2732. },
  2733. copyComponentData: {
  2734. name: `${i18n.t('contextMenu.copyComponentData')} <${vueComponent._componentName}>`,
  2735. icon: 'fa-copy',
  2736. callback: function (key, options) {
  2737. const data = JSON.stringify(vueComponent.$data, null, 2);
  2738. debug.log(`[vueComponentData] ${vueComponent._componentName}`, JSON.parse(data));
  2739. debug.log(data);
  2740. copyToClipboard(data);
  2741. }
  2742. },
  2743. copyComponentProps: {
  2744. name: `${i18n.t('contextMenu.copyComponentProps')} <${vueComponent._componentName}>`,
  2745. icon: 'fa-copy',
  2746. callback: function (key, options) {
  2747. const props = JSON.stringify(vueComponent.$props, null, 2);
  2748. debug.log(`[vueComponentProps] ${vueComponent._componentName}`, JSON.parse(props));
  2749. debug.log(props);
  2750. copyToClipboard(props);
  2751. }
  2752. },
  2753. // copyComponentTag: {
  2754. // name: `${i18n.t('contextMenu.copyComponentTag')} <${vueComponent._componentName}>`,
  2755. // icon: 'fa-copy',
  2756. // callback: function (key, options) {
  2757. // copyToClipboard(vueComponent._componentTag)
  2758. // }
  2759. // },
  2760. copyComponentUid: {
  2761. name: `${i18n.t('contextMenu.copyComponentUid')} -> ${vueComponent._uid}`,
  2762. icon: 'fa-copy',
  2763. callback: function (key, options) {
  2764. copyToClipboard(vueComponent._uid);
  2765. }
  2766. },
  2767. copyComponentChian: {
  2768. name: `${i18n.t('contextMenu.copyComponentChian')}`,
  2769. icon: 'fa-copy',
  2770. callback: function (key, options) {
  2771. debug.log(`[vueComponentChain] ${vueComponent._componentName}`, vueComponent._componentChain);
  2772. copyToClipboard(vueComponent._componentChain);
  2773. }
  2774. },
  2775. findComponents: {
  2776. name: `${i18n.t('contextMenu.findComponents')} <${vueComponent._componentName}>`,
  2777. icon: 'fa-search',
  2778. callback: function (key, options) {
  2779. functionCall.findComponents(vueComponent._componentName);
  2780. }
  2781. },
  2782. printLifeCycleInfo: {
  2783. name: `${i18n.t('contextMenu.printLifeCycleInfo')} <${vueComponent._componentName}>`,
  2784. icon: 'fa-print',
  2785. callback: function (key, options) {
  2786. functionCall.printLifeCycleInfo(vueComponent._componentName);
  2787. }
  2788. },
  2789. blockComponents: {
  2790. name: `${i18n.t('contextMenu.blockComponents')} <${vueComponent._componentName}>`,
  2791. icon: 'fa-ban',
  2792. callback: function (key, options) {
  2793. functionCall.blockComponents(vueComponent._componentName);
  2794. }
  2795. }
  2796. }
  2797. };
  2798.  
  2799. return componentMenu
  2800. }
  2801.  
  2802. $.contextMenu({
  2803. selector: 'body.vue-debug-helper-inspect-mode',
  2804. zIndex: 2147483647,
  2805. build: function ($trigger, e) {
  2806. const conf = helper.config;
  2807. const vueComponent = currentComponent ? currentComponent.__vue__ : null;
  2808.  
  2809. let componentMenu = {};
  2810. if (vueComponent) {
  2811. componentMenu = createComponentMenuItem(vueComponent);
  2812. componentMenu.componentMenuSeparator = '---------';
  2813. }
  2814.  
  2815. const commonMenu = {
  2816. componentsStatistics: {
  2817. name: i18n.t('debugHelper.componentsStatistics'),
  2818. icon: 'fa-thin fa-info-circle',
  2819. callback: functionCall.componentsStatistics
  2820. },
  2821. componentsSummaryStatisticsSort: {
  2822. name: i18n.t('debugHelper.componentsSummaryStatisticsSort'),
  2823. icon: 'fa-thin fa-info-circle',
  2824. callback: functionCall.componentsSummaryStatisticsSort
  2825. },
  2826. destroyStatisticsSort: {
  2827. name: i18n.t('debugHelper.destroyStatisticsSort'),
  2828. icon: 'fa-regular fa-trash',
  2829. callback: functionCall.destroyStatisticsSort
  2830. },
  2831. clearAll: {
  2832. name: i18n.t('debugHelper.clearAll'),
  2833. icon: 'fa-regular fa-close',
  2834. callback: functionCall.clearAll
  2835. },
  2836. statisticsSeparator: '---------',
  2837. findComponents: {
  2838. name: i18n.t('debugHelper.findComponents'),
  2839. icon: 'fa-regular fa-search',
  2840. callback: () => {
  2841. functionCall.findComponents();
  2842. }
  2843. },
  2844. blockComponents: {
  2845. name: i18n.t('debugHelper.blockComponents'),
  2846. icon: 'fa-regular fa-ban',
  2847. callback: () => {
  2848. functionCall.blockComponents();
  2849. }
  2850. },
  2851. printLifeCycleInfo: {
  2852. name: conf.lifecycle.show ? i18n.t('debugHelper.notPrintLifeCycleInfo') : i18n.t('debugHelper.printLifeCycleInfo'),
  2853. icon: 'fa-regular fa-life-ring',
  2854. callback: () => {
  2855. conf.lifecycle.show ? functionCall.notPrintLifeCycleInfo() : functionCall.printLifeCycleInfo();
  2856. }
  2857. },
  2858. dd: {
  2859. name: conf.dd.enabled ? i18n.t('debugHelper.undd') : i18n.t('debugHelper.dd'),
  2860. icon: 'fa-regular fa-arrows-alt',
  2861. callback: conf.dd.enabled ? functionCall.undd : functionCall.dd
  2862. },
  2863. toggleHackVueComponent: {
  2864. name: conf.hackVueComponent ? i18n.t('debugHelper.hackVueComponent.unhack') : i18n.t('debugHelper.hackVueComponent.hack'),
  2865. icon: 'fa-regular fa-bug',
  2866. callback: functionCall.toggleHackVueComponent
  2867. },
  2868. togglePerformanceObserver: {
  2869. name: conf.performanceObserver.enabled ? i18n.t('debugHelper.performanceObserverStatus.off') : i18n.t('debugHelper.performanceObserverStatus.on'),
  2870. icon: 'fa-regular fa-paint-brush',
  2871. callback: functionCall.togglePerformanceObserver
  2872. },
  2873. toggleAjaxCache: {
  2874. name: conf.ajaxCache.enabled ? i18n.t('debugHelper.ajaxCacheStatus.off') : i18n.t('debugHelper.ajaxCacheStatus.on'),
  2875. icon: 'fa-regular fa-database',
  2876. callback: functionCall.toggleAjaxCache
  2877. },
  2878. clearAjaxCache: {
  2879. name: i18n.t('debugHelper.clearAjaxCache'),
  2880. icon: 'fa-regular fa-database',
  2881. callback: functionCall.clearAjaxCache
  2882. },
  2883. measureSelectorInterval: {
  2884. name: i18n.t('debugHelper.measureSelectorInterval'),
  2885. icon: 'fa-regular fa-clock-o',
  2886. callback: functionCall.measureSelectorInterval
  2887. },
  2888. commonEndSeparator: '---------',
  2889. toggleInspect: {
  2890. name: conf.inspect.enabled ? i18n.t('debugHelper.inspectStatus.off') : i18n.t('debugHelper.inspectStatus.on'),
  2891. icon: 'fa-regular fa-eye',
  2892. callback: functionCall.toggleInspect
  2893. }
  2894. };
  2895.  
  2896. const menu = {
  2897. callback: function (key, options) {
  2898. debug.log(`[contextMenu] ${key}`);
  2899. },
  2900. items: {
  2901. refresh: {
  2902. name: i18n.t('refreshPage'),
  2903. icon: 'fa-refresh',
  2904. callback: function (key, options) {
  2905. window.location.reload();
  2906. }
  2907. },
  2908. sep0: '---------',
  2909. ...componentMenu,
  2910. ...commonMenu,
  2911. quit: {
  2912. name: i18n.t('quit'),
  2913. icon: 'fa-close',
  2914. callback: function ($element, key, item) {
  2915. return 'context-menu-icon context-menu-icon-quit'
  2916. }
  2917. }
  2918. }
  2919. };
  2920.  
  2921. return menu
  2922. }
  2923. });
  2924.  
  2925. this._hasInitContextMenu_ = true;
  2926. },
  2927.  
  2928. setOverlay (el) {
  2929. let overlay = document.querySelector('#' + overlaySelector);
  2930. if (!overlay) {
  2931. overlay = document.createElement('div');
  2932. overlay.id = overlaySelector;
  2933.  
  2934. const infoBox = document.createElement('div');
  2935. infoBox.className = 'vue-debugger-component-info';
  2936.  
  2937. const styleDom = document.createElement('style');
  2938. styleDom.appendChild(document.createTextNode(`
  2939. #${overlaySelector} {
  2940. position: fixed;
  2941. z-index: 2147483647;
  2942. background-color: rgba(65, 184, 131, 0.15);
  2943. padding: 5px;
  2944. font-size: 11px;
  2945. pointer-events: none;
  2946. box-size: border-box;
  2947. border-radius: 3px;
  2948. overflow: visible;
  2949. }
  2950.  
  2951. #${overlaySelector} .vue-debugger-component-info {
  2952. position: absolute;
  2953. top: -30px;
  2954. left: 0;
  2955. line-height: 1.5;
  2956. display: inline-block;
  2957. padding: 4px 8px;
  2958. border-radius: 3px;
  2959. background-color: #fff;
  2960. font-family: monospace;
  2961. font-size: 11px;
  2962. color: rgb(51, 51, 51);
  2963. text-align: center;
  2964. border: 1px solid rgba(65, 184, 131, 0.5);
  2965. background-clip: padding-box;
  2966. pointer-events: none;
  2967. white-space: nowrap;
  2968. }
  2969. `));
  2970.  
  2971. overlay.appendChild(infoBox);
  2972. overlay.appendChild(styleDom);
  2973. document.body.appendChild(overlay);
  2974. }
  2975.  
  2976. /* 批量设置样式,减少样式扰动 */
  2977. const rect = el.getBoundingClientRect();
  2978. const overlayStyle = [
  2979. `width: ${rect.width}px;`,
  2980. `height: ${rect.height}px;`,
  2981. `top: ${rect.top}px;`,
  2982. `left: ${rect.left}px;`,
  2983. 'display: block;'
  2984. ].join(' ');
  2985. overlay.setAttribute('style', overlayStyle);
  2986.  
  2987. const vm = el.__vue__;
  2988. if (vm) {
  2989. helper.methods.initComponentInfo(vm);
  2990. const name = vm._componentName || vm._componentTag || vm._uid;
  2991. const infoBox = overlay.querySelector('.vue-debugger-component-info');
  2992.  
  2993. infoBox.innerHTML = [
  2994. '<span style="opacity: 0.6;">&lt;</span>',
  2995. `<span style="font-weight: bold; color: rgb(9, 171, 86);">${name}</span>`,
  2996. '<span style="opacity: 0.6;">&gt;</span>',
  2997. `<span style="opacity: 0.5; margin-left: 6px;">${Math.round(rect.width)}<span style="margin-right: 2px; margin-left: 2px;">×</span>${Math.round(rect.height)}</span>`
  2998. ].join('');
  2999.  
  3000. rect.y < 32 ? (infoBox.style.top = '0') : (infoBox.style.top = '-30px');
  3001. }
  3002.  
  3003. $(document.body).addClass('vue-debug-helper-inspect-mode');
  3004. inspect.initContextMenu();
  3005. },
  3006.  
  3007. clearOverlay () {
  3008. $(document.body).removeClass('vue-debug-helper-inspect-mode');
  3009. const overlay = document.querySelector('#vue-debugger-overlay');
  3010. if (overlay) {
  3011. overlay.style.display = 'none';
  3012. }
  3013. },
  3014.  
  3015. init (Vue) {
  3016. document.body.addEventListener('mouseover', (event) => {
  3017. if (!helper.config.inspect.enabled) {
  3018. return
  3019. }
  3020.  
  3021. const componentEl = inspect.findComponentsByElement(event.target);
  3022.  
  3023. if (componentEl) {
  3024. currentComponent = componentEl;
  3025. inspect.setOverlay(componentEl);
  3026. } else {
  3027. currentComponent = null;
  3028. }
  3029. });
  3030. }
  3031. };
  3032.  
  3033. /**
  3034. * 元素监听器
  3035. * @param selector -必选
  3036. * @param fn -必选,元素存在时的回调
  3037. * @param shadowRoot -可选 指定监听某个shadowRoot下面的DOM元素
  3038. * 参考:https://javascript.ruanyifeng.com/dom/mutationobserver.html
  3039. */
  3040. function ready (selector, fn, shadowRoot) {
  3041. const win = window;
  3042. const docRoot = shadowRoot || win.document.documentElement;
  3043. if (!docRoot) return false
  3044. const MutationObserver = win.MutationObserver || win.WebKitMutationObserver;
  3045. const listeners = docRoot._MutationListeners || [];
  3046.  
  3047. function $ready (selector, fn) {
  3048. // 储存选择器和回调函数
  3049. listeners.push({
  3050. selector: selector,
  3051. fn: fn
  3052. });
  3053.  
  3054. /* 增加监听对象 */
  3055. if (!docRoot._MutationListeners || !docRoot._MutationObserver) {
  3056. docRoot._MutationListeners = listeners;
  3057. docRoot._MutationObserver = new MutationObserver(() => {
  3058. for (let i = 0; i < docRoot._MutationListeners.length; i++) {
  3059. const item = docRoot._MutationListeners[i];
  3060. check(item.selector, item.fn);
  3061. }
  3062. });
  3063.  
  3064. docRoot._MutationObserver.observe(docRoot, {
  3065. childList: true,
  3066. subtree: true
  3067. });
  3068. }
  3069.  
  3070. // 检查节点是否已经在DOM中
  3071. check(selector, fn);
  3072. }
  3073.  
  3074. function check (selector, fn) {
  3075. const elements = docRoot.querySelectorAll(selector);
  3076. for (let i = 0; i < elements.length; i++) {
  3077. const element = elements[i];
  3078. element._MutationReadyList_ = element._MutationReadyList_ || [];
  3079. if (!element._MutationReadyList_.includes(fn)) {
  3080. element._MutationReadyList_.push(fn);
  3081. fn.call(element, element);
  3082. }
  3083. }
  3084. }
  3085.  
  3086. const selectorArr = Array.isArray(selector) ? selector : [selector];
  3087. selectorArr.forEach(selector => $ready(selector, fn));
  3088. }
  3089.  
  3090. /*!
  3091. * @name functionCall.js
  3092. * @description 统一的提供外部功能调用管理模块
  3093. * @version 0.0.1
  3094. * @author xxxily
  3095. * @date 2022/04/27 17:42
  3096. * @github https://github.com/xxxily
  3097. */
  3098.  
  3099. const functionCall = {
  3100. toggleInspect () {
  3101. helper.config.inspect.enabled = !helper.config.inspect.enabled;
  3102. debug.log(`${i18n.t('debugHelper.toggleInspect')} success (${helper.config.inspect.enabled})`);
  3103.  
  3104. if (!helper.config.inspect.enabled) {
  3105. inspect.clearOverlay();
  3106. }
  3107. },
  3108. viewVueDebugHelperObject () {
  3109. debug.log(i18n.t('debugHelper.viewVueDebugHelperObject'), helper);
  3110. },
  3111. componentsStatistics () {
  3112. const result = helper.methods.componentsStatistics();
  3113. let total = 0;
  3114.  
  3115. /* 提供友好的可视化展示方式 */
  3116. console.table && console.table(result.map(item => {
  3117. total += item.componentInstance.length;
  3118. return {
  3119. componentName: item.componentName,
  3120. count: item.componentInstance.length
  3121. }
  3122. }));
  3123.  
  3124. debug.log(`${i18n.t('debugHelper.componentsStatistics')} (total:${total})`, result);
  3125. },
  3126. destroyStatisticsSort () {
  3127. const result = helper.methods.destroyStatisticsSort();
  3128. let total = 0;
  3129.  
  3130. /* 提供友好的可视化展示方式 */
  3131. console.table && console.table(result.map(item => {
  3132. const durationList = item.destroyList.map(item => item.duration);
  3133. const maxDuration = Math.max(...durationList);
  3134. const minDuration = Math.min(...durationList);
  3135. const durationRange = maxDuration - minDuration;
  3136. total += item.destroyList.length;
  3137.  
  3138. return {
  3139. componentName: item.componentName,
  3140. count: item.destroyList.length,
  3141. avgDuration: durationList.reduce((pre, cur) => pre + cur, 0) / durationList.length,
  3142. maxDuration,
  3143. minDuration,
  3144. durationRange,
  3145. durationRangePercent: (1000 - minDuration) / durationRange
  3146. }
  3147. }));
  3148.  
  3149. debug.log(`${i18n.t('debugHelper.destroyStatisticsSort')} (total:${total})`, result);
  3150. },
  3151. componentsSummaryStatisticsSort () {
  3152. const result = helper.methods.componentsSummaryStatisticsSort();
  3153. let total = 0;
  3154.  
  3155. /* 提供友好的可视化展示方式 */
  3156. console.table && console.table(result.map(item => {
  3157. total += item.componentsSummary.length;
  3158. return {
  3159. componentName: item.componentName,
  3160. count: item.componentsSummary.length
  3161. }
  3162. }));
  3163.  
  3164. debug.log(`${i18n.t('debugHelper.componentsSummaryStatisticsSort')} (total:${total})`, result);
  3165. },
  3166. getDestroyByDuration () {
  3167. const destroyInfo = helper.methods.getDestroyByDuration();
  3168. console.table && console.table(destroyInfo.destroyList);
  3169. debug.log(i18n.t('debugHelper.getDestroyByDuration'), destroyInfo);
  3170. },
  3171. clearAll () {
  3172. helper.methods.clearAll();
  3173. debug.log(i18n.t('debugHelper.clearAll'));
  3174. },
  3175.  
  3176. printLifeCycleInfo (str) {
  3177. addToFilters(helper.config.lifecycle, 'componentFilters', str);
  3178.  
  3179. const lifecycleFilters = window.prompt(i18n.t('debugHelper.printLifeCycleInfoPrompt.lifecycleFilters'), helper.config.lifecycle.filters.join(','));
  3180. const componentFilters = window.prompt(i18n.t('debugHelper.printLifeCycleInfoPrompt.componentFilters'), helper.config.lifecycle.componentFilters.join(','));
  3181.  
  3182. if (lifecycleFilters !== null && componentFilters !== null) {
  3183. debug.log(i18n.t('debugHelper.printLifeCycleInfo'));
  3184. helper.methods.printLifeCycleInfo(lifecycleFilters, componentFilters);
  3185. }
  3186. },
  3187.  
  3188. notPrintLifeCycleInfo () {
  3189. debug.log(i18n.t('debugHelper.notPrintLifeCycleInfo'));
  3190. helper.methods.notPrintLifeCycleInfo();
  3191. },
  3192.  
  3193. findComponents (str) {
  3194. addToFilters(helper.config, 'findComponentsFilters', str);
  3195.  
  3196. const filters = window.prompt(i18n.t('debugHelper.findComponentsPrompt.filters'), helper.config.findComponentsFilters.join(','));
  3197. if (filters !== null) {
  3198. debug.log(i18n.t('debugHelper.findComponents'), helper.methods.findComponents(filters));
  3199. }
  3200. },
  3201.  
  3202. findNotContainElementComponents () {
  3203. debug.log(i18n.t('debugHelper.findNotContainElementComponents'), helper.methods.findNotContainElementComponents());
  3204. },
  3205.  
  3206. blockComponents (str) {
  3207. addToFilters(helper.config, 'blockFilters', str);
  3208.  
  3209. const filters = window.prompt(i18n.t('debugHelper.blockComponentsPrompt.filters'), helper.config.blockFilters.join(','));
  3210. if (filters !== null) {
  3211. helper.methods.blockComponents(filters);
  3212. debug.log(i18n.t('debugHelper.blockComponents'), filters);
  3213. }
  3214. },
  3215.  
  3216. dd () {
  3217. const filter = window.prompt(i18n.t('debugHelper.ddPrompt.filter'), helper.config.dd.filters.join(','));
  3218. const count = window.prompt(i18n.t('debugHelper.ddPrompt.count'), helper.config.dd.count);
  3219.  
  3220. if (filter !== null && count !== null) {
  3221. debug.log(i18n.t('debugHelper.dd'));
  3222. helper.methods.dd(filter, Number(count));
  3223. }
  3224. },
  3225.  
  3226. undd () {
  3227. debug.log(i18n.t('debugHelper.undd'));
  3228. helper.methods.undd();
  3229. },
  3230.  
  3231. toggleHackVueComponent () {
  3232. helper.config.hackVueComponent ? vueHooks.unHackVueComponent() : vueHooks.hackVueComponent();
  3233. helper.config.hackVueComponent = !helper.config.hackVueComponent;
  3234. },
  3235.  
  3236. togglePerformanceObserver () {
  3237. helper.config.performanceObserver.enabled = !helper.config.performanceObserver.enabled;
  3238.  
  3239. if (helper.config.performanceObserver.enabled) {
  3240. let entryTypes = window.prompt(i18n.t('debugHelper.performanceObserverPrompt.entryTypes'), helper.config.performanceObserver.entryTypes.join(','));
  3241. if (entryTypes) {
  3242. const entryTypesArr = toArrFilters(entryTypes);
  3243. const supportEntryTypes = ['element', 'navigation', 'resource', 'mark', 'measure', 'paint', 'longtask'];
  3244.  
  3245. /* 过滤出支持的entryTypes */
  3246. entryTypes = entryTypesArr.filter(item => supportEntryTypes.includes(item));
  3247.  
  3248. if (entryTypes.length !== entryTypesArr.length) {
  3249. debug.warn(`some entryTypes not support, only support: ${supportEntryTypes.join(',')}`);
  3250. }
  3251.  
  3252. helper.config.performanceObserver.entryTypes = entryTypes;
  3253.  
  3254. performanceObserver.init();
  3255. } else {
  3256. alert('entryTypes is empty');
  3257. }
  3258. }
  3259.  
  3260. debug.log(`${i18n.t('debugHelper.togglePerformanceObserver')} success (${helper.config.performanceObserver.enabled})`);
  3261. },
  3262.  
  3263. useAjaxCache () {
  3264. helper.config.ajaxCache.enabled = true;
  3265.  
  3266. const filters = window.prompt(i18n.t('debugHelper.jaxCachePrompt.filters'), helper.config.ajaxCache.filters.join(','));
  3267. const expires = window.prompt(i18n.t('debugHelper.jaxCachePrompt.expires'), helper.config.ajaxCache.expires / 1000 / 60);
  3268.  
  3269. if (filters && expires) {
  3270. helper.config.ajaxCache.filters = toArrFilters(filters);
  3271.  
  3272. if (!isNaN(Number(expires))) {
  3273. helper.config.ajaxCache.expires = Number(expires) * 1000 * 60;
  3274. }
  3275.  
  3276. ajaxHooks.hook();
  3277.  
  3278. debug.log(`${i18n.t('debugHelper.enableAjaxCacheTips')}`);
  3279. }
  3280. },
  3281.  
  3282. disableAjaxCache () {
  3283. helper.config.ajaxCache.enabled = false;
  3284. ajaxHooks.unHook();
  3285. debug.log(`${i18n.t('debugHelper.disableAjaxCacheTips')}`);
  3286. },
  3287.  
  3288. toggleAjaxCache () {
  3289. if (helper.config.ajaxCache.enabled) {
  3290. functionCall.disableAjaxCache();
  3291. } else {
  3292. functionCall.useAjaxCache();
  3293. }
  3294. },
  3295.  
  3296. async clearAjaxCache () {
  3297. await cacheStore.store.clear();
  3298. debug.log(`${i18n.t('debugHelper.clearAjaxCacheTips')}`);
  3299. },
  3300.  
  3301. addMeasureSelectorInterval (selector1, selector2) {
  3302. let result = {};
  3303. if (!functionCall._measureSelectorArr) {
  3304. functionCall._measureSelectorArr = [];
  3305. }
  3306.  
  3307. function measure (element) {
  3308. // debug.log(`[measure] ${i18n.t('debugHelper.measureSelectorInterval')}`, element)
  3309.  
  3310. const selector1 = helper.config.measureSelectorInterval.selector1;
  3311. const selector2 = helper.config.measureSelectorInterval.selector2;
  3312. const selectorArr = [selector1, selector2];
  3313. selectorArr.forEach(selector => {
  3314. if (selector && element.parentElement && element.parentElement.querySelector(selector)) {
  3315. result[selector] = {
  3316. time: Date.now(),
  3317. element: element
  3318. };
  3319.  
  3320. debug.info(`${i18n.t('debugHelper.selectorReadyTips')}: ${selector}`, element);
  3321. }
  3322. });
  3323.  
  3324. if (Object.keys(result).length >= 2) {
  3325. const time = ((result[selector2].time - result[selector1].time) / 1000).toFixed(2);
  3326.  
  3327. debug.info(`[[${selector1}] -> [${selector2}]] time: ${time}s`);
  3328. result = {};
  3329. }
  3330. }
  3331.  
  3332. if (selector1 && selector2) {
  3333. helper.config.measureSelectorInterval.selector1 = selector1;
  3334. helper.config.measureSelectorInterval.selector2 = selector2;
  3335.  
  3336. const selectorArr = [selector1, selector2];
  3337. selectorArr.forEach(selector => {
  3338. if (!functionCall._measureSelectorArr.includes(selector)) {
  3339. // 防止重复注册
  3340. functionCall._measureSelectorArr.push(selector);
  3341.  
  3342. ready(selector, measure);
  3343. }
  3344. });
  3345. } else {
  3346. debug.log('selector is empty, please input selector');
  3347. }
  3348. },
  3349.  
  3350. initMeasureSelectorInterval () {
  3351. const selector1 = helper.config.measureSelectorInterval.selector1;
  3352. const selector2 = helper.config.measureSelectorInterval.selector2;
  3353. if (selector1 && selector2) {
  3354. functionCall.addMeasureSelectorInterval(selector1, selector2);
  3355. debug.log('[measureSelectorInterval] init success');
  3356. }
  3357. },
  3358.  
  3359. measureSelectorInterval () {
  3360. const selector1 = window.prompt(i18n.t('debugHelper.measureSelectorIntervalPrompt.selector1'), helper.config.measureSelectorInterval.selector1);
  3361. const selector2 = window.prompt(i18n.t('debugHelper.measureSelectorIntervalPrompt.selector2'), helper.config.measureSelectorInterval.selector2);
  3362.  
  3363. if (!selector1 && !selector2) {
  3364. helper.config.measureSelectorInterval.selector1 = '';
  3365. helper.config.measureSelectorInterval.selector2 = '';
  3366. }
  3367.  
  3368. functionCall.addMeasureSelectorInterval(selector1, selector2);
  3369. }
  3370. };
  3371.  
  3372. /*!
  3373. * @name menu.js
  3374. * @description vue-debug-helper的菜单配置
  3375. * @version 0.0.1
  3376. * @author xxxily
  3377. * @date 2022/04/25 22:28
  3378. * @github https://github.com/xxxily
  3379. */
  3380.  
  3381. function menuRegister (Vue) {
  3382. if (!Vue) {
  3383. monkeyMenu.on('not detected ' + i18n.t('issues'), () => {
  3384. window.GM_openInTab('https://github.com/xxxily/vue-debug-helper/issues', {
  3385. active: true,
  3386. insert: true,
  3387. setParent: true
  3388. });
  3389. });
  3390. return false
  3391. }
  3392.  
  3393. /* 批量注册菜单 */
  3394. Object.keys(functionCall).forEach(key => {
  3395. const text = i18n.t(`debugHelper.${key}`);
  3396. if (text && functionCall[key] instanceof Function) {
  3397. monkeyMenu.on(text, functionCall[key]);
  3398. }
  3399. });
  3400.  
  3401. /* 是否开启vue-devtools的菜单 */
  3402. const devtoolsText = helper.config.devtools ? i18n.t('debugHelper.devtools.disable') : i18n.t('debugHelper.devtools.enabled');
  3403. monkeyMenu.on(devtoolsText, helper.methods.toggleDevtools);
  3404.  
  3405. // monkeyMenu.on('i18n.t('setting')', () => {
  3406. // window.alert('功能开发中,敬请期待...')
  3407. // })
  3408.  
  3409. monkeyMenu.on(i18n.t('issues'), () => {
  3410. window.GM_openInTab('https://github.com/xxxily/vue-debug-helper/issues', {
  3411. active: true,
  3412. insert: true,
  3413. setParent: true
  3414. });
  3415. });
  3416.  
  3417. // monkeyMenu.on(i18n.t('donate'), () => {
  3418. // window.GM_openInTab('https://cdn.jsdelivr.net/gh/xxxily/vue-debug-helper@main/donate.png', {
  3419. // active: true,
  3420. // insert: true,
  3421. // setParent: true
  3422. // })
  3423. // })
  3424. }
  3425.  
  3426. const isff = typeof navigator !== 'undefined' ? navigator.userAgent.toLowerCase().indexOf('firefox') > 0 : false;
  3427.  
  3428. // 绑定事件
  3429. function addEvent (object, event, method) {
  3430. if (object.addEventListener) {
  3431. object.addEventListener(event, method, false);
  3432. } else if (object.attachEvent) {
  3433. object.attachEvent(`on${event}`, () => { method(window.event); });
  3434. }
  3435. }
  3436.  
  3437. // 修饰键转换成对应的键码
  3438. function getMods (modifier, key) {
  3439. const mods = key.slice(0, key.length - 1);
  3440. for (let i = 0; i < mods.length; i++) mods[i] = modifier[mods[i].toLowerCase()];
  3441. return mods
  3442. }
  3443.  
  3444. // 处理传的key字符串转换成数组
  3445. function getKeys (key) {
  3446. if (typeof key !== 'string') key = '';
  3447. key = key.replace(/\s/g, ''); // 匹配任何空白字符,包括空格、制表符、换页符等等
  3448. const keys = key.split(','); // 同时设置多个快捷键,以','分割
  3449. let index = keys.lastIndexOf('');
  3450.  
  3451. // 快捷键可能包含',',需特殊处理
  3452. for (; index >= 0;) {
  3453. keys[index - 1] += ',';
  3454. keys.splice(index, 1);
  3455. index = keys.lastIndexOf('');
  3456. }
  3457.  
  3458. return keys
  3459. }
  3460.  
  3461. // 比较修饰键的数组
  3462. function compareArray (a1, a2) {
  3463. const arr1 = a1.length >= a2.length ? a1 : a2;
  3464. const arr2 = a1.length >= a2.length ? a2 : a1;
  3465. let isIndex = true;
  3466.  
  3467. for (let i = 0; i < arr1.length; i++) {
  3468. if (arr2.indexOf(arr1[i]) === -1) isIndex = false;
  3469. }
  3470. return isIndex
  3471. }
  3472.  
  3473. // Special Keys
  3474. const _keyMap = {
  3475. backspace: 8,
  3476. tab: 9,
  3477. clear: 12,
  3478. enter: 13,
  3479. return: 13,
  3480. esc: 27,
  3481. escape: 27,
  3482. space: 32,
  3483. left: 37,
  3484. up: 38,
  3485. right: 39,
  3486. down: 40,
  3487. del: 46,
  3488. delete: 46,
  3489. ins: 45,
  3490. insert: 45,
  3491. home: 36,
  3492. end: 35,
  3493. pageup: 33,
  3494. pagedown: 34,
  3495. capslock: 20,
  3496. num_0: 96,
  3497. num_1: 97,
  3498. num_2: 98,
  3499. num_3: 99,
  3500. num_4: 100,
  3501. num_5: 101,
  3502. num_6: 102,
  3503. num_7: 103,
  3504. num_8: 104,
  3505. num_9: 105,
  3506. num_multiply: 106,
  3507. num_add: 107,
  3508. num_enter: 108,
  3509. num_subtract: 109,
  3510. num_decimal: 110,
  3511. num_divide: 111,
  3512. '⇪': 20,
  3513. ',': 188,
  3514. '.': 190,
  3515. '/': 191,
  3516. '`': 192,
  3517. '-': isff ? 173 : 189,
  3518. '=': isff ? 61 : 187,
  3519. ';': isff ? 59 : 186,
  3520. '\'': 222,
  3521. '[': 219,
  3522. ']': 221,
  3523. '\\': 220
  3524. };
  3525.  
  3526. // Modifier Keys
  3527. const _modifier = {
  3528. // shiftKey
  3529. '⇧': 16,
  3530. shift: 16,
  3531. // altKey
  3532. '⌥': 18,
  3533. alt: 18,
  3534. option: 18,
  3535. // ctrlKey
  3536. '⌃': 17,
  3537. ctrl: 17,
  3538. control: 17,
  3539. // metaKey
  3540. '⌘': 91,
  3541. cmd: 91,
  3542. command: 91
  3543. };
  3544. const modifierMap = {
  3545. 16: 'shiftKey',
  3546. 18: 'altKey',
  3547. 17: 'ctrlKey',
  3548. 91: 'metaKey',
  3549.  
  3550. shiftKey: 16,
  3551. ctrlKey: 17,
  3552. altKey: 18,
  3553. metaKey: 91
  3554. };
  3555. const _mods = {
  3556. 16: false,
  3557. 18: false,
  3558. 17: false,
  3559. 91: false
  3560. };
  3561. const _handlers = {};
  3562.  
  3563. // F1~F12 special key
  3564. for (let k = 1; k < 20; k++) {
  3565. _keyMap[`f${k}`] = 111 + k;
  3566. }
  3567.  
  3568. // https://github.com/jaywcjlove/hotkeys
  3569.  
  3570. let _downKeys = []; // 记录摁下的绑定键
  3571. let winListendFocus = false; // window是否已经监听了focus事件
  3572. let _scope = 'all'; // 默认热键范围
  3573. const elementHasBindEvent = []; // 已绑定事件的节点记录
  3574.  
  3575. // 返回键码
  3576. const code = (x) => _keyMap[x.toLowerCase()] ||
  3577. _modifier[x.toLowerCase()] ||
  3578. x.toUpperCase().charCodeAt(0);
  3579.  
  3580. // 设置获取当前范围(默认为'所有')
  3581. function setScope (scope) {
  3582. _scope = scope || 'all';
  3583. }
  3584. // 获取当前范围
  3585. function getScope () {
  3586. return _scope || 'all'
  3587. }
  3588. // 获取摁下绑定键的键值
  3589. function getPressedKeyCodes () {
  3590. return _downKeys.slice(0)
  3591. }
  3592.  
  3593. // 表单控件控件判断 返回 Boolean
  3594. // hotkey is effective only when filter return true
  3595. function filter (event) {
  3596. const target = event.target || event.srcElement;
  3597. const { tagName } = target;
  3598. let flag = true;
  3599. // ignore: isContentEditable === 'true', <input> and <textarea> when readOnly state is false, <select>
  3600. if (
  3601. target.isContentEditable ||
  3602. ((tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT') && !target.readOnly)
  3603. ) {
  3604. flag = false;
  3605. }
  3606. return flag
  3607. }
  3608.  
  3609. // 判断摁下的键是否为某个键,返回true或者false
  3610. function isPressed (keyCode) {
  3611. if (typeof keyCode === 'string') {
  3612. keyCode = code(keyCode); // 转换成键码
  3613. }
  3614. return _downKeys.indexOf(keyCode) !== -1
  3615. }
  3616.  
  3617. // 循环删除handlers中的所有 scope(范围)
  3618. function deleteScope (scope, newScope) {
  3619. let handlers;
  3620. let i;
  3621.  
  3622. // 没有指定scope,获取scope
  3623. if (!scope) scope = getScope();
  3624.  
  3625. for (const key in _handlers) {
  3626. if (Object.prototype.hasOwnProperty.call(_handlers, key)) {
  3627. handlers = _handlers[key];
  3628. for (i = 0; i < handlers.length;) {
  3629. if (handlers[i].scope === scope) handlers.splice(i, 1);
  3630. else i++;
  3631. }
  3632. }
  3633. }
  3634.  
  3635. // 如果scope被删除,将scope重置为all
  3636. if (getScope() === scope) setScope(newScope || 'all');
  3637. }
  3638.  
  3639. // 清除修饰键
  3640. function clearModifier (event) {
  3641. let key = event.keyCode || event.which || event.charCode;
  3642. const i = _downKeys.indexOf(key);
  3643.  
  3644. // 从列表中清除按压过的键
  3645. if (i >= 0) {
  3646. _downKeys.splice(i, 1);
  3647. }
  3648. // 特殊处理 cmmand 键,在 cmmand 组合快捷键 keyup 只执行一次的问题
  3649. if (event.key && event.key.toLowerCase() === 'meta') {
  3650. _downKeys.splice(0, _downKeys.length);
  3651. }
  3652.  
  3653. // 修饰键 shiftKey altKey ctrlKey (command||metaKey) 清除
  3654. if (key === 93 || key === 224) key = 91;
  3655. if (key in _mods) {
  3656. _mods[key] = false;
  3657.  
  3658. // 将修饰键重置为false
  3659. for (const k in _modifier) if (_modifier[k] === key) hotkeys[k] = false;
  3660. }
  3661. }
  3662.  
  3663. function unbind (keysInfo, ...args) {
  3664. // unbind(), unbind all keys
  3665. if (!keysInfo) {
  3666. Object.keys(_handlers).forEach((key) => delete _handlers[key]);
  3667. } else if (Array.isArray(keysInfo)) {
  3668. // support like : unbind([{key: 'ctrl+a', scope: 's1'}, {key: 'ctrl-a', scope: 's2', splitKey: '-'}])
  3669. keysInfo.forEach((info) => {
  3670. if (info.key) eachUnbind(info);
  3671. });
  3672. } else if (typeof keysInfo === 'object') {
  3673. // support like unbind({key: 'ctrl+a, ctrl+b', scope:'abc'})
  3674. if (keysInfo.key) eachUnbind(keysInfo);
  3675. } else if (typeof keysInfo === 'string') {
  3676. // support old method
  3677. // eslint-disable-line
  3678. let [scope, method] = args;
  3679. if (typeof scope === 'function') {
  3680. method = scope;
  3681. scope = '';
  3682. }
  3683. eachUnbind({
  3684. key: keysInfo,
  3685. scope,
  3686. method,
  3687. splitKey: '+'
  3688. });
  3689. }
  3690. }
  3691.  
  3692. // 解除绑定某个范围的快捷键
  3693. const eachUnbind = ({
  3694. key, scope, method, splitKey = '+'
  3695. }) => {
  3696. const multipleKeys = getKeys(key);
  3697. multipleKeys.forEach((originKey) => {
  3698. const unbindKeys = originKey.split(splitKey);
  3699. const len = unbindKeys.length;
  3700. const lastKey = unbindKeys[len - 1];
  3701. const keyCode = lastKey === '*' ? '*' : code(lastKey);
  3702. if (!_handlers[keyCode]) return
  3703. // 判断是否传入范围,没有就获取范围
  3704. if (!scope) scope = getScope();
  3705. const mods = len > 1 ? getMods(_modifier, unbindKeys) : [];
  3706. _handlers[keyCode] = _handlers[keyCode].filter((record) => {
  3707. // 通过函数判断,是否解除绑定,函数相等直接返回
  3708. const isMatchingMethod = method ? record.method === method : true;
  3709. return !(
  3710. isMatchingMethod &&
  3711. record.scope === scope &&
  3712. compareArray(record.mods, mods)
  3713. )
  3714. });
  3715. });
  3716. };
  3717.  
  3718. // 对监听对应快捷键的回调函数进行处理
  3719. function eventHandler (event, handler, scope, element) {
  3720. if (handler.element !== element) {
  3721. return
  3722. }
  3723. let modifiersMatch;
  3724.  
  3725. // 看它是否在当前范围
  3726. if (handler.scope === scope || handler.scope === 'all') {
  3727. // 检查是否匹配修饰符(如果有返回true)
  3728. modifiersMatch = handler.mods.length > 0;
  3729.  
  3730. for (const y in _mods) {
  3731. if (Object.prototype.hasOwnProperty.call(_mods, y)) {
  3732. if (
  3733. (!_mods[y] && handler.mods.indexOf(+y) > -1) ||
  3734. (_mods[y] && handler.mods.indexOf(+y) === -1)
  3735. ) {
  3736. modifiersMatch = false;
  3737. }
  3738. }
  3739. }
  3740.  
  3741. // 调用处理程序,如果是修饰键不做处理
  3742. if (
  3743. (handler.mods.length === 0 &&
  3744. !_mods[16] &&
  3745. !_mods[18] &&
  3746. !_mods[17] &&
  3747. !_mods[91]) ||
  3748. modifiersMatch ||
  3749. handler.shortcut === '*'
  3750. ) {
  3751. if (handler.method(event, handler) === false) {
  3752. if (event.preventDefault) event.preventDefault();
  3753. else event.returnValue = false;
  3754. if (event.stopPropagation) event.stopPropagation();
  3755. if (event.cancelBubble) event.cancelBubble = true;
  3756. }
  3757. }
  3758. }
  3759. }
  3760.  
  3761. // 处理keydown事件
  3762. function dispatch (event, element) {
  3763. const asterisk = _handlers['*'];
  3764. let key = event.keyCode || event.which || event.charCode;
  3765.  
  3766. // 表单控件过滤 默认表单控件不触发快捷键
  3767. if (!hotkeys.filter.call(this, event)) return
  3768.  
  3769. // Gecko(Firefox)的command键值224,在Webkit(Chrome)中保持一致
  3770. // Webkit左右 command 键值不一样
  3771. if (key === 93 || key === 224) key = 91;
  3772.  
  3773. /**
  3774. * Collect bound keys
  3775. * If an Input Method Editor is processing key input and the event is keydown, return 229.
  3776. * https://stackoverflow.com/questions/25043934/is-it-ok-to-ignore-keydown-events-with-keycode-229
  3777. * http://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html
  3778. */
  3779. if (_downKeys.indexOf(key) === -1 && key !== 229) _downKeys.push(key);
  3780. /**
  3781. * Jest test cases are required.
  3782. * ===============================
  3783. */
  3784. ['ctrlKey', 'altKey', 'shiftKey', 'metaKey'].forEach((keyName) => {
  3785. const keyNum = modifierMap[keyName];
  3786. if (event[keyName] && _downKeys.indexOf(keyNum) === -1) {
  3787. _downKeys.push(keyNum);
  3788. } else if (!event[keyName] && _downKeys.indexOf(keyNum) > -1) {
  3789. _downKeys.splice(_downKeys.indexOf(keyNum), 1);
  3790. } else if (keyName === 'metaKey' && event[keyName] && _downKeys.length === 3) {
  3791. /**
  3792. * Fix if Command is pressed:
  3793. * ===============================
  3794. */
  3795. if (!(event.ctrlKey || event.shiftKey || event.altKey)) {
  3796. _downKeys = _downKeys.slice(_downKeys.indexOf(keyNum));
  3797. }
  3798. }
  3799. });
  3800. /**
  3801. * -------------------------------
  3802. */
  3803.  
  3804. if (key in _mods) {
  3805. _mods[key] = true;
  3806.  
  3807. // 将特殊字符的key注册到 hotkeys 上
  3808. for (const k in _modifier) {
  3809. if (_modifier[k] === key) hotkeys[k] = true;
  3810. }
  3811.  
  3812. if (!asterisk) return
  3813. }
  3814.  
  3815. // 将 modifierMap 里面的修饰键绑定到 event 中
  3816. for (const e in _mods) {
  3817. if (Object.prototype.hasOwnProperty.call(_mods, e)) {
  3818. _mods[e] = event[modifierMap[e]];
  3819. }
  3820. }
  3821. /**
  3822. * https://github.com/jaywcjlove/hotkeys/pull/129
  3823. * This solves the issue in Firefox on Windows where hotkeys corresponding to special characters would not trigger.
  3824. * An example of this is ctrl+alt+m on a Swedish keyboard which is used to type μ.
  3825. * Browser support: https://caniuse.com/#feat=keyboardevent-getmodifierstate
  3826. */
  3827. if (event.getModifierState && (!(event.altKey && !event.ctrlKey) && event.getModifierState('AltGraph'))) {
  3828. if (_downKeys.indexOf(17) === -1) {
  3829. _downKeys.push(17);
  3830. }
  3831.  
  3832. if (_downKeys.indexOf(18) === -1) {
  3833. _downKeys.push(18);
  3834. }
  3835.  
  3836. _mods[17] = true;
  3837. _mods[18] = true;
  3838. }
  3839.  
  3840. // 获取范围 默认为 `all`
  3841. const scope = getScope();
  3842. // 对任何快捷键都需要做的处理
  3843. if (asterisk) {
  3844. for (let i = 0; i < asterisk.length; i++) {
  3845. if (
  3846. asterisk[i].scope === scope &&
  3847. ((event.type === 'keydown' && asterisk[i].keydown) ||
  3848. (event.type === 'keyup' && asterisk[i].keyup))
  3849. ) {
  3850. eventHandler(event, asterisk[i], scope, element);
  3851. }
  3852. }
  3853. }
  3854. // key 不在 _handlers 中返回
  3855. if (!(key in _handlers)) return
  3856.  
  3857. for (let i = 0; i < _handlers[key].length; i++) {
  3858. if (
  3859. (event.type === 'keydown' && _handlers[key][i].keydown) ||
  3860. (event.type === 'keyup' && _handlers[key][i].keyup)
  3861. ) {
  3862. if (_handlers[key][i].key) {
  3863. const record = _handlers[key][i];
  3864. const { splitKey } = record;
  3865. const keyShortcut = record.key.split(splitKey);
  3866. const _downKeysCurrent = []; // 记录当前按键键值
  3867. for (let a = 0; a < keyShortcut.length; a++) {
  3868. _downKeysCurrent.push(code(keyShortcut[a]));
  3869. }
  3870. if (_downKeysCurrent.sort().join('') === _downKeys.sort().join('')) {
  3871. // 找到处理内容
  3872. eventHandler(event, record, scope, element);
  3873. }
  3874. }
  3875. }
  3876. }
  3877. }
  3878.  
  3879. // 判断 element 是否已经绑定事件
  3880. function isElementBind (element) {
  3881. return elementHasBindEvent.indexOf(element) > -1
  3882. }
  3883.  
  3884. function hotkeys (key, option, method) {
  3885. _downKeys = [];
  3886. const keys = getKeys(key); // 需要处理的快捷键列表
  3887. let mods = [];
  3888. let scope = 'all'; // scope默认为all,所有范围都有效
  3889. let element = document; // 快捷键事件绑定节点
  3890. let i = 0;
  3891. let keyup = false;
  3892. let keydown = true;
  3893. let splitKey = '+';
  3894.  
  3895. // 对为设定范围的判断
  3896. if (method === undefined && typeof option === 'function') {
  3897. method = option;
  3898. }
  3899.  
  3900. if (Object.prototype.toString.call(option) === '[object Object]') {
  3901. if (option.scope) scope = option.scope; // eslint-disable-line
  3902. if (option.element) element = option.element; // eslint-disable-line
  3903. if (option.keyup) keyup = option.keyup; // eslint-disable-line
  3904. if (option.keydown !== undefined) keydown = option.keydown; // eslint-disable-line
  3905. if (typeof option.splitKey === 'string') splitKey = option.splitKey; // eslint-disable-line
  3906. }
  3907.  
  3908. if (typeof option === 'string') scope = option;
  3909.  
  3910. // 对于每个快捷键进行处理
  3911. for (; i < keys.length; i++) {
  3912. key = keys[i].split(splitKey); // 按键列表
  3913. mods = [];
  3914.  
  3915. // 如果是组合快捷键取得组合快捷键
  3916. if (key.length > 1) mods = getMods(_modifier, key);
  3917.  
  3918. // 将非修饰键转化为键码
  3919. key = key[key.length - 1];
  3920. key = key === '*' ? '*' : code(key); // *表示匹配所有快捷键
  3921.  
  3922. // 判断key是否在_handlers中,不在就赋一个空数组
  3923. if (!(key in _handlers)) _handlers[key] = [];
  3924. _handlers[key].push({
  3925. keyup,
  3926. keydown,
  3927. scope,
  3928. mods,
  3929. shortcut: keys[i],
  3930. method,
  3931. key: keys[i],
  3932. splitKey,
  3933. element
  3934. });
  3935. }
  3936. // 在全局document上设置快捷键
  3937. if (typeof element !== 'undefined' && !isElementBind(element) && window) {
  3938. elementHasBindEvent.push(element);
  3939. addEvent(element, 'keydown', (e) => {
  3940. dispatch(e, element);
  3941. });
  3942. if (!winListendFocus) {
  3943. winListendFocus = true;
  3944. addEvent(window, 'focus', () => {
  3945. _downKeys = [];
  3946. });
  3947. }
  3948. addEvent(element, 'keyup', (e) => {
  3949. dispatch(e, element);
  3950. clearModifier(e);
  3951. });
  3952. }
  3953. }
  3954.  
  3955. function trigger (shortcut, scope = 'all') {
  3956. Object.keys(_handlers).forEach((key) => {
  3957. const data = _handlers[key].find((item) => item.scope === scope && item.shortcut === shortcut);
  3958. if (data && data.method) {
  3959. data.method();
  3960. }
  3961. });
  3962. }
  3963.  
  3964. const _api = {
  3965. setScope,
  3966. getScope,
  3967. deleteScope,
  3968. getPressedKeyCodes,
  3969. isPressed,
  3970. filter,
  3971. trigger,
  3972. unbind,
  3973. keyMap: _keyMap,
  3974. modifier: _modifier,
  3975. modifierMap
  3976. };
  3977. for (const a in _api) {
  3978. if (Object.prototype.hasOwnProperty.call(_api, a)) {
  3979. hotkeys[a] = _api[a];
  3980. }
  3981. }
  3982.  
  3983. if (typeof window !== 'undefined') {
  3984. const _hotkeys = window.hotkeys;
  3985. hotkeys.noConflict = (deep) => {
  3986. if (deep && window.hotkeys === hotkeys) {
  3987. window.hotkeys = _hotkeys;
  3988. }
  3989. return hotkeys
  3990. };
  3991. window.hotkeys = hotkeys;
  3992. }
  3993.  
  3994. /*!
  3995. * @name hotKeyRegister.js
  3996. * @description vue-debug-helper的快捷键配置
  3997. * @version 0.0.1
  3998. * @author xxxily
  3999. * @date 2022/04/26 14:37
  4000. * @github https://github.com/xxxily
  4001. */
  4002.  
  4003. function hotKeyRegister () {
  4004. const hotKeyMap = {
  4005. 'shift+alt+i': functionCall.toggleInspect,
  4006. 'shift+alt+a,shift+alt+ctrl+a': functionCall.componentsSummaryStatisticsSort,
  4007. 'shift+alt+l': functionCall.componentsStatistics,
  4008. 'shift+alt+d': functionCall.destroyStatisticsSort,
  4009. 'shift+alt+c': functionCall.clearAll,
  4010. 'shift+alt+e': function (event, handler) {
  4011. if (helper.config.dd.enabled) {
  4012. functionCall.undd();
  4013. } else {
  4014. functionCall.dd();
  4015. }
  4016. }
  4017. };
  4018.  
  4019. Object.keys(hotKeyMap).forEach(key => {
  4020. hotkeys(key, hotKeyMap[key]);
  4021. });
  4022. }
  4023.  
  4024. /*!
  4025. * @name vueDetector.js
  4026. * @description 检测页面是否存在Vue对象
  4027. * @version 0.0.1
  4028. * @author xxxily
  4029. * @date 2022/04/27 11:43
  4030. * @github https://github.com/xxxily
  4031. */
  4032.  
  4033. function mutationDetector (callback, shadowRoot) {
  4034. const win = window;
  4035. const MutationObserver = win.MutationObserver || win.WebKitMutationObserver;
  4036. const docRoot = shadowRoot || win.document.documentElement;
  4037. const maxDetectTries = 1500;
  4038. const timeout = 1000 * 10;
  4039. const startTime = Date.now();
  4040. let detectCount = 0;
  4041. let detectStatus = false;
  4042.  
  4043. if (!MutationObserver) {
  4044. debug.warn('MutationObserver is not supported in this browser');
  4045. return false
  4046. }
  4047.  
  4048. let mObserver = null;
  4049. const mObserverCallback = (mutationsList, observer) => {
  4050. if (detectStatus) {
  4051. return
  4052. }
  4053.  
  4054. /* 超时或检测次数过多,取消监听 */
  4055. if (Date.now() - startTime > timeout || detectCount > maxDetectTries) {
  4056. debug.warn('mutationDetector timeout or detectCount > maxDetectTries, stop detect');
  4057. if (mObserver && mObserver.disconnect) {
  4058. mObserver.disconnect();
  4059. mObserver = null;
  4060. }
  4061. }
  4062.  
  4063. for (let i = 0; i < mutationsList.length; i++) {
  4064. detectCount++;
  4065. const mutation = mutationsList[i];
  4066. if (mutation.target && mutation.target.__vue__) {
  4067. let Vue = Object.getPrototypeOf(mutation.target.__vue__).constructor;
  4068. while (Vue.super) {
  4069. Vue = Vue.super;
  4070. }
  4071.  
  4072. /* 检测成功后销毁观察对象 */
  4073. if (mObserver && mObserver.disconnect) {
  4074. mObserver.disconnect();
  4075. mObserver = null;
  4076. }
  4077.  
  4078. detectStatus = true;
  4079. callback && callback(Vue);
  4080. break
  4081. }
  4082. }
  4083. };
  4084.  
  4085. mObserver = new MutationObserver(mObserverCallback);
  4086. mObserver.observe(docRoot, {
  4087. attributes: true,
  4088. childList: true,
  4089. subtree: true
  4090. });
  4091. }
  4092.  
  4093. /**
  4094. * 检测页面是否存在Vue对象,方法参考:https://github.com/vuejs/devtools/blob/main/packages/shell-chrome/src/detector.js
  4095. * @param {window} win windwod对象
  4096. * @param {function} callback 检测到Vue对象后的回调函数
  4097. */
  4098. function vueDetect (win, callback) {
  4099. let delay = 1000;
  4100. let detectRemainingTries = 10;
  4101. let detectSuc = false;
  4102.  
  4103. // Method 1: MutationObserver detector
  4104. mutationDetector((Vue) => {
  4105. if (!detectSuc) {
  4106. debug.info(`------------- Vue mutation detected (${Vue.version}) -------------`);
  4107. detectSuc = true;
  4108. callback(Vue);
  4109. }
  4110. });
  4111.  
  4112. function runDetect () {
  4113. if (detectSuc) {
  4114. return false
  4115. }
  4116.  
  4117. // Method 2: Check Vue 3
  4118. const vueDetected = !!(win.__VUE__);
  4119. if (vueDetected) {
  4120. debug.info(`------------- Vue global detected (${win.__VUE__.version}) -------------`);
  4121. detectSuc = true;
  4122. callback(win.__VUE__);
  4123. return
  4124. }
  4125.  
  4126. // Method 3: Scan all elements inside document
  4127. const all = document.querySelectorAll('*');
  4128. let el;
  4129. for (let i = 0; i < all.length; i++) {
  4130. if (all[i].__vue__) {
  4131. el = all[i];
  4132. break
  4133. }
  4134. }
  4135. if (el) {
  4136. let Vue = Object.getPrototypeOf(el.__vue__).constructor;
  4137. while (Vue.super) {
  4138. Vue = Vue.super;
  4139. }
  4140. debug.info(`------------- Vue dom detected (${Vue.version}) -------------`);
  4141. detectSuc = true;
  4142. callback(Vue);
  4143. return
  4144. }
  4145.  
  4146. if (detectRemainingTries > 0) {
  4147. detectRemainingTries--;
  4148.  
  4149. if (detectRemainingTries >= 7) {
  4150. setTimeout(() => {
  4151. runDetect();
  4152. }, 40);
  4153. } else {
  4154. setTimeout(() => {
  4155. runDetect();
  4156. }, delay);
  4157. delay *= 5;
  4158. }
  4159. }
  4160. }
  4161.  
  4162. setTimeout(() => {
  4163. runDetect();
  4164. }, 40);
  4165. }
  4166.  
  4167. /*!
  4168. * @name vueConfig.js
  4169. * @description 对Vue的配置进行修改
  4170. * @version 0.0.1
  4171. * @author xxxily
  4172. * @date 2022/05/10 15:15
  4173. * @github https://github.com/xxxily
  4174. */
  4175.  
  4176. function vueConfigInit (Vue, config) {
  4177. if (Vue.config) {
  4178. /* 自动开启Vue的调试模式 */
  4179. if (config.devtools) {
  4180. Vue.config.debug = true;
  4181. Vue.config.devtools = true;
  4182. Vue.config.performance = true;
  4183.  
  4184. setTimeout(() => {
  4185. const devtools = getVueDevtools();
  4186. if (devtools) {
  4187. if (!devtools.enabled) {
  4188. devtools.emit('init', Vue);
  4189. debug.info('vue devtools init emit.');
  4190. }
  4191. } else {
  4192. // debug.info(
  4193. // 'Download the Vue Devtools extension for a better development experience:\n' +
  4194. // 'https://github.com/vuejs/vue-devtools'
  4195. // )
  4196. debug.info('vue devtools check failed.');
  4197. }
  4198. }, 200);
  4199. } else {
  4200. Vue.config.debug = false;
  4201. Vue.config.devtools = false;
  4202. Vue.config.performance = false;
  4203. }
  4204. } else {
  4205. debug.log('Vue.config is not defined');
  4206. }
  4207. }
  4208.  
  4209. /**
  4210. * 判断是否处于Iframe中
  4211. * @returns {boolean}
  4212. */
  4213. function isInIframe () {
  4214. return window !== window.top
  4215. }
  4216.  
  4217. /**
  4218. * 由于tampermonkey对window对象进行了封装,我们实际访问到的window并非页面真实的window
  4219. * 这就导致了如果我们需要将某些对象挂载到页面的window进行调试的时候就无法挂载了
  4220. * 所以必须使用特殊手段才能访问到页面真实的window对象,于是就有了下面这个函数
  4221. * @returns {Promise<void>}
  4222. */
  4223. async function getPageWindow () {
  4224. return new Promise(function (resolve, reject) {
  4225. if (window._pageWindow) {
  4226. return resolve(window._pageWindow)
  4227. }
  4228.  
  4229. const listenEventList = ['load', 'mousemove', 'scroll', 'get-page-window-event'];
  4230.  
  4231. function getWin (event) {
  4232. window._pageWindow = this;
  4233. // debug.log('getPageWindow succeed', event)
  4234. listenEventList.forEach(eventType => {
  4235. window.removeEventListener(eventType, getWin, true);
  4236. });
  4237. resolve(window._pageWindow);
  4238. }
  4239.  
  4240. listenEventList.forEach(eventType => {
  4241. window.addEventListener(eventType, getWin, true);
  4242. });
  4243.  
  4244. /* 自行派发事件以便用最短的时候获得pageWindow对象 */
  4245. window.dispatchEvent(new window.Event('get-page-window-event'));
  4246. })
  4247. }
  4248. // getPageWindow()
  4249.  
  4250. /**
  4251. * 通过同步的方式获取pageWindow
  4252. * 注意同步获取的方式需要将脚本写入head,部分网站由于安全策略会导致写入失败,而无法正常获取
  4253. * @returns {*}
  4254. */
  4255. function getPageWindowSync () {
  4256. if (document._win_) return document._win_
  4257.  
  4258. const head = document.head || document.querySelector('head');
  4259. const script = document.createElement('script');
  4260. script.appendChild(document.createTextNode('document._win_ = window'));
  4261. head.appendChild(script);
  4262.  
  4263. return document._win_
  4264. }
  4265.  
  4266. let registerStatus = 'init';
  4267. window._debugMode_ = true;
  4268.  
  4269. /* 注入相关样式到页面 */
  4270. if (window.GM_getResourceText && window.GM_addStyle) {
  4271. const contextMenuCss = window.GM_getResourceText('contextMenuCss');
  4272. window.GM_addStyle(contextMenuCss);
  4273. }
  4274.  
  4275. function init (win) {
  4276. if (isInIframe()) {
  4277. debug.log('running in iframe, skip init', window.location.href);
  4278. return false
  4279. }
  4280.  
  4281. if (registerStatus === 'initing') {
  4282. return false
  4283. }
  4284.  
  4285. registerStatus = 'initing';
  4286.  
  4287. /* 注册接口拦截功能和接近数据缓存功能 */
  4288. ajaxHooks.init(win);
  4289.  
  4290. vueDetect(win, function (Vue) {
  4291. /* 挂载到window上,方便通过控制台调用调试 */
  4292. helper.Vue = Vue;
  4293. win.vueDebugHelper = helper;
  4294.  
  4295. /* 注册阻断Vue组件的功能 */
  4296. vueHooks.blockComponents(Vue, helper.config);
  4297.  
  4298. /* 注册打印全局组件注册信息的功能 */
  4299. if (helper.config.hackVueComponent) {
  4300. vueHooks.hackVueComponent(Vue);
  4301. }
  4302.  
  4303. /* 注册性能观察的功能 */
  4304. performanceObserver.init();
  4305.  
  4306. /* 注册选择器测量辅助功能 */
  4307. functionCall.initMeasureSelectorInterval();
  4308.  
  4309. /* 对Vue相关配置进行初始化 */
  4310. vueConfigInit(Vue, helper.config);
  4311.  
  4312. mixinRegister(Vue);
  4313. menuRegister(Vue);
  4314. hotKeyRegister();
  4315.  
  4316. inspect.init(Vue);
  4317.  
  4318. debug.log('vue debug helper register success');
  4319. registerStatus = 'success';
  4320. });
  4321.  
  4322. setTimeout(() => {
  4323. if (registerStatus !== 'success') {
  4324. menuRegister(null);
  4325. debug.warn('vue debug helper register failed, please check if vue is loaded .', win.location.href);
  4326. }
  4327. }, 1000 * 10);
  4328. }
  4329.  
  4330. let win$1 = null;
  4331. try {
  4332. win$1 = getPageWindowSync();
  4333. if (win$1) {
  4334. init(win$1);
  4335. }
  4336. } catch (e) {
  4337. debug.error('getPageWindowSync failed', e);
  4338. }
  4339. (async function () {
  4340. if (!win$1) {
  4341. win$1 = await getPageWindow();
  4342. init(win$1);
  4343. }
  4344. })();