diff --git a/.changeset/node-module-load-failure-context.md b/.changeset/node-module-load-failure-context.md new file mode 100644 index 00000000..5de13a81 --- /dev/null +++ b/.changeset/node-module-load-failure-context.md @@ -0,0 +1,5 @@ +--- +'@bugsee/node': patch +--- + +An uncaught exception or unhandled rejection raised while LOADING a module now names the module that failed, instead of being reported as an error at `node:internal/modules/...` (Node) or with no frames at all (Bun). The failed module becomes the first frame (`import()` or `require()`), and the report description adds the importer, how it was loaded, the error `code` and the CommonJS `require` stack. Node reports a failed ESM/CJS resolution (`ERR_MODULE_NOT_FOUND`, `MODULE_NOT_FOUND`, `ERR_UNSUPPORTED_DIR_IMPORT`, `ERR_PACKAGE_PATH_NOT_EXPORTED`, ...) with the module in the message and in `url`/`requireStack`; Bun (via `@bugsee/bun`, which re-exports this composition) reports a stackless `ResolveMessage` whose `specifier`/`referrer`/`importKind` the SDK now reads. A syntax error becomes a frame at its file, line and column, from Bun's build-error `position` or from the header of Node's stack (present for a CommonJS file and for a missing named export; Node gives no file for a syntax error in a dynamically imported ES module, so that case is unchanged). Bun's stackless missing-named-export SyntaxError names the module from its message. The runtime's own frames are kept after the new first frame, and a caller-supplied frame enricher still runs first. diff --git a/packages/instrumentation-tests/test/spec-drift.test.ts b/packages/instrumentation-tests/test/spec-drift.test.ts index 57ea9107..b3e366ad 100644 --- a/packages/instrumentation-tests/test/spec-drift.test.ts +++ b/packages/instrumentation-tests/test/spec-drift.test.ts @@ -92,6 +92,10 @@ const NOT_A_WIRE_NAME: Readonly< reason: "the on-disk subdirectory 'capture'", literals: { capture: 1 }, }, + 'node/src/module-load-failure.ts': { + reason: "the Node error property 'url' (the URL of the module that failed to load)", + literals: { url: 1 }, + }, 'node/src/recover-instances.ts': { reason: "the on-disk subdirectory 'capture'", literals: { capture: 1 }, diff --git a/packages/node/src/detection-providers.test.ts b/packages/node/src/detection-providers.test.ts index 554a7c7b..1c109c74 100644 --- a/packages/node/src/detection-providers.test.ts +++ b/packages/node/src/detection-providers.test.ts @@ -247,3 +247,51 @@ describe('debug-ids on node crash frames', () => { }); }); }); + +describe('a failed module load', () => { + const notFound = () => { + const error = Object.assign( + new Error("Cannot find module '/app/lazy.mjs' imported from /app/main.mjs"), + { code: 'ERR_MODULE_NOT_FOUND', url: 'file:///app/lazy.mjs' }, + ); + error.stack = `Error [ERR_MODULE_NOT_FOUND]: ${error.message}\n at finalizeResolution (node:internal/modules/esm/resolve:241:11)`; + return error; + }; + + it('is reported with the failed module as its first frame and in the description (uncaught)', () => { + const p = fakeProcess(); + const requests = started(createUncaughtExceptionProvider(p.proc)); + p.emit('uncaughtException', notFound()); + const report = requests[0]?.report as unknown as { description: string; crash: CrashJson }; + expect(report.crash.exception.frames[0]?.trace).toBe('at import() (/app/lazy.mjs)'); + expect(report.description).toContain('Failed module: /app/lazy.mjs'); + expect(report.description).toContain('Imported from: /app/main.mjs'); + expect(report.description).toContain('finalizeResolution'); + }); + + it('is reported the same way for an unhandled rejection, with no stack at all (bun)', () => { + const error = notFound(); + error.stack = undefined; + const p = fakeProcess(); + const requests = started(createUnhandledRejectionProvider(p.proc)); + p.emit('unhandledRejection', error); + const report = requests[0]?.report as unknown as { description: string; crash: CrashJson }; + expect(report.crash.exception.frames).toHaveLength(1); + expect(report.description).toContain('Code: ERR_MODULE_NOT_FOUND'); + }); + + it('keeps the caller-supplied frame enricher, and still adds the module', () => { + const p = fakeProcess(); + const seen: number[] = []; + const requests: ReportingRequest[] = []; + createUncaughtExceptionProvider(p.proc, (_error, frames) => { + seen.push(frames.length); + return frames; + }).start(dummyClient, (r) => requests.push(r)); + p.emit('uncaughtException', notFound()); + expect(seen).toEqual([1]); + expect( + (requests[0]?.report as unknown as { crash: CrashJson }).crash.exception.frames, + ).toHaveLength(2); + }); +}); diff --git a/packages/node/src/detection-providers.ts b/packages/node/src/detection-providers.ts index e69e27a8..93ae5eb9 100644 --- a/packages/node/src/detection-providers.ts +++ b/packages/node/src/detection-providers.ts @@ -2,6 +2,7 @@ import process from 'node:process'; import type { CrashJson, DetectionProvider } from '@bugsee/core'; import { buildCrashJson, + composeFrameEnrichers, DetectionProviderBase, describeThrown, type FrameEnricher, @@ -9,6 +10,7 @@ import { parseV8Stack, } from '@bugsee/core'; import { BugseeOption } from '@bugsee/protocol'; +import { describeModuleLoadFailure, moduleLoadFrameEnricher } from './module-load-failure'; import { markOwnHandler } from './process-policy'; // Node crash/error detection providers (the globalErrorInterceptor equivalent on Node). @@ -29,10 +31,14 @@ export interface ProcessEvents { function describeError(value: unknown): { summary: string; description?: string } { if (value instanceof Error) { const summary = value.message || value.name; - if (value.stack) { - return { summary, description: formatStack(parseV8Stack(value.stack)) }; - } - return { summary }; + // A failed module load: the failed module first (the runtime's own stack is loader internals, or absent in Bun), then whatever + // stack there is. + const moduleFailure = describeModuleLoadFailure(value); + const frames = value.stack ? formatStack(parseV8Stack(value.stack)) : undefined; + const description = [moduleFailure, frames] + .filter((part) => part !== undefined && part !== '') + .join('\n'); + return description === '' ? { summary } : { summary, description }; } return { summary: describeThrown(value) }; } @@ -46,10 +52,15 @@ function describeError(value: unknown): { summary: string; description?: string * could not see it: they drive `logException`, which does go through the client. */ function crashOf(value: unknown, enrichFrames?: FrameEnricher): CrashJson | undefined { + // The failed module goes in last, after the locals enricher has seen the runtime's own frames. + const enrich = composeFrameEnrichers([ + ...(enrichFrames !== undefined ? [enrichFrames] : []), + moduleLoadFrameEnricher, + ]); return buildCrashJson(value, { parseStack: parseV8Stack, handled: false, - ...(enrichFrames !== undefined ? { enrichFrames } : {}), + ...(enrich !== undefined ? { enrichFrames: enrich } : {}), }); } diff --git a/packages/node/src/module-load-failure.test.ts b/packages/node/src/module-load-failure.test.ts new file mode 100644 index 00000000..43ebea72 --- /dev/null +++ b/packages/node/src/module-load-failure.test.ts @@ -0,0 +1,495 @@ +import { describe, expect, it } from 'vitest'; +import { + describeModuleLoadFailure, + detectModuleLoadFailure, + IMPORT_FRAME_FUNCTION, + moduleLoadFrameEnricher, + REQUIRE_FRAME_FUNCTION, +} from './module-load-failure'; + +// Shapes copied from what node 26 and bun 1.4 really produce (see the module's header). +function nodeEsmNotFound(): Error { + return Object.assign( + new Error("Cannot find module '/app/lazy.mjs' imported from /app/main.mjs"), + { code: 'ERR_MODULE_NOT_FOUND', url: 'file:///app/lazy.mjs' }, + ); +} + +function nodeEsmPackageNotFound(): Error { + return Object.assign(new Error("Cannot find package 'left-pad' imported from /app/main.mjs"), { + code: 'ERR_MODULE_NOT_FOUND', + }); +} + +function nodeCjsNotFound(): Error { + return Object.assign( + new Error("Cannot find module './missing'\nRequire stack:\n- /app/a.cjs\n- /app/main.cjs"), + { code: 'MODULE_NOT_FOUND', requireStack: ['/app/a.cjs', '/app/main.cjs'] }, + ); +} + +function bunResolve(extra: Record = {}): Error { + const error = new Error("Cannot find module './nope-dep.mjs' imported from /app/dep.mjs"); + error.name = 'ResolveMessage'; + return Object.assign(error, { + code: 'ERR_MODULE_NOT_FOUND', + specifier: './nope-dep.mjs', + referrer: '/app/dep.mjs', + importKind: 'import-statement', + ...extra, + }); +} + +function bunBuildError(column: number | null = 17): Error { + const error = new Error('2 errors building "/app/syntax.mjs"'); + error.name = 'AggregateError'; + return Object.assign(error, { + errors: [ + { + name: 'BuildMessage', + position: { file: '/app/syntax.mjs', line: 1, column: column ?? undefined }, + }, + ], + }); +} + +function nodeSyntax(): Error { + const error = new SyntaxError( + "The requested module './exports.mjs' does not provide an export named 'nothere'", + ); + error.stack = [ + 'file:///app/named.mjs:1', + "import { nothere } from './exports.mjs';", + ' ^^^^^^^', + `SyntaxError: ${error.message}`, + ' at #asyncInstantiate (node:internal/modules/esm/module_job:463:21)', + ].join('\n'); + return error; +} + +describe('detectModuleLoadFailure', () => { + it('reads a CommonJS syntax-error header, whose file is a bare path', () => { + const error = new SyntaxError('Unexpected token'); + error.stack = + '/app/broken.cjs:3\nconst = ;\n ^\n\nSyntaxError: Unexpected token\n at wrapSafe (node:internal/modules/cjs/loader:1)'; + expect(detectModuleLoadFailure(error)?.position).toEqual({ + file: '/app/broken.cjs', + line: 3, + column: 7, + }); + }); + + it('ignores a SyntaxError with no stack and no position', () => { + const error = new SyntaxError('Unexpected token'); + error.stack = undefined; + expect(detectModuleLoadFailure(error)).toBeUndefined(); + }); + + it('reads a node ESM resolution failure from its url and message', () => { + expect(detectModuleLoadFailure(nodeEsmNotFound())).toEqual({ + kind: 'resolution', + via: 'import', + requireStack: [], + module: '/app/lazy.mjs', + importer: '/app/main.mjs', + code: 'ERR_MODULE_NOT_FOUND', + }); + }); + + it('reads a missing package from the message alone', () => { + expect(detectModuleLoadFailure(nodeEsmPackageNotFound())).toMatchObject({ + module: 'left-pad', + importer: '/app/main.mjs', + via: 'import', + }); + }); + + it('treats a require chain as a require, importer first', () => { + expect(detectModuleLoadFailure(nodeCjsNotFound())).toMatchObject({ + via: 'require', + module: './missing', + importer: '/app/a.cjs', + requireStack: ['/app/a.cjs', '/app/main.cjs'], + }); + }); + + it("reads bun's structured ResolveMessage fields, which carry no stack", () => { + expect(detectModuleLoadFailure(bunResolve())).toMatchObject({ + module: './nope-dep.mjs', + importer: '/app/dep.mjs', + via: 'import', + code: 'ERR_MODULE_NOT_FOUND', + }); + expect(detectModuleLoadFailure(bunResolve({ importKind: 'require-call' }))?.via).toBe( + 'require', + ); + }); + + it("finds the position of bun's build error and of node's syntax-error stack header", () => { + expect(detectModuleLoadFailure(bunBuildError())?.position).toEqual({ + file: '/app/syntax.mjs', + line: 1, + column: 17, + }); + expect(detectModuleLoadFailure(nodeSyntax())?.position).toEqual({ + file: '/app/named.mjs', + line: 1, + column: 10, + }); + }); + + it("names the module of bun's stackless missing-export SyntaxError", () => { + const error = new SyntaxError("Export named 'nothere' not found in module '/app/exports.mjs'."); + error.stack = undefined; + expect(detectModuleLoadFailure(error)).toMatchObject({ + kind: 'resolution', + module: '/app/exports.mjs', + missingExport: 'nothere', + }); + expect(describeModuleLoadFailure(error)).toBe( + 'Failed module: /app/exports.mjs\nLoaded via: import\nMissing export: nothere', + ); + expect(moduleLoadFrameEnricher(error, [])).toEqual([ + { function: IMPORT_FRAME_FUNCTION, file: '/app/exports.mjs' }, + ]); + }); + + it('ignores errors that are not module loads', () => { + expect(detectModuleLoadFailure(new Error('boom'))).toBeUndefined(); + expect( + detectModuleLoadFailure(new SyntaxError('Unexpected end of JSON input')), + ).toBeUndefined(); + expect( + detectModuleLoadFailure(Object.assign(new Error('x'), { code: 'ENOENT' })), + ).toBeUndefined(); + expect(detectModuleLoadFailure('ERR_MODULE_NOT_FOUND')).toBeUndefined(); + expect(detectModuleLoadFailure(null)).toBeUndefined(); + const aggregate = new AggregateError([new Error('a')], 'many'); + expect(detectModuleLoadFailure(aggregate)).toBeUndefined(); + }); + + it('survives a hostile error whose getters throw', () => { + const hostile = Object.defineProperties(new Error('x'), { + code: { + get() { + throw new Error('getter'); + }, + }, + name: { + get() { + throw new Error('getter'); + }, + }, + }); + expect(detectModuleLoadFailure(hostile)).toBeUndefined(); + }); + + it('keeps going when one field is unusable', () => { + const odd = Object.assign(new Error("Cannot find module 'x'"), { + code: 'MODULE_NOT_FOUND', + requireStack: 'not-an-array', + url: 'file://%zz', + }); + expect(detectModuleLoadFailure(odd)).toMatchObject({ requireStack: [] }); + }); +}); + +describe('moduleLoadFrameEnricher', () => { + const internal = [ + { + function: 'finalizeResolution', + file: 'node:internal/modules/esm/resolve', + line: 241, + column: 11, + }, + ]; + + it('puts the failed module first and keeps the runtime frames', () => { + const frames = moduleLoadFrameEnricher(nodeEsmNotFound(), internal); + expect(frames[0]).toEqual({ function: IMPORT_FRAME_FUNCTION, file: '/app/lazy.mjs' }); + expect(frames.slice(1)).toEqual(internal); + }); + + it('is the only frame when the runtime gave none (bun)', () => { + expect(moduleLoadFrameEnricher(bunResolve(), [])).toEqual([ + { function: IMPORT_FRAME_FUNCTION, file: './nope-dep.mjs' }, + ]); + }); + + it('names a require()', () => { + expect(moduleLoadFrameEnricher(nodeCjsNotFound(), [])[0]?.function).toBe( + REQUIRE_FRAME_FUNCTION, + ); + }); + + it('turns a syntax error into a frame at its position, once', () => { + const frames = moduleLoadFrameEnricher(nodeSyntax(), internal); + expect(frames[0]).toMatchObject({ file: '/app/named.mjs', line: 1, column: 10 }); + expect(moduleLoadFrameEnricher(nodeSyntax(), frames)).toBe(frames); + const columnless = bunBuildError(null); + expect(moduleLoadFrameEnricher(columnless, [])[0]).toEqual({ + file: '/app/syntax.mjs', + line: 1, + }); + }); + + it('leaves any other error alone, and a failure that names no module', () => { + const frames = [{ file: 'a.js', line: 1, column: 1 }]; + expect(moduleLoadFrameEnricher(new Error('x'), frames)).toBe(frames); + const nameless = Object.assign(new Error('Module resolution failed'), { + code: 'ERR_REQUIRE_ESM', + }); + expect(moduleLoadFrameEnricher(nameless, frames)).toBe(frames); + }); +}); + +describe('describeModuleLoadFailure', () => { + it('lists the module, importer, how it was loaded, the code and the require stack', () => { + expect(describeModuleLoadFailure(nodeCjsNotFound())).toBe( + [ + 'Failed module: ./missing', + 'Imported from: /app/a.cjs', + 'Loaded via: require()', + 'Code: MODULE_NOT_FOUND', + 'Require stack:', + ' /app/a.cjs', + ' /app/main.cjs', + ].join('\n'), + ); + }); + + it('describes an ESM failure and a syntax error', () => { + expect(describeModuleLoadFailure(nodeEsmNotFound())).toBe( + [ + 'Failed module: /app/lazy.mjs', + 'Imported from: /app/main.mjs', + 'Loaded via: import', + 'Code: ERR_MODULE_NOT_FOUND', + ].join('\n'), + ); + expect(describeModuleLoadFailure(nodeSyntax())).toBe( + 'Syntax error in module: /app/named.mjs:1:10', + ); + expect(describeModuleLoadFailure(bunBuildError())).toBe( + 'Syntax error in module: /app/syntax.mjs:1:17', + ); + }); + + it('says only what it knows', () => { + const bare = Object.assign(new Error('nope'), { code: 'ERR_REQUIRE_ESM' }); + expect(describeModuleLoadFailure(bare)).toBe('Loaded via: require()\nCode: ERR_REQUIRE_ESM'); + const noCode = bunResolve({ code: undefined }); + expect(describeModuleLoadFailure(noCode)).not.toContain('Code:'); + }); + + it('is undefined for any other error', () => { + expect(describeModuleLoadFailure(new Error('x'))).toBeUndefined(); + }); +}); + +describe('review follow-ups', () => { + const coded = (code: string, message: string): Error => + Object.assign(new Error(message), { code }); + + it('names the module and importer of an unexported package subpath', () => { + const failure = detectModuleLoadFailure( + coded( + 'ERR_PACKAGE_PATH_NOT_EXPORTED', + `Package subpath './sub' is not defined by "exports" in /app/node_modules/pkg/package.json imported from /app/a.mjs`, + ), + ); + expect(failure?.module).toBe('pkg/sub'); + expect(failure?.importer).toBe('/app/a.mjs'); + }); + + it('names the directory of a directory import and its importer', () => { + const failure = detectModuleLoadFailure( + coded( + 'ERR_UNSUPPORTED_DIR_IMPORT', + "Directory import '/app/dir' is not supported resolving ES modules imported from /app/a.mjs", + ), + ); + expect(failure?.module).toBe('/app/dir'); + expect(failure?.importer).toBe('/app/a.mjs'); + }); + + it('names the file of an unknown extension', () => { + const failure = detectModuleLoadFailure( + coded('ERR_UNKNOWN_FILE_EXTENSION', 'Unknown file extension ".xyz" for /app/component.xyz'), + ); + expect(failure?.module).toBe('/app/component.xyz'); + }); + + it('reports a require() of an ES module as a require, with or without a require stack', () => { + for (const code of ['ERR_REQUIRE_ESM', 'ERR_REQUIRE_ASYNC_MODULE']) { + const text = describeModuleLoadFailure( + coded(code, "require() of ES Module '/app/esm.mjs' not supported"), + ); + expect(detectModuleLoadFailure(coded(code, 'x'))?.via).toBe('require'); + expect(text).toBeDefined(); + } + }); + + it('does not claim how a module of unknown name was loaded', () => { + const text = describeModuleLoadFailure(coded('ERR_UNKNOWN_FILE_EXTENSION', 'something odd')); + expect(text).toBe('Code: ERR_UNKNOWN_FILE_EXTENSION'); + }); + + it('elides the payload of a data: or blob: specifier and caps a long one', () => { + const data = coded( + 'ERR_MODULE_NOT_FOUND', + "Cannot find module 'data:text/javascript,SECRET' imported from /app/a.mjs", + ); + expect(describeModuleLoadFailure(data)).toContain('Failed module: data:'); + expect(describeModuleLoadFailure(data)).not.toContain('SECRET'); + const long = coded( + 'ERR_MODULE_NOT_FOUND', + `Cannot find module '/${'a'.repeat(1000)}' imported from /app/a.mjs`, + ); + expect(describeModuleLoadFailure(long)?.split('\n')[0]?.length).toBeLessThan(400); + }); + + it('reads a Windows drive path and a UNC path from a syntax-error header', () => { + for (const [header, file] of [ + ['C:\\app\\x.js', 'C:\\app\\x.js'], + ['\\\\server\\share\\x.js', '\\\\server\\share\\x.js'], + ] as const) { + const error = new SyntaxError('Unexpected token'); + error.stack = `${header}:3\nconst = 1;\n ^\n\nSyntaxError: Unexpected token`; + expect(detectModuleLoadFailure(error)?.position).toEqual({ file, line: 3, column: 7 }); + } + }); + + it('survives a throwing requireStack index and an errors getter that changes its answer', () => { + const stack = ['/app/a.cjs']; + Object.defineProperty(stack, '1', { + get() { + throw new Error('hostile'); + }, + }); + stack.length = 2; + const error = coded('MODULE_NOT_FOUND', "Cannot find module './m'"); + Object.assign(error, { requireStack: stack }); + expect(detectModuleLoadFailure(error)?.requireStack).toEqual(['/app/a.cjs']); + + let reads = 0; + const aggregate = new AggregateError([], 'bundle failed'); + Object.defineProperty(aggregate, 'errors', { + get() { + reads += 1; + if (reads > 1) throw new Error('hostile'); + return []; + }, + }); + expect(() => detectModuleLoadFailure(aggregate)).not.toThrow(); + }); +}); + +describe('probed Node message shapes (v26)', () => { + const coded = (code: string, message: string): Error => + Object.assign(new Error(message), { code }); + + it('a CommonJS require of an unexported subpath names the package and does not claim an import', () => { + const failure = detectModuleLoadFailure( + coded( + 'ERR_PACKAGE_PATH_NOT_EXPORTED', + `Package subpath './sub' is not defined by "exports" in /app/node_modules/@s/pkg/package.json`, + ), + ); + expect(failure?.module).toBe('@s/pkg/sub'); + expect(failure?.via).toBeUndefined(); + expect(failure?.importer).toBeUndefined(); + const frames = moduleLoadFrameEnricher( + coded( + 'ERR_PACKAGE_PATH_NOT_EXPORTED', + `Package subpath './sub' is not defined by "exports" in /app/node_modules/@s/pkg/package.json`, + ), + [], + ); + expect(frames[0]?.function).toBe('load()'); + }); + + it('an unexported subpath from a bare path (no node_modules) keeps the subpath', () => { + expect( + detectModuleLoadFailure( + coded( + 'ERR_PACKAGE_PATH_NOT_EXPORTED', + 'Package subpath \'./x\' is not defined by "exports" in /p/package.json', + ), + )?.module, + ).toBe('./x'); + }); + + it('require() of an ES module names the module and its requirer', () => { + const failure = detectModuleLoadFailure( + coded( + 'ERR_REQUIRE_ESM', + 'require() of ES Module /app/esm.mjs from /app/t.cjs not supported.\nInstead change ...', + ), + ); + expect(failure).toMatchObject({ + module: '/app/esm.mjs', + importer: '/app/t.cjs', + via: 'require', + }); + }); + + it('require() of an ESM graph with top-level await names the required module', () => { + const failure = detectModuleLoadFailure( + coded( + 'ERR_REQUIRE_ASYNC_MODULE', + 'require() cannot be used on an ESM graph with top-level await. Use import() instead.\nRequired module: /app/tla.mjs\nRequire stack:\n- /app/t.cjs', + ), + ); + expect(failure).toMatchObject({ module: '/app/tla.mjs', via: 'require' }); + }); + + it('an undefined package import names the specifier and its importer', () => { + const failure = detectModuleLoadFailure( + coded( + 'ERR_PACKAGE_IMPORT_NOT_DEFINED', + 'Package import specifier "#nope" is not defined in package /app/package.json imported from /app/t.cjs', + ), + ); + expect(failure).toMatchObject({ module: '#nope', importer: '/app/t.cjs' }); + // the CommonJS loader raises this too, so `imported from` does not say it was an import() + expect(failure?.via).toBeUndefined(); + }); + + it('the root of a package with no "exports" main names the package, in ESM and CJS messages', () => { + const esm = detectModuleLoadFailure( + coded( + 'ERR_PACKAGE_PATH_NOT_EXPORTED', + 'No "exports" main defined in /app/node_modules/pkg/package.json imported from /app/m.mjs', + ), + ); + expect(esm).toMatchObject({ module: 'pkg', importer: '/app/m.mjs' }); + const cjs = detectModuleLoadFailure( + coded( + 'ERR_PACKAGE_PATH_NOT_EXPORTED', + 'No "exports" main defined in /app/node_modules/pkg/package.json', + ), + ); + expect(cjs?.module).toBe('pkg'); + }); + + it('reads Windows separators in the package path', () => { + const failure = detectModuleLoadFailure( + coded( + 'ERR_PACKAGE_PATH_NOT_EXPORTED', + 'Package subpath \'./sub\' is not defined by "exports" in C:\\app\\node_modules\\@s\\pkg\\package.json', + ), + ); + expect(failure?.module).toBe('@s/pkg/sub'); + }); + + it('require() of an ES module in a path with spaces still names both paths', () => { + const failure = detectModuleLoadFailure( + coded( + 'ERR_REQUIRE_ESM', + 'require() of ES Module /my app/x.mjs from /my app/z.cjs not supported.\nInstead ...', + ), + ); + expect(failure).toMatchObject({ module: '/my app/x.mjs', importer: '/my app/z.cjs' }); + }); +}); diff --git a/packages/node/src/module-load-failure.ts b/packages/node/src/module-load-failure.ts new file mode 100644 index 00000000..dc59ab99 --- /dev/null +++ b/packages/node/src/module-load-failure.ts @@ -0,0 +1,309 @@ +import { fileURLToPath } from 'node:url'; +import type { FrameEnricher, StackFrame } from '@bugsee/core'; +import { parseLocation } from '@bugsee/core'; + +// Context for an error raised while LOADING a module, so the report names what failed instead of "Error at node:internal/...". +// +// What each runtime hands over (probed on node 26 and bun 1.4): +// - Node, ESM and CJS resolution failures (`ERR_MODULE_NOT_FOUND`, `MODULE_NOT_FOUND`, `ERR_UNSUPPORTED_DIR_IMPORT`, +// `ERR_PACKAGE_PATH_NOT_EXPORTED`, ...): a stack made of loader internals. The module and its importer live in the message, plus +// `url` (ESM) or `requireStack` (CJS) as properties. +// - Node, a SyntaxError in an imported module: loader internals only. The file and line are in the stack HEADER, above the error +// line (`file:///app/x.mjs:1`, the source line, a caret line), where no frame parser looks. +// - Bun, resolution failures: a `ResolveMessage` with NO stack at all, but `specifier`, `referrer`, `importKind` and `code` as +// properties. A syntax error is an `AggregateError` with no stack whose `errors[]` carry `position.file/line/column`. +// Best-effort and pure reads: every property read goes through `prop`, which contains a throwing getter, and nothing is invented +// that the error does not say. + +/** The frame function of a module that failed to resolve or load. */ +export const IMPORT_FRAME_FUNCTION = 'import()'; +/** The frame function when the failure does not say whether it was an `import()` or a `require()`. */ +export const LOAD_FRAME_FUNCTION = 'load()'; +/** The frame function when the failing load was a `require()` (CommonJS). */ +export const REQUIRE_FRAME_FUNCTION = 'require()'; + +const FAILED_RESOLUTION_CODES = new Set([ + 'ERR_MODULE_NOT_FOUND', + 'MODULE_NOT_FOUND', + 'ERR_UNSUPPORTED_DIR_IMPORT', + 'ERR_PACKAGE_PATH_NOT_EXPORTED', + 'ERR_PACKAGE_IMPORT_NOT_DEFINED', + 'ERR_UNKNOWN_FILE_EXTENSION', + 'ERR_REQUIRE_ESM', + 'ERR_REQUIRE_ASYNC_MODULE', +]); + +// The message shapes Node uses. Each is anchored on a fixed prefix and uses no nested or lazy repetition, so none can backtrack +// badly on a hostile message. +// `Cannot find module '/abs/x.mjs' imported from /abs/y.mjs`, `Cannot find package 'p' imported from ...`. +const NOT_FOUND = /Cannot find (?:module|package) '([^']+)'/; +// `Directory import '/abs/dir' is not supported resolving ES modules imported from /abs/y.mjs` +const DIR_IMPORT = /^Directory import '([^']+)'/; +// `Package subpath './sub' is not defined by "exports" in /abs/node_modules/pkg/package.json imported from /abs/y.mjs` +const NOT_EXPORTED = /^Package subpath '([^']+)'/; +// The package a `package.json` path in the message belongs to: `/app/node_modules/@scope/pkg/package.json` -> `@scope/pkg`. +// Either separator: on Windows the path is `C:\app\node_modules\@scope\pkg\package.json`. +const PACKAGE_OF_JSON = /node_modules[\\/]((?:@[^\\/\n]+[\\/])?[^\\/\n]+)[\\/]package\.json/; +// `No \"exports\" main defined in /app/node_modules/pkg/package.json [imported from ...]`: the package root, with no subpath. +const NO_EXPORTS_MAIN = /^No "exports" main defined in /; +// `Package import specifier "#x" is not defined in package /app/package.json imported from /app/y.mjs` +const IMPORT_NOT_DEFINED = /^Package import specifier "([^"]+)"/; +// `require() of ES Module /app/esm.mjs from /app/y.js not supported.` +// Lazy but anchored and bounded by `[^\n]`, so a path with a space still matches and nothing backtracks badly. +const REQUIRE_ESM = /^require\(\) of ES Module ([^\n]+?) from ([^\n]+?) not supported/; +// `require() cannot be used on an ESM graph with top-level await. ...\nRequired module: /app/tla.mjs` +const REQUIRED_MODULE = /^Required module: ([^\n]+)/m; +// `Unknown file extension ".xyz" for /abs/component.xyz` +const UNKNOWN_EXTENSION = /^Unknown file extension "[^"]*" for ([^\n]+)/; +// the importer, wherever the message names it +const IMPORTED_FROM = / imported from ([^\n]+)/; +// Longest specifier or path shipped in a frame or description line: a `data:` URL can be kilobytes of inline source. +const MAX_SPECIFIER = 300; +// Bun's stackless SyntaxError for a missing named export: `Export named 'x' not found in module '/abs/y.mjs'.` +const BUN_MISSING_EXPORT = /^Export named '([^']+)' not found in module '([^']+)'\.?$/; +// Node's SyntaxError header: `:` / the source line / the caret line. +// The file is a POSIX path, a `file://` URL, a Windows drive path (`C:\app\x.js`) or a UNC path (`\\server\share\x.js`). +const SYNTAX_HEADER = /^((?:file:\/\/|[A-Za-z]:[\\/]|\\\\|\/)[^\n]*?):(\d+)\n[^\n]*\n( *)\^/; + +export interface ModuleLoadFailure { + /** What failed: a SyntaxError found in a module's source, or a module that could not be resolved/loaded. */ + kind: 'resolution' | 'syntax'; + /** The module that could not be found or loaded (file path, or the bare specifier). */ + module?: string; + /** The module that asked for it. */ + importer?: string; + /** Node's / Bun's error code (`ERR_MODULE_NOT_FOUND`). */ + code?: string; + /** `import` or `require`: how the load was requested; undefined when nothing in the error says. */ + via?: 'import' | 'require'; + /** CommonJS `require()` chain, innermost first. */ + requireStack: string[]; + /** A named export the module does not provide (`import { x } from './m'`). */ + missingExport?: string; + /** The source position of a syntax error. */ + position?: { file: string; line: number; column?: number }; +} + +function prop(value: unknown, key: string): unknown { + if (typeof value !== 'object' || value === null) return undefined; + try { + return (value as Record)[key]; + } catch { + return undefined; + } +} + +function str(value: unknown, key: string): string | undefined { + const v = prop(value, key); + return typeof v === 'string' && v !== '' ? v : undefined; +} + +/** `file:///a/b.mjs` -> `/a/b.mjs`; anything else unchanged. */ +function toPath(location: string): string { + if (!location.startsWith('file://')) return location; + try { + return fileURLToPath(location); + } catch { + return location.slice('file://'.length); + } +} + +/** The array's strings, each element read through `prop` so a throwing index getter costs that element, not the report. */ +/** A package name with the platform separator normalized to `/`. */ +function slashed(name: string): string { + return name.replace(/\\/g, '/'); +} + +function stringList(value: unknown): string[] { + if (!Array.isArray(value)) return []; + const out: string[] = []; + for (let i = 0; i < value.length; i++) { + const entry = prop(value, String(i)); + if (typeof entry === 'string') out.push(entry); + } + return out; +} + +function objectList(value: unknown): unknown[] { + if (!Array.isArray(value)) return []; + const out: unknown[] = []; + for (let i = 0; i < value.length; i++) out.push(prop(value, String(i))); + return out; +} + +function syntaxPosition(value: unknown): ModuleLoadFailure['position'] | undefined { + // Bun: the build error itself, or the first of an AggregateError's `errors`. + const candidates = [value, ...objectList(prop(value, 'errors'))]; + for (const candidate of candidates) { + const position = prop(candidate, 'position'); + const file = str(position, 'file'); + const line = prop(position, 'line'); + if (file !== undefined && typeof line === 'number') { + const column = prop(position, 'column'); + return { file, line, ...(typeof column === 'number' ? { column } : {}) }; + } + } + // Node: the header of the stack. + const stack = str(value, 'stack'); + const header = stack === undefined ? null : SYNTAX_HEADER.exec(stack); + if (header !== null) { + return { + file: toPath(header[1] as string), + line: Number(header[2]), + column: (header[3] as string).length + 1, + }; + } + return undefined; +} + +/** Describe a module-load error, or undefined when `value` is not one. */ +export function detectModuleLoadFailure(value: unknown): ModuleLoadFailure | undefined { + if (typeof value !== 'object' || value === null) return undefined; + const name = str(value, 'name'); + const code = str(value, 'code'); + const message = str(value, 'message') ?? ''; + + if (name === 'SyntaxError' || name === 'AggregateError' || name === 'BuildMessage') { + const position = syntaxPosition(value); + const missing = BUN_MISSING_EXPORT.exec(message); + if (position === undefined && missing !== null) { + return { + kind: 'resolution', + via: 'import', + requireStack: [], + module: missing[2] as string, + missingExport: missing[1] as string, + }; + } + // An AggregateError that is not a build error carries no position, so it is not ours. + return position === undefined + ? undefined + : { kind: 'syntax', via: 'import', requireStack: [], position }; + } + + const isBunResolve = name === 'ResolveMessage'; + if (!isBunResolve && (code === undefined || !FAILED_RESOLUTION_CODES.has(code))) return undefined; + + const requireStack = stringList(prop(value, 'requireStack')); + const url = str(value, 'url'); + const requireEsm = REQUIRE_ESM.exec(message); + const exported = NOT_EXPORTED.exec(message); + const exportedIn = exported === null ? null : PACKAGE_OF_JSON.exec(message); + const noMain = NO_EXPORTS_MAIN.test(message) ? PACKAGE_OF_JSON.exec(message) : null; + let exportedModule: string | undefined; + if (exported !== null) { + const subpath = exported[1] as string; + exportedModule = + exportedIn === null + ? subpath + : `${slashed(exportedIn[1] as string)}/${subpath.replace(/^\.\//, '')}`; + } else if (noMain !== null) { + exportedModule = slashed(noMain[1] as string); + } + const module = + str(value, 'specifier') ?? + (url !== undefined ? toPath(url) : undefined) ?? + exportedModule ?? + (NOT_FOUND.exec(message) ?? + DIR_IMPORT.exec(message) ?? + IMPORT_NOT_DEFINED.exec(message) ?? + UNKNOWN_EXTENSION.exec(message) ?? + REQUIRED_MODULE.exec(message) ?? + requireEsm)?.[1]; + const importedFrom = IMPORTED_FROM.exec(message)?.[1]; + const importer = str(value, 'referrer') ?? importedFrom ?? requireEsm?.[2] ?? requireStack[0]; + const importKind = str(value, 'importKind'); + // Said only on evidence. `require()` of an ES module raises these two codes (no require stack on them); an ESM loader error + // carries a `url`, an `imported from` clause or Bun's `importKind`. A CommonJS `require('pkg/sub')` blocked by `exports` has + // none of these, so it stays unknown. + const viaRequire = + requireStack.length > 0 || + importKind === 'require-call' || + code === 'ERR_REQUIRE_ESM' || + code === 'ERR_REQUIRE_ASYNC_MODULE'; + // `imported from` does not settle it for the two errors the CommonJS loader shares with the ESM resolver. + const sharedResolver = + code === 'ERR_PACKAGE_IMPORT_NOT_DEFINED' || code === 'ERR_PACKAGE_PATH_NOT_EXPORTED'; + const viaImport = + importKind !== undefined || + url !== undefined || + (importedFrom !== undefined && !sharedResolver) || + isBunResolve; + const via = viaRequire ? 'require' : viaImport ? 'import' : undefined; + return { + kind: 'resolution', + ...(via !== undefined ? { via } : {}), + requireStack, + ...(module !== undefined ? { module } : {}), + ...(importer !== undefined ? { importer } : {}), + ...(code !== undefined ? { code } : {}), + }; +} + +function scrub(path: string): string { + // A `data:` / `blob:` specifier IS its payload (inline source, possibly a secret): keep the scheme, drop the rest. + const inline = /^(data|blob):/i.exec(path); + if (inline !== null) return `${(inline[1] as string).toLowerCase()}:`; + const file = parseLocation(path).file ?? path; + return file.length > MAX_SPECIFIER ? `${file.slice(0, MAX_SPECIFIER)}...` : file; +} + +/** The frame that stands for the failed load, placed at the top of the stack so the report names it. */ +function failureFrame(failure: ModuleLoadFailure): StackFrame | undefined { + const position = failure.position; + if (position !== undefined) { + const frame = parseLocation(position.file); + frame.line = position.line; + if (position.column !== undefined) frame.column = position.column; + return frame; + } + if (failure.module === undefined) return undefined; + return { + function: + failure.via === 'require' + ? REQUIRE_FRAME_FUNCTION + : failure.via === 'import' + ? IMPORT_FRAME_FUNCTION + : LOAD_FRAME_FUNCTION, + file: scrub(failure.module), + }; +} + +/** + * A frame enricher that puts the failed module (or the syntax error's position) FIRST. The frames the runtime did give are kept + * after it: they are loader internals, but they are the only stack there is, and a frame that is already first is not repeated. + */ +export const moduleLoadFrameEnricher: FrameEnricher = (error, frames) => { + const failure = detectModuleLoadFailure(error); + const added = failure === undefined ? undefined : failureFrame(failure); + if (added === undefined) return frames; + const first = frames[0]; + if (first !== undefined && first.file === added.file && first.line === added.line) return frames; + return [added, ...frames]; +}; + +/** Description lines for a module-load error, or undefined when `value` is not one. */ +export function describeModuleLoadFailure(value: unknown): string | undefined { + const failure = detectModuleLoadFailure(value); + if (failure === undefined) return undefined; + const lines: string[] = []; + const position = failure.position; + if (position !== undefined) { + const at = `${scrub(position.file)}:${position.line}${position.column !== undefined ? `:${position.column}` : ''}`; + lines.push(`Syntax error in module: ${at}`); + } else { + if (failure.module !== undefined) lines.push(`Failed module: ${scrub(failure.module)}`); + if (failure.importer !== undefined) lines.push(`Imported from: ${scrub(failure.importer)}`); + // Only said when the load is known: with no module and no stack to go on, a default would be a guess. + if (failure.via !== undefined) { + lines.push(`Loaded via: ${failure.via === 'require' ? 'require()' : 'import'}`); + } + if (failure.missingExport !== undefined) lines.push(`Missing export: ${failure.missingExport}`); + if (failure.code !== undefined) lines.push(`Code: ${failure.code}`); + if (failure.requireStack.length > 0) { + lines.push('Require stack:'); + for (const entry of failure.requireStack) lines.push(` ${scrub(entry)}`); + } + } + return lines.join('\n'); +}