add console.log automaticaly to 1-lvl expressions
This commit is contained in:
@@ -3,6 +3,8 @@ import { stringify } from 'javascript-stringify';
|
||||
import { MAX_DATA_SIZE } from './app.config';
|
||||
import { getType } from '@gkucmierz/utils/src/get-type';
|
||||
|
||||
import { addDefaultLog } from './utils/utils';
|
||||
|
||||
const log = console.log;
|
||||
console.log = (...a) => l(a);
|
||||
console.error = a => e(a);
|
||||
@@ -61,7 +63,7 @@ const e = err => {
|
||||
|
||||
addEventListener('message', ({ data }) => {
|
||||
try {
|
||||
const code = new Function(data);
|
||||
const code = new Function(addDefaultLog(data));
|
||||
code();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
|
||||
37
src/utils/utils.mjs
Normal file
37
src/utils/utils.mjs
Normal file
@@ -0,0 +1,37 @@
|
||||
|
||||
import { parseScript } from 'meriyah';
|
||||
|
||||
export const addDefaultLog = code => {
|
||||
const lines = code.split('\n');
|
||||
const tree = parseScript(code, { loc: true });
|
||||
|
||||
const insert = ({ line, column }, str, trim = false) => {
|
||||
const l = lines[line-1];
|
||||
lines[line-1] = [
|
||||
trim ? l.substr(0, column).replace(/;$/, '') : l.substr(0, column),
|
||||
str,
|
||||
l.substr(column)
|
||||
].join('');
|
||||
};
|
||||
|
||||
const exprs = (tree.body
|
||||
.filter(node => node.type === 'ExpressionStatement')
|
||||
.filter(node => {
|
||||
const expr = node.expression;
|
||||
if (expr.type !== 'CallExpression') return true;
|
||||
const callee = expr.callee;
|
||||
if (callee.type !== 'MemberExpression') return true;
|
||||
if (callee.object.type !== 'Identifier') return true;
|
||||
if (callee.object.name !== 'console') return true;
|
||||
return false;
|
||||
})
|
||||
);
|
||||
|
||||
exprs.map(expr => {
|
||||
const { start, end } = expr.loc;
|
||||
insert(end, ');', true);
|
||||
insert(start, 'console.log(');
|
||||
});
|
||||
|
||||
return lines.join('\n');
|
||||
};
|
||||
@@ -20,6 +20,9 @@ export default defineComponent({
|
||||
},
|
||||
data() {
|
||||
const code = `
|
||||
'Hello World!';
|
||||
|
||||
2n ** 42n;
|
||||
|
||||
for (let i = 0; i < 42; ++i) {
|
||||
console.log(i);
|
||||
|
||||
Reference in New Issue
Block a user