2023-07-16 06:02:12 +00:00
|
|
|
import chalk from "chalk"
|
2023-08-05 18:28:09 +00:00
|
|
|
import process from "process"
|
2023-08-09 05:52:49 +00:00
|
|
|
import { isMainThread } from "workerpool"
|
2023-07-16 06:02:12 +00:00
|
|
|
|
|
|
|
const rootFile = /.*at file:/
|
|
|
|
export function trace(msg: string, err: Error) {
|
|
|
|
const stack = err.stack
|
2023-08-09 05:52:49 +00:00
|
|
|
|
|
|
|
const lines: string[] = []
|
|
|
|
|
|
|
|
lines.push("")
|
|
|
|
lines.push(
|
|
|
|
"\n" +
|
|
|
|
chalk.bgRed.black.bold(" ERROR ") +
|
2023-07-23 18:49:26 +00:00
|
|
|
"\n" +
|
2023-08-09 05:52:49 +00:00
|
|
|
chalk.red(` ${msg}`) +
|
|
|
|
(err.message.length > 0 ? `: ${err.message}` : ""),
|
2023-07-23 00:27:41 +00:00
|
|
|
)
|
2023-08-09 05:52:49 +00:00
|
|
|
|
2023-07-16 06:02:12 +00:00
|
|
|
if (!stack) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
let reachedEndOfLegibleTrace = false
|
2023-07-23 00:27:41 +00:00
|
|
|
for (const line of stack.split("\n").slice(1)) {
|
2023-07-16 06:02:12 +00:00
|
|
|
if (reachedEndOfLegibleTrace) {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!line.includes("node_modules")) {
|
2023-08-09 05:52:49 +00:00
|
|
|
lines.push(` ${line}`)
|
2023-07-16 06:02:12 +00:00
|
|
|
if (rootFile.test(line)) {
|
|
|
|
reachedEndOfLegibleTrace = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-08-09 05:52:49 +00:00
|
|
|
|
|
|
|
const traceMsg = lines.join("\n")
|
|
|
|
if (!isMainThread) {
|
|
|
|
// gather lines and throw
|
|
|
|
throw new Error(traceMsg)
|
|
|
|
} else {
|
|
|
|
// print and exit
|
|
|
|
console.error(traceMsg)
|
|
|
|
process.exit(1)
|
|
|
|
}
|
2023-07-16 06:02:12 +00:00
|
|
|
}
|