fix: Improve get caller file path util (#7974)

* fix: Improve get caller file path util

* improve compatibility

* update comment

---------

Co-authored-by: Riqwan Thamir <rmthamir@gmail.com>
This commit is contained in:
Adrien de Peretti
2024-07-05 12:54:27 +02:00
committed by GitHub
co-authored by Riqwan Thamir
parent de0a9c14ab
commit 1393f51046
2 changed files with 18 additions and 17 deletions
@@ -4,24 +4,26 @@
*/
export function getCallerFilePath(position = 2) {
if (position >= Error.stackTraceLimit) {
throw new TypeError(
"getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `" +
position +
"` and Error.stackTraceLimit was: `" +
Error.stackTraceLimit +
"`"
)
return null
}
const oldPrepareStackTrace = Error.prepareStackTrace
Error.prepareStackTrace = (_, stack) => stack
const stack = new Error().stack
let result!: string
Error.prepareStackTrace = (_, stack) => {
if (stack !== null && typeof stack === "object") {
// stack[0] holds this file
// stack[1] holds where this function was called
// stack[2] holds the file we're interested in, in most cases, otherwise we need to get higher
result = stack[position]
? (stack[position] as any).getFileName()
: undefined
}
return stack
}
new Error().stack
Error.prepareStackTrace = oldPrepareStackTrace
if (stack !== null && typeof stack === "object") {
// stack[0] holds this file
// stack[1] holds where this function was called
// stack[2] holds the file we're interested in
return stack[position] ? (stack[position] as any).getFileName() : undefined
}
return result
}