Skip to content

Commit

Permalink
perf(ssr): calculate stacktrace offset lazily (#13256)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tomer Ohana authored May 22, 2023
1 parent 3f3fff2 commit 906c4c1
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions packages/vite/src/node/ssr/ssrStacktrace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,28 @@ import { TraceMap, originalPositionFor } from '@jridgewell/trace-mapping'
import type { ModuleGraph } from '../server/moduleGraph'

let offset: number
try {
new Function('throw new Error(1)')()
} catch (e) {
// in Node 12, stack traces account for the function wrapper.
// in Node 13 and later, the function wrapper adds two lines,
// which must be subtracted to generate a valid mapping
const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1])
offset = match ? +match[1] - 1 : 0

function calculateOffsetOnce() {
if (offset !== undefined) {
return
}

try {
new Function('throw new Error(1)')()
} catch (e) {
// in Node 12, stack traces account for the function wrapper.
// in Node 13 and later, the function wrapper adds two lines,
// which must be subtracted to generate a valid mapping
const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1])
offset = match ? +match[1] - 1 : 0
}
}

export function ssrRewriteStacktrace(
stack: string,
moduleGraph: ModuleGraph,
): string {
calculateOffsetOnce()
return stack
.split('\n')
.map((line) => {
Expand Down

0 comments on commit 906c4c1

Please sign in to comment.