Vue調試分析助手

Vue組件探測、統計、分析輔助腳本

目前為 2022-05-23 提交的版本,檢視 最新版本

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