Skip to content
11 changes: 11 additions & 0 deletions docs/PROGRESS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1310,6 +1310,17 @@ recorded" was false.
Still open from #120: WebKit/Firefox projects, the 22-secret smoke, `document.open`. #119 (other masking-option
gaps on re-observed observers) is untouched.

### 2026-11-11 — `node --enable-source-maps` vs debug-ID stamping (#185)

Reproduced through the real crash builder (esbuild bundle + CLI-shaped stub, real node/bun processes,
`instrumentation-tests/test/sourcemaps-runtime.e2e.ts`): with the flag and a map on disk Node maps the registration
key's top frame to `src/main.js`, so a frame at `src/main.js:3:3` was stamped with the bundle's id (wrong line after the
backend remaps). A global skip on the flag was rejected (review): with the plugin-default deleted maps, or the flag
enabled after load, nothing is mapped and the join is correct. Fix: `applyDebugIds` validates each registration while
`process.sourceMapsEnabled` through an injected verifier (`setDebugIdRegistrationVerifier`; `@bugsee/node` installs
`createStampedBundleVerifier`, which requires the top-frame file's tail to carry `//# debugId=<id>`). The verifier decodes the percent-encoded ESM frames core leaves (`./dist/my%20chunk.mjs`, `?v=1`), caches verdicts (4096), and old Node (no `process.sourceMapsEnabled`) falls back to `--enable-source-maps` in `execArgv`/`NODE_OPTIONS`. Bun does not map
`Error.stack` (measured), unaffected. Design: `docs/design/source-maps.md` §7.2.

### 2026-11-09 — Replay moves onto upstream rrweb 2.2.1 → `krassx/rrweb-2.2.1-a625`

Fork `bugsee-port-2.2.1` (merge of rrweb-io/rrweb tag `rrweb@2.2.1` into `bugsee-port-2.2.0-iframe-block`; one
Expand Down
41 changes: 41 additions & 0 deletions docs/design/source-maps.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,47 @@ is a change to the spawn model in §4 and is tracked as OPEN-FINDINGS D3.

---

## 7.2 Runtime-mapped stacks (`node --enable-source-maps`, #185)

With `node --enable-source-maps` Node rewrites `Error.stack` to ORIGINAL positions before the SDK sees it, but only
when the bundle's `.map` is readable AND source maps were enabled before the bundle loaded
(`process.setSourceMapsEnabled(true)` affects only modules loaded afterwards). Then the stack the injected stub
registers is mapped too: its top frame becomes e.g. `src/main.js:4:1` (the appended stub has no mapping of its own),
so the `file -> debugId` join stamps the bundle's id onto already-mapped frames (measured: `src/main.js:3:3` got the
id; the backend remaps it again, a wrong line).

Two cases look the same from `process.sourceMapsEnabled` but are different, so a global switch is wrong:
- the plugin DELETES `*.map` after upload by default; with the flag on and no map on disk nothing is mapped, the
registration key and the error frames both stay on `dist/app.js`, and the plain join is correct;
- the flag turned on after the bundle loaded: same, frames are unmapped and the join is correct.

So the guard is PER REGISTRATION. While `process.sourceMapsEnabled === true` (`runtimeMapsStacks`, read through a
`globalThis` cast), `applyDebugIds` keeps a registration only if the injected verifier proves its top-frame file is the
stamped bundle. `@bugsee/node` installs that verifier at launch (`createStampedBundleVerifier`): the file's tail must
carry `//# debugId=<the registered id>` (the same marker `bundler-plugin-core` reads). A mapped registration points at
`src/main.js`, which has no stamp, so it is dropped and the frames stay unstamped (already original, no id needed).
Core stays runtime-portable: no `node:fs`, the verifier is injected (`setDebugIdRegistrationVerifier` / the
`verifyRegistration` option). With no verifier (browsers, Electron renderers: Chromium does not map `Error.stack`
even where `process.sourceMapsEnabled` reads true) every registration is kept, i.e. the previous behaviour.
The verifier reads the path the way core scrubs it, which is not always a plain path: ESM frames arrive
percent-encoded (core strips `file://` without URL-decoding): `/…/my%20app/dist/app.mjs` outside the app root,
`./dist/my%20chunk.mjs` UNDER it (the common case: `launch()` sets the app root to the cwd), possibly with an import
`?v=1`/`#hash`, and on Windows as `/C:/…`. It tries the literal path first, then the decoded form with the query
stripped, then the stripped literal. Answers are cached per (file, id), bounded to 4096 registrations (reports cost no
file I/O after the first for any realistic build; a build with more stamped chunks than that re-reads). Old Node
(18.0-18.18, 20.0-20.6) has no `process.sourceMapsEnabled`, so the probe falls back to `--enable-source-maps` in
`execArgv` / `NODE_OPTIONS` (tokenized on whitespace, double quotes stripped as Node does; `=true`/`=1` forms count, `=false`/`=0` do not); an explicit property always wins. A runtime
`process.setSourceMapsEnabled(true)` on those old versions cannot be observed. With no verifier installed the runtime is
not probed at all. Not handled: a FIFO-backed path (`/dev/fd/N`) would block the synchronous open; a bundle rewritten in
place during a deploy keeps its cached verdict until restart. Known limits: a path scrubbed to
`node_modules/...` has no `./` prefix and is resolved against `process.cwd()`, not the app root, so it verifies when
the first `node_modules` sits in the cwd and is not joined (flag on) in a hoisted monorepo or when `appRoot` differs
from the cwd. Separately (pre-existing): encoded ESM paths never match the app root, so they ship as absolute paths.
Windows hosts were not run. Bun does not map `Error.stack` and has no
`process.sourceMapsEnabled` (Bun 1.4.4, measured), so it keeps stamping, which is correct.

---

## 8. Deferred
- A real-`bugsee-cli` integration e2e (needs the built Rust binary in the harness) — follow-up once CI has it.
- Turbopack loader for Next.js (`turbopack.rules`) — Next-adapter follow-up.
Expand Down
238 changes: 237 additions & 1 deletion packages/core/src/debug-id.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { describe, expect, it } from 'vitest';
import { applyDebugIds, attachDebugIds, buildDebugIdMap, readDebugIds } from './debug-id';
import {
applyDebugIds,
attachDebugIds,
buildDebugIdMap,
readDebugIds,
runtimeMapsStacks,
setDebugIdRegistrationVerifier,
} from './debug-id';
import { parseV8Stack, type StackFrame } from './stack';

// A V8 `Error().stack` whose TOP frame is the bundle's own file (what the injected stub captures).
Expand Down Expand Up @@ -94,3 +101,232 @@ describe('applyDebugIds', () => {
}
});
});

describe('runtimeMapsStacks', () => {
it('is true only when the runtime reports `process.sourceMapsEnabled === true`', () => {
expect(runtimeMapsStacks({ sourceMapsEnabled: true })).toBe(true);
expect(runtimeMapsStacks({ sourceMapsEnabled: false })).toBe(false);
expect(runtimeMapsStacks({})).toBe(false); // Bun / browser polyfills: property absent
expect(runtimeMapsStacks({ sourceMapsEnabled: 'yes' })).toBe(false);
});

it('falls back to the launch flags where `sourceMapsEnabled` does not exist (Node < 18.19 / 20.7)', () => {
expect(runtimeMapsStacks({ execArgv: ['--no-warnings', '--enable-source-maps'] })).toBe(true);
expect(
runtimeMapsStacks({ env: { NODE_OPTIONS: '--max-old-space-size=4 --enable-source-maps' } }),
).toBe(true);
expect(runtimeMapsStacks({ execArgv: ['--no-warnings'], env: { NODE_OPTIONS: '--x' } })).toBe(
false,
);
expect(
runtimeMapsStacks({ env: { NODE_OPTIONS: '--enable-source-maps-extra --enable' } }),
).toBe(false);
expect(runtimeMapsStacks({ execArgv: 'nope', env: null })).toBe(false);
expect(runtimeMapsStacks({ env: { NODE_OPTIONS: 7 } })).toBe(false);
// an explicit answer always wins over the launch flags (setSourceMapsEnabled(false) after start)
expect(
runtimeMapsStacks({ sourceMapsEnabled: false, execArgv: ['--enable-source-maps'] }),
).toBe(false);
});

it('reads NODE_OPTIONS like Node: whitespace-separated tokens, DOUBLE quotes only (single quotes are not stripped)', () => {
const opts = (NODE_OPTIONS: string) => runtimeMapsStacks({ env: { NODE_OPTIONS } });
expect(opts('--x\t--enable-source-maps')).toBe(true);
expect(opts('--x --enable-source-maps')).toBe(true);
expect(opts('"--enable-source-maps"')).toBe(true);
expect(opts("--x '--enable-source-maps'")).toBe(false);
expect(opts('"--enable-source-maps-extra"')).toBe(false);
});

it('recognizes the `=true` form of the flag, and not `=false`/`=0`, in execArgv and NODE_OPTIONS', () => {
expect(runtimeMapsStacks({ execArgv: ['--enable-source-maps=true'] })).toBe(true);
expect(runtimeMapsStacks({ env: { NODE_OPTIONS: '--enable-source-maps=true' } })).toBe(true);
expect(runtimeMapsStacks({ env: { NODE_OPTIONS: '"--enable-source-maps=1"' } })).toBe(true);
expect(runtimeMapsStacks({ execArgv: ['--enable-source-maps=false'] })).toBe(false);
expect(runtimeMapsStacks({ env: { NODE_OPTIONS: '--enable-source-maps=0' } })).toBe(false);
expect(runtimeMapsStacks({ env: { NODE_OPTIONS: '--enable-source-maps=maybe' } })).toBe(false);
});

it('never throws: a hostile process object answers false', () => {
const hostile = {
get sourceMapsEnabled(): never {
throw new Error('getter');
},
};
expect(runtimeMapsStacks(hostile)).toBe(false);
const envThrows = {
get env(): never {
throw new Error('env getter');
},
};
expect(runtimeMapsStacks(envThrows)).toBe(false);
});

it('is false without a process object (browsers, workers, edge)', () => {
expect(runtimeMapsStacks(undefined)).toBe(false);
expect(runtimeMapsStacks(null)).toBe(false);
expect(runtimeMapsStacks(1)).toBe(false);
});

it('defaults to the live `globalThis.process`', () => {
const g = globalThis as unknown as { process?: { sourceMapsEnabled?: boolean } };
const real = g.process;
try {
g.process = { sourceMapsEnabled: true };
expect(runtimeMapsStacks()).toBe(true);
g.process = {};
expect(runtimeMapsStacks()).toBe(false);
g.process = undefined;
expect(runtimeMapsStacks()).toBe(false);
} finally {
g.process = real;
}
});
});

describe('buildDebugIdMap with an accept predicate', () => {
it('keeps only registrations the predicate accepts, passing (top-frame file, debugId)', () => {
const seen: [string, string][] = [];
const map = buildDebugIdMap(
{
[bundleStack('/app/src/main.js')]: 'mapped-id',
[bundleStack('/app/dist/app.js')]: 'real-id',
},
parseV8Stack,
(file, id) => {
seen.push([file, id]);
return file.includes('dist');
},
);
expect([...map]).toEqual([['/app/dist/app.js', 'real-id']]);
expect(seen).toEqual([
['/app/src/main.js', 'mapped-id'],
['/app/dist/app.js', 'real-id'],
]);
});
});

describe('buildDebugIdMap with a throwing predicate', () => {
it('treats a throw as a rejection of that registration only', () => {
const map = buildDebugIdMap(
{
[bundleStack('/app/dist/bad.js')]: 'bad-id',
[bundleStack('/app/dist/good.js')]: 'good-id',
},
parseV8Stack,
(file) => {
if (file.includes('bad')) throw new Error('verifier blew up');
return true;
},
);
expect([...map]).toEqual([['/app/dist/good.js', 'good-id']]);
});
});

describe('applyDebugIds under runtime source-map support (#185)', () => {
// With `node --enable-source-maps` AND a map on disk, the registration key's top frame is mapped to an
// ORIGINAL file (`src/main.js`). Joining on it stamps the bundle's id onto already-mapped frames -> the
// backend remaps them again -> a wrong line. Without the map on disk (the plugin default: maps are deleted
// after upload) nothing is mapped and the plain join is correct. So the guard is PER REGISTRATION.
const registry = {
[bundleStack('/app/src/main.js')]: 'mapped-id', // registered under a mapping runtime
[bundleStack('/app/dist/other.js')]: 'other-id', // a bundle whose map is absent
};
const verify = (file: string, id: string): boolean =>
file === '/app/dist/other.js' && id === 'other-id';
const frames = (): StackFrame[] => [
{ file: '/app/src/main.js', line: 3, column: 3 },
{ file: '/app/dist/other.js', line: 1, column: 9 },
];

it('while the runtime maps stacks, drops registrations the verifier rejects and keeps verified ones', () => {
const f = frames();
applyDebugIds(f, {
globalObject: { _bugseeDebugIds: registry },
parseStack: parseV8Stack,
runtimeMapsStacks: true,
verifyRegistration: verify,
});
expect(f[0]?.debugId).toBeUndefined();
expect(f[1]?.debugId).toBe('other-id');
});

it('does not consult the verifier when the runtime does not map stacks', () => {
const f = frames();
applyDebugIds(f, {
globalObject: { _bugseeDebugIds: registry },
parseStack: parseV8Stack,
runtimeMapsStacks: false,
verifyRegistration: () => false,
});
expect(f.map((x) => x.debugId)).toEqual(['mapped-id', 'other-id']);
});

it('keeps every registration when mapping is on but no verifier exists (browser / Electron renderer)', () => {
const f = frames();
applyDebugIds(f, {
globalObject: { _bugseeDebugIds: registry },
parseStack: parseV8Stack,
runtimeMapsStacks: true,
});
expect(f.map((x) => x.debugId)).toEqual(['mapped-id', 'other-id']);
});

it('with no verifier at all, never even probes the runtime (identical to the pre-#185 path)', () => {
const g = globalThis as unknown as {
process?: unknown;
_bugseeDebugIds?: Record<string, string>;
};
const real = g.process;
const prev = g._bugseeDebugIds;
let probed = 0;
g._bugseeDebugIds = registry;
g.process = {
get sourceMapsEnabled(): boolean {
probed++;
return true;
},
};
try {
const f = frames();
applyDebugIds(f);
expect(f.map((x) => x.debugId)).toEqual(['mapped-id', 'other-id']);
expect(probed).toBe(0);
} finally {
g.process = real;
if (prev === undefined) delete g._bugseeDebugIds;
else g._bugseeDebugIds = prev;
}
});

it('uses the installed process-wide verifier by default, and the live process probe', () => {
const g = globalThis as unknown as {
process?: { sourceMapsEnabled?: boolean };
_bugseeDebugIds?: Record<string, string>;
};
const real = g.process;
const prev = g._bugseeDebugIds;
g._bugseeDebugIds = registry;
setDebugIdRegistrationVerifier(verify);
try {
g.process = { sourceMapsEnabled: true };
const mapped = frames();
applyDebugIds(mapped);
expect(mapped.map((x) => x.debugId)).toEqual([undefined, 'other-id']);
g.process = { sourceMapsEnabled: false };
const plain = frames();
applyDebugIds(plain);
expect(plain.map((x) => x.debugId)).toEqual(['mapped-id', 'other-id']);
setDebugIdRegistrationVerifier(undefined);
g.process = { sourceMapsEnabled: true };
const none = frames();
applyDebugIds(none);
expect(none.map((x) => x.debugId)).toEqual(['mapped-id', 'other-id']);
} finally {
setDebugIdRegistrationVerifier(undefined);
g.process = real;
if (prev === undefined) delete g._bugseeDebugIds;
else g._bugseeDebugIds = prev;
}
});
});
Loading