# API Reference ## Runtime and module identity The package targets Node.js 14.15.1 and newer. Its root runtime implementation is CommonJS. `require('@stackline/source-map-support')` returns an ordinary namespace object and does not install hooks by itself. The CommonJS root has exactly these enumerable keys, in order: 1. `wrapCallSite` 2. `getErrorSource` 3. `mapSourcePosition` 4. `retrieveSourceMap` 5. `install` 6. `resetRetrieveHandlers` The ESM host entry returns that same object as its default export and exposes the same six functions as named exports. The ESM facade is not a second implementation and does not install hooks. ## Coordinates and payloads ```ts interface Position { source: string line: number column: number name?: string | null } interface UrlAndMap { url?: string map: string | object } interface SourceMapPayload extends UrlAndMap {} interface State { nextPosition: Position | null curPosition: Position | null } ``` Lines are one-based. Columns are zero-based in `Position`; rendered stack columns are converted back to the one-based form users see. `map` can be JSON text or an object accepted by `@jridgewell/trace-mapping`'s `AnyMap` constructor. `AnyMap` accepts both regular and indexed/sectioned Source Map v3 payloads. `url` is optional for compatibility; provide it whenever relative `sourceRoot` or source paths must resolve from a known map location. ## `install(options?)` ```ts function install(options?: InstallOptions): void ``` Installs the package's global stack formatter once and applies requested retrieval, environment, cache, CommonJS compilation, and uncaught-exception options. ### `environment` ```ts environment?: 'auto' | 'browser' | 'node' ``` The default is `auto`. Explicit `browser` selects browser retrieval; explicit `node` selects local filesystem behavior. Any other value throws the preserved error: ```text environment VALUE was unknown. Available options are {auto, browser, node} ``` In auto mode, a realm is treated as a browser when `window` exists, `XMLHttpRequest` is callable, and it is not an Electron renderer exposing the historical `window.require`, `window.module`, and `window.process.type === 'renderer'` shape. This detection is compatibility behavior; Electron callers with a deliberate custom integration should set the environment explicitly. ### `retrieveFile` and `overrideRetrieveFile` ```ts type RetrieveFile = (path: string) => string | null | undefined retrieveFile?: RetrieveFile overrideRetrieveFile?: boolean ``` The handler is synchronous. A truthy string is a hit; a nullish or empty result allows the next provider to run. By default, a newly installed handler has priority over existing handlers. `overrideRetrieveFile: true` clears the list before adding it. The built-in Node provider trims the path, handles `file:` paths, and reads an existing file as UTF-8. The built-in browser provider uses synchronous `XMLHttpRequest` when no filesystem implementation is present. ### `retrieveSourceMap` and `overrideRetrieveSourceMap` ```ts type RetrieveSourceMap = ( source: string ) => SourceMapPayload | null | undefined retrieveSourceMap?: RetrieveSourceMap overrideRetrieveSourceMap?: boolean ``` The handler is synchronous and receives the generated source name. Return `{ map, url? }` or a nullish miss. New handlers take priority. The override flag clears the existing map providers before adding the custom provider. The built-in provider finds the final matching `sourceMappingURL` comment, decodes inline base64 JSON, or resolves and reads an external map. Browser mode also recognizes `SourceMap` and `X-SourceMap` response headers. A malformed inline base64 payload is treated as a retrieval miss, including in browser runtimes whose `atob()` rejects it, rather than replacing the original stack failure with a decoding exception. A provider exception is an integration failure and can escape stack work. Custom providers must catch their own expected failures and bound their work. ### `hookRequire` ```ts hookRequire?: boolean ``` Outside browser mode, true wraps Node's private `Module.prototype._compile`. The wrapper caches source passed to the compiler and invalidates the corresponding map cache, which preserves runtime-transpiler inline maps. The hook is installed once and is process-global. It is not removed by `resetRetrieveHandlers()`. It relies on a private Node implementation surface, so consumers must smoke-test their actual loader and runtime. ### `emptyCacheBetweenOperations` ```ts emptyCacheBetweenOperations?: boolean ``` When enabled, the file-content and source-map caches are replaced before each stack-formatting operation. This can reduce cross-operation retention at the cost of repeated synchronous retrieval and parsing. Direct `mapSourcePosition()` calls are not themselves stack-formatting operations. ### `handleUncaughtExceptions` ```ts handleUncaughtExceptions?: boolean ``` Defaults to true when first installed in the Node main thread. The historical shim wraps `process.emit` so an uncaught error with a stack and no user listener can print mapped source context synchronously and exit. Worker threads disable this shim because their errors are delivered to the parent. Set false when a test runner, Electron integration, application framework, or other owner manages uncaught exceptions. The wrapper is installed at most once and is not uninstalled by the reset function. If `process.exitCode` is already nonzero, the maintained implementation preserves it; otherwise it exits 1. ### Global formatter The first call to `install()` assigns `Error.prepareStackTrace`. Later calls can add providers and options but do not install a second formatter. The package does not preserve or restore a previous formatter automatically. ## `mapSourcePosition(position)` ```ts function mapSourcePosition(position: Position): Position ``` Retrieves and caches a map for `position.source`, traces the generated one-based line and zero-based column, resolves the original source against the map URL and `sourceRoot`, and returns the mapped position. A mapped name is included when present. Regular Source Map v3 payloads and indexed maps with `sections` are both accepted through `AnyMap`. Section line/column offsets, mapped names, and embedded `sourcesContent` are retained when the indexed map is flattened. The generated position is returned when: - no provider finds a map; - the map is malformed; - lookup throws; - the requested segment has no original source; - the map contains a gap at that position. Malformed maps and misses are cached. A precise generated position is favored over an imprecise original location. When the map includes `sourcesContent`, truthy source values are cached under their resolved source URLs for later `getErrorSource()` calls. The declarations also export `Environment`, `Options`, and `InstallOptions`; `InstallOptions` extends the same option surface documented in the install section. ## `wrapCallSite(frame, state?)` ```ts function wrapCallSite(frame: CallSite, state?: State): CallSite ``` Maps one V8-compatible CallSite. Native frames are returned unchanged. Normal frames receive mapped file, line, column, script URL, and when available the mapped name. Eval origins are parsed recursively and mapped where their shape is recognized. The optional `State` is the historical formatter coordination object used to carry the current and next mapped positions while a stack is processed in reverse. Direct callers normally omit it; omission creates a fresh null state. The public `CallSite` declaration includes: ```text getThis, getTypeName, getFunction, getFunctionName, getMethodName, getFileName, getLineNumber, getColumnNumber, getEvalOrigin, getScriptNameOrSourceURL, isToplevel, isEval, isNative, isConstructor, optional isAsync, optional isPromiseAll, optional getPromiseIndex, toString ``` The formatter's `CallSiteToString` derives from V8 4.3.49 code and is covered by the V8 BSD 3-Clause attribution in NOTICE and the licenses directory. Its observable formatting retains the current native V8 convention for a differently named property, such as `Object.doSomething [as customMethod]`. ## `getErrorSource(error)` ```ts function getErrorSource(error: Error): string | null ``` Inspects the first recognized mapped stack frame. When the original source is available from cached `sourcesContent` or a readable local file, returns: ```text /path/or/url/original.ts:LINE source line text ^ ``` Returns null when no frame, file, or nonempty source line can be found. This is diagnostic formatting, not a source-code redaction or containment API. ## `retrieveSourceMap(source)` ```ts function retrieveSourceMap(source: string): SourceMapPayload | null ``` Runs the source-map provider chain and returns its first truthy payload or null. The exported function is primarily retained for upstream compatibility; applications normally provide a hook through `install()` or call `mapSourcePosition()`. ## `resetRetrieveHandlers()` ```ts function resetRetrieveHandlers(): void ``` Restores the original built-in file and source-map provider lists. It does not: - restore a prior `Error.prepareStackTrace`; - restore the original `process.emit`; - restore `Module.prototype._compile`; - clear every existing cache immediately; - create an isolated mapper instance. Use it to isolate retrieval-provider tests, not as a general uninstall API. ## Supported entries The export map intentionally supports these ten keys: 1. `.` 2. `./source-map-support` 3. `./source-map-support.js` 4. `./register` 5. `./register.js` 6. `./register-hook-require` 7. `./register-hook-require.js` 8. `./browser-source-map-support` 9. `./browser-source-map-support.js` 10. `./package.json` `register` calls `install()` as a side effect. `register-hook-require` calls `install({ hookRequire: true })`. Both have empty side-effect TypeScript modules. The browser entry has the root namespace declaration and does not use the Node register side effect. The root export also has browser conditions. Browser-aware ESM imports select `browser-source-map-support.mjs`; browser-aware CommonJS resolution selects `browser-source-map-support.js`. The package `browser` field maps the explicit Node implementation file to the UMD browser implementation for legacy bundlers. These files are condition targets, not additional public export-map keys. ## Browser UMD and ESM contract The standalone browser bundle targets ES2015 and is self-contained. It selects one delivery form: - CommonJS: `module.exports = factory()`; - AMD: `define('browser-source-map-support', factory)`; - global: `globalThis.sourceMapSupport = factory()`. The companion browser ESM host provides the same API object as default and the same six named function identities. An ordinary root ESM import in a browser-aware bundler selects this host; an explicit `browser-source-map-support` deep import continues to select the UMD artifact. Its six-function API and custom browser map resolution are verified in all three UMD delivery forms and through the ESM host. Bundler gates verify root require/import selection. Default external retrieval uses synchronous XHR and is subject to browser origin policy. The bundled path implementation resolves relative map and source URLs without requiring a Node `process` global, and malformed inline maps fail back to their generated locations. Automatic stack formatting additionally depends on compatible V8-style Error and CallSite behavior. ## TypeScript declarations The historical CommonJS namespace declaration is compatible with TypeScript 3.9 and supports `export =` plus `export as namespace`. Modern CommonJS resolution uses `.d.cts`; modern ESM resolution uses `.d.mts` and exposes the default namespace plus named functions. The register and browser entries have their own declarations. Types describe the supported API but do not make global hooks local, retrieval asynchronous, or arbitrary browser engines compatible.