Jacky Zhao
2023-08-09 49bd6bc3ffe1d3507e00bae62c12d9b045363090
quartz/trace.ts
@@ -1,25 +1,47 @@
import chalk from "chalk"
import process from "process"
import { isMainThread } from "workerpool"
const rootFile = /.*at file:/
export function trace(msg: string, err: Error) {
  const stack = err.stack
  console.log()
  console.log(chalk.bgRed.white.bold(" ERROR ") + chalk.red(` ${msg}`) + (err.message.length > 0 ? `: ${err.message}` : ""))
  const lines: string[] = []
  lines.push("")
  lines.push(
    "\n" +
    chalk.bgRed.black.bold(" ERROR ") +
    "\n" +
    chalk.red(` ${msg}`) +
    (err.message.length > 0 ? `: ${err.message}` : ""),
  )
  if (!stack) {
    return
  }
  let reachedEndOfLegibleTrace = false
  for (const line of stack.split('\n').slice(1)) {
  for (const line of stack.split("\n").slice(1)) {
    if (reachedEndOfLegibleTrace) {
      break
    }
    if (!line.includes("node_modules")) {
      console.log(` ${line}`)
      lines.push(` ${line}`)
      if (rootFile.test(line)) {
        reachedEndOfLegibleTrace = true
      }
    }
  }
  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)
  }
}