Vue調試分析助手

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

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

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