vue-debug-helper

Vue components debug helper

2022-05-20 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

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