import { Error, ErrorGetStack, ObjectDefineProperty, ObjectGetPrototypeOf, ReflectApply, String, StringPrototypeSlice, uncurryThis, } from "ext:core/primordials"; import { mapSourceLocation } from "ext:core/source_map"; const lastIndexOf = uncurryThis(String.prototype.lastIndexOf); ObjectDefineProperty(Error, "prepareStackTrace", { value: (_, frames) => frames, writable: true, configurable: true, }); const prototype = ObjectGetPrototypeOf(ErrorGetStack(new Error())[0]); const fileName = uncurryThis(prototype.getFileName); const lineNumber = uncurryThis(prototype.getLineNumber); const columnNumber = uncurryThis(prototype.getColumnNumber); const frameToString = uncurryThis(prototype.toString); const errorToString = uncurryThis(Error.prototype.toString); delete Error.prepareStackTrace; export function formatStackTrace(error, frames) { const custom = Error.prepareStackTrace; if (typeof custom === "function") { return ReflectApply(custom, Error, [error, frames]); } let stack; try { stack = errorToString(error); for (let index = 0; index < frames.length; index++) { stack += `\n at ${frameToString(frames[index])}`; } } catch { // V8's reentrant fallback preserves the original message and guards hostile getters. stack = ErrorGetStack(error); } let end = stack.length; for (let index = frames.length - 1; index >= 0; index--) { const frame = frames[index]; const name = fileName(frame); const line = lineNumber(frame); const column = columnNumber(frame); const mapped = name && line && column && mapSourceLocation(name, line, column); if (!mapped) continue; let text; try { text = `\n at ${frameToString(frame)}`; } catch { continue; } const generated = `${name}:${line}:${column}`; const frameAt = lastIndexOf(stack, text, end); const locationAt = lastIndexOf(text, generated); if (frameAt === -1 || locationAt === -1) continue; end = frameAt - 1; const at = frameAt + locationAt; stack = StringPrototypeSlice(stack, 0, at) + `${mapped[0]}:${mapped[1]}:${mapped[2]}` + StringPrototypeSlice(stack, at + generated.length); } return stack; }