lukehaas / RunJS

RunJS is a JavaScript playground for macOS, Windows and Linux. Write code with instant feedback and access to Node.js and browser APIs.
https://runjs.app
2.03k stars 44 forks source link

implement console.trace() #224

Open 40detectives opened 3 years ago

40detectives commented 3 years ago

Could it be possible to implement console.trace? Right now the method is present in the console object but returns undefined (if you check them to be shown).

lukehaas commented 3 years ago

👍 will be good to have this at some point.

oculus42 commented 1 month ago

This is still a minor item, but it has come up for me lately. I've been testing a proof-of-concept promise tracer. This would mostly be for demonstration in RunJS, being able to demonstrate the functionality would be nice.

My example code, for reference:

const tracePromise = (promise, options, depth=0) => ({
  get then() {
    if (options.then !== false) {
      console.log(`${options.message ?? ''} .then() depth ${depth} accessed`);
      if (options.trace) console.trace();
    }
    if (!options.deep) return promise.then.bind(promise);
    return function (...args) {
      return tracePromise(promise.then(...args), options, depth+1);
    }
  },
  get catch() {
    if (options.catch !== false) {
      console.log(`${options.message ?? ''} .catch() depth ${depth} accessed`);
      if (options.trace) console.trace();
    }
    if (!options.deep) return promise.catch.bind(promise);
    return function (...args) {
      return tracePromise(promise.catch(...args), options, depth+1);
    }
  },
});

const one = () => {
  console.log('one');
  const { promise, resolve } = Promise.withResolvers();
  setTimeout(resolve, 0, 3);
  return tracePromise(promise, { message: 'one', trace: true, deep: true });
};

const two = () => {
  console.log('two');
  return one().then((v) => v * 2);
};

const three = (v) => {
  console.log('three');
  return two().then((data) => data * v);
};

three(3).then(console.log).catch(console.error);

The current output shows the console.log entries, but not the trace.

'three'
'two'
'one'
'one .then() depth 0 accessed'
'one .then() depth 1 accessed'
'one .then() depth 2 accessed'
'one .catch() depth 3 accessed'
'one .then() depth 4 accessed'
18

An example with file imports would probably be more interesting than the many "VM" entries my example provides in Chrome, but being able to see the trace in RunJS would be nice.

image