sindresorhus / caller-callsite

Get the callsite of the caller function
MIT License
53 stars 10 forks source link

`callerCallsite()` works incorrectly if there is a top-level await before it #12

Open KostyaTretyak opened 1 month ago

KostyaTretyak commented 1 month ago

Example:

await Promise.resolve();
const callsites = callerCallsite({ depth: 0 });
console.log(callsites); // undefined

In a real-life example, I import another library of yours before calling callerCallsite(), where there is a top-level await.

KostyaTretyak commented 1 month ago

Maybe this will solve this bug:

export function callerCallsite({ depth = 0 } = {}) {
  const callers = [];
  const callerFileSet = new Set();
  const sliceOfCallsites = callsites();

  for (let i = 0; i < sliceOfCallsites.length; i++) {
    const callsite = sliceOfCallsites[i];
    const fileName = callsite.getFileName();
    const hasReceiver = callsite.getTypeName() !== null && fileName !== null;

    if (!callerFileSet.has(fileName) && !fileName?.startsWith('node:internal/')) {
      callerFileSet.add(fileName);
      callers.unshift(callsite);
    }

    if (hasReceiver || sliceOfCallsites.length == i + 1) {
      return callers[depth];
    }
  }
  return;
}