default.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /*
  2. Tencent is pleased to support the open source community by making vConsole available.
  3. Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
  4. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
  5. http://opensource.org/licenses/MIT
  6. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
  7. */
  8. /**
  9. * vConsole Default Tab
  10. */
  11. import $ from '../lib/query.js';
  12. import * as tool from '../lib/tool.js';
  13. import VConsoleLogTab from './log.js';
  14. import tplTabbox from './tabbox_default.html';
  15. import tplItemCode from './item_code.html';
  16. class VConsoleDefaultTab extends VConsoleLogTab {
  17. constructor(...args) {
  18. super(...args);
  19. this.tplTabbox = tplTabbox;
  20. }
  21. onReady() {
  22. const that = this;
  23. super.onReady();
  24. window.winKeys = Object.getOwnPropertyNames(window).sort();
  25. window.keyTypes = {};
  26. for (let i = 0; i < winKeys.length; i++) {
  27. keyTypes[winKeys[i]] = typeof window[winKeys[i]];
  28. }
  29. const cacheObj = {};
  30. const ID_REGEX = /[a-zA-Z_0-9\$\-\u00A2-\uFFFF]/;
  31. const retrievePrecedingIdentifier = (text, pos, regex) => {
  32. regex = regex || ID_REGEX;
  33. const buf = [];
  34. for (let i = pos - 1; i >= 0; i--) {
  35. if (regex.test(text[i])) {
  36. buf.push(text[i]);
  37. } else {
  38. break;
  39. }
  40. }
  41. if (buf.length == 0) {
  42. regex = /\./;
  43. for (let i = pos - 1; i >= 0; i--) {
  44. if (regex.test(text[i])) {
  45. buf.push(text[i]);
  46. } else {
  47. break;
  48. }
  49. }
  50. }
  51. if (buf.length === 0) {
  52. const arr = (text.match(/[\(\)\[\]\{\}]/gi) || []);
  53. return arr[arr.length - 1];
  54. }
  55. return buf.reverse().join('');
  56. };
  57. $.bind($.one('.vc-cmd-input'), 'keyup', function (e) {
  58. const isDeleteKeyCode = e.keyCode === 8 || e.keyCode === 46;
  59. const $prompted = $.one('.vc-cmd-prompted');
  60. $prompted.style.display = 'none';
  61. $prompted.innerHTML = '';
  62. const tempValue = this.value;
  63. const value = retrievePrecedingIdentifier(this.value, this.value.length);
  64. if (value && value.length > 0) {
  65. if (/\(/.test(value) && !isDeleteKeyCode) {
  66. $.one('.vc-cmd-input').value += ')';
  67. return;
  68. }
  69. if (/\[/.test(value) && !isDeleteKeyCode) {
  70. $.one('.vc-cmd-input').value += ']';
  71. return;
  72. }
  73. if (/\{/.test(value) && !isDeleteKeyCode) {
  74. $.one('.vc-cmd-input').value += '}';
  75. return;
  76. }
  77. if ('.' === value) {
  78. const key = retrievePrecedingIdentifier(tempValue, tempValue.length - 1);
  79. if (!cacheObj[key]) {
  80. try {
  81. cacheObj[key] = Object.getOwnPropertyNames(eval('(' + key + ')')).sort();
  82. } catch (e) {
  83. ;
  84. }
  85. }
  86. try {
  87. for (let i = 0; i < cacheObj[key].length; i++) {
  88. const $li = document.createElement('li');
  89. const _key = cacheObj[key][i];
  90. $li.innerHTML = _key;
  91. $li.onclick = function () {
  92. $.one('.vc-cmd-input').value = '';
  93. $.one('.vc-cmd-input').value = tempValue + this.innerHTML;
  94. $prompted.style.display = 'none';
  95. };
  96. $prompted.appendChild($li);
  97. }
  98. } catch (e) {
  99. ;
  100. }
  101. } else if ('.' !== value.substring(value.length - 1) && value.indexOf('.') < 0) {
  102. for (let i = 0; i < winKeys.length; i++) {
  103. if (winKeys[i].toLowerCase().indexOf(value.toLowerCase()) >= 0) {
  104. const $li = document.createElement('li');
  105. $li.innerHTML = winKeys[i];
  106. $li.onclick = function () {
  107. $.one('.vc-cmd-input').value = '';
  108. $.one('.vc-cmd-input').value = this.innerHTML;
  109. if (keyTypes[this.innerHTML] == 'function') {
  110. $.one('.vc-cmd-input').value += '()';
  111. }
  112. $prompted.style.display = 'none';
  113. };
  114. $prompted.appendChild($li);
  115. }
  116. }
  117. } else {
  118. const arr = value.split('.');
  119. if (cacheObj[arr[0]]) {
  120. cacheObj[arr[0]].sort();
  121. for (let i = 0; i < cacheObj[arr[0]].length; i++) {
  122. const $li = document.createElement('li');
  123. const _key = cacheObj[arr[0]][i];
  124. if (_key.indexOf(arr[1]) >= 0) {
  125. $li.innerHTML = _key;
  126. $li.onclick = function () {
  127. $.one('.vc-cmd-input').value = '';
  128. $.one('.vc-cmd-input').value = tempValue + this.innerHTML;
  129. $prompted.style.display = 'none';
  130. };
  131. $prompted.appendChild($li);
  132. }
  133. }
  134. }
  135. }
  136. if ($prompted.children.length > 0) {
  137. const m = Math.min(200, $prompted.children.length * 31);
  138. $prompted.style.display = 'block';
  139. $prompted.style.height = m + 'px';
  140. $prompted.style.marginTop = -m + 'px';
  141. }
  142. } else {
  143. $prompted.style.display = 'none';
  144. }
  145. });
  146. $.bind($.one('.vc-cmd', this.$tabbox), 'submit', function (e) {
  147. e.preventDefault();
  148. let $input = $.one('.vc-cmd-input', e.target),
  149. cmd = $input.value;
  150. $input.value = '';
  151. if (cmd !== '') {
  152. that.evalCommand(cmd);
  153. }
  154. const $prompted = $.one('.vc-cmd-prompted');
  155. if ($prompted) {
  156. $prompted.style.display = 'none';
  157. }
  158. });
  159. // create a global letiable to save custom command's result
  160. let code = '';
  161. code += 'if (!!window) {';
  162. code += 'window.__vConsole_cmd_result = undefined;';
  163. code += 'window.__vConsole_cmd_error = false;';
  164. code += '}';
  165. let scriptList = document.getElementsByTagName('script');
  166. let nonce = '';
  167. if (scriptList.length > 0) {
  168. nonce = scriptList[0].nonce || ''; // get nonce to avoid `unsafe-inline`
  169. }
  170. let script = document.createElement('SCRIPT');
  171. script.innerHTML = code;
  172. script.setAttribute('nonce', nonce);
  173. document.documentElement.appendChild(script);
  174. document.documentElement.removeChild(script);
  175. }
  176. /**
  177. * replace window.console & window.onerror with vConsole method
  178. * @private
  179. */
  180. mockConsole() {
  181. super.mockConsole();
  182. let that = this;
  183. if (tool.isFunction(window.onerror)) {
  184. this.windowOnError = window.onerror;
  185. }
  186. window.onerror = function (message, source, lineNo, colNo, error) {
  187. let msg = message;
  188. if (source) {
  189. msg += "\n" + source.replace(location.origin, '');
  190. }
  191. if (lineNo || colNo) {
  192. msg += ':' + lineNo + ':' + colNo;
  193. }
  194. //print error stack info
  195. let stack = !!error && !!error.stack;
  196. let statckInfo = (stack && error.stack.toString()) || '';
  197. that.printLog({
  198. logType: 'error',
  199. logs: [msg, statckInfo],
  200. noOrigin: true
  201. });
  202. if (tool.isFunction(that.windowOnError)) {
  203. that.windowOnError.call(window, message, source, lineNo, colNo, error);
  204. }
  205. };
  206. }
  207. /**
  208. *
  209. * @private
  210. */
  211. evalCommand(cmd) {
  212. // print command to console
  213. this.printLog({
  214. logType: 'log',
  215. content: $.render(tplItemCode, {content: cmd, type: 'input'}),
  216. style: ''
  217. });
  218. // do not use `eval` or `new Function` to avoid `unsafe-eval` CSP rule
  219. /* let code = '';
  220. code += 'try {\n';
  221. code += 'window.__vConsole_cmd_result = (function() {\n';
  222. code += 'return ' + cmd + ';\n';
  223. code += '})();\n';
  224. code += 'window.__vConsole_cmd_error = false;\n';
  225. code += '} catch (e) {\n';
  226. code += 'window.__vConsole_cmd_result = e.message;\n';
  227. code += 'window.__vConsole_cmd_error = true;\n';
  228. code += '}';
  229. let scriptList = document.getElementsByTagName('script');
  230. let nonce = '';
  231. if (scriptList.length > 0) {
  232. nonce = scriptList[0].getAttribute('nonce') || ''; // get nonce to avoid `unsafe-inline`
  233. }
  234. let script = document.createElement('SCRIPT');
  235. script.innerHTML = code;
  236. script.setAttribute('nonce', nonce);
  237. document.documentElement.appendChild(script);
  238. let result = window.__vConsole_cmd_result,
  239. error = window.__vConsole_cmd_error;
  240. document.documentElement.removeChild(script);*/
  241. /* let code = ' try {';
  242. code += cmd;
  243. code += ' } catch (e) {';
  244. code += 'window.__vConsole_cmd_error = true;window.__vConsole_cmd_result = e.message;}';
  245. eval(code.replace(new RegExp('\n', 'gi'), ''));*/
  246. let result = void 0;
  247. try {
  248. result = eval.call(window, '(' + cmd + ')');
  249. } catch (e) {
  250. try {
  251. result = eval.call(window, cmd);
  252. } catch (e) {
  253. ;
  254. }
  255. }
  256. /* debugger
  257. let result = window.__vConsole_cmd_result,
  258. error = window.__vConsole_cmd_error;*/
  259. // print result to console
  260. let $content;
  261. if (tool.isArray(result) || tool.isObject(result)) {
  262. $content = this.getFoldedLine(result);
  263. } else {
  264. if (tool.isNull(result)) {
  265. result = 'null';
  266. } else if (tool.isUndefined(result)) {
  267. result = 'undefined';
  268. } else if (tool.isFunction(result)) {
  269. result = 'function()'
  270. } else if (tool.isString(result)) {
  271. result = '"' + result + '"';
  272. }
  273. $content = $.render(tplItemCode, {content: result, type: 'output'});
  274. }
  275. this.printLog({
  276. logType: 'log',
  277. content: $content,
  278. style: ''
  279. });
  280. window.winKeys = Object.getOwnPropertyNames(window).sort();
  281. }
  282. } // END class
  283. export default VConsoleDefaultTab;