notes/node/source-maps.md
Node caches source maps and maps its default error stack traces when source maps are enabled through --enable-source-maps or process.setSourceMapsEnabled(true) (CLI contract).
Enabling source maps installs Node's source-map formatter as the internal stack formatter (v20.16.0 setup). Node calls a user-defined Error.prepareStackTrace before its internal formatter (v20.16.0 error formatting), so custom formatters receive CallSite locations from generated code. Node's default formatter does not map a stack trace that the custom formatter returns.
Node documents that overriding Error.prepareStackTrace can prevent source-map stack formatting and shows a delegation pattern that captures and returns the original formatter (CLI contract).
Custom formatters that need original locations can look up the generated file URL with module.findSourceMap() and map each 1-indexed CallSite line and column with sourceMap.findOrigin() (v20.16.0 API, findOrigin() contract).
import { findSourceMap } from 'node:module'
const fileName = callSite.getFileName()
const location = fileName && findSourceMap(fileName)?.findOrigin(
callSite.getLineNumber(),
callSite.getColumnNumber()
)
findSourceMap() was added in Node v12.17.0 and v13.7.0 (v20.16.0 API history). findOrigin() is available from Node v18.18.0 and v20.4.0 (v18.18.0 implementation, v20.4.0 implementation).
Node's test runner has a bug: test-definition mapping reads only the startup --enable-source-maps option (v24.15.0 utils.js) and maps locations only when that setting is enabled (test.js). This conflicts with module.setSourceMapsSupport(), which Node documents as providing the same features as the startup flag (v24.15.0 API contract). Programmatic source-map support does not update the test-runner setting.
Source-mapped test locations are available from Node v20.14.0 and v22.0.0 (v20.14.0 implementation, v22.0.0 implementation).
Node maps generated assertion positions to the original source in Node v22.21.0, v24.9.0, and v25.0.0 (Node PR #59751). The assertion-source helper maps a generated location through the cached source map (v24.9.0 error_source.js); it uses embedded source content when present and otherwise reads file URLs from disk (source_map_cache.js).