diff --git a/pkgs/mcpx/internal/codegen/emit.go b/pkgs/mcpx/internal/codegen/emit.go index 38c3be0cc5..ca2dedbd1d 100644 --- a/pkgs/mcpx/internal/codegen/emit.go +++ b/pkgs/mcpx/internal/codegen/emit.go @@ -900,6 +900,69 @@ export interface Frame { native?: boolean; } +/** + * The best name a CallSite can give its frame. + * + * getFunctionName is the primary source, but it is not the only one: a + * method frame may only answer to getMethodName, and some shims populate + * getFunction (whose .name is the same string) while leaving both name + * getters empty. Trying all three costs nothing on runtimes where the + * first already answers. + */ +function frameName(s: any): string | undefined { + const fn = s.getFunctionName?.(); + if (fn) return fn; + const mn = s.getMethodName?.(); + if (mn) return mn; + const f = s.getFunction?.(); + if (f && typeof f.name === "string" && f.name) return f.name; + return undefined; +} + +/** + * Parse a runtime's default stack string into frames. + * + * Bun's V8 CallSite shim is lossy: for frames the string form names, the + * CallSite getters can all come back empty, and captureStackTrace may + * collapse the stack to a single unnamed frame (verified on Bun 1.4.2). + * The string is strictly worse where CallSites work -- it carries no + * async/native/type flags -- so this is a fallback for the case where + * the CallSite path produced no names at all, never a replacement. + * Handles both "at name (file:line:col)" and "at file:line:col" lines. + */ +function parseStackString(stack: unknown): Frame[] { + if (typeof stack !== "string") return []; + const frames: Frame[] = []; + for (const raw of stack.split("\n")) { + const line = raw.trim(); + if (!line.startsWith("at ")) continue; + const rest = line.slice(3); + const f: Frame = {}; + let loc = rest; + const open = rest.lastIndexOf(" ("); + if (open > 0 && rest.endsWith(")")) { + const name = rest.slice(0, open); + if (name) f.function = name; + loc = rest.slice(open + 2, -1); + } + const m = /^(.*):(\d+):(\d+)$/.exec(loc); + if (m) { + f.file = m[1].replace(/^file:\/\//, ""); + f.line = Number(m[2]); + f.column = Number(m[3]); + } else if (loc) { + f.file = loc; + } + frames.push(f); + } + return frames; +} + +/** True when no frame carries a function name. */ +function nameless(frames: Frame[]): boolean { + return frames.every((f) => !f.function); +} + /** * Capture a stack as structured frames. * @@ -925,10 +988,10 @@ export function captureFrames(skip = 0, limit = 32): Frame[] { if (typeof line === "number") f.line = line; const col = s.getColumnNumber?.(); if (typeof col === "number") f.column = col; - const fn = s.getFunctionName?.(); + const fn = frameName(s); if (fn) f.function = fn; const tn = s.getTypeName?.(); - if (tn) f.type = tn; + if (tn && tn !== "undefined") f.type = tn; if (s.isAsync?.()) f.async = true; if (s.isNative?.()) f.native = true; return f; @@ -936,7 +999,24 @@ export function captureFrames(skip = 0, limit = 32): Frame[] { const holder: any = {}; E.captureStackTrace?.(holder, captureFrames); const frames: Frame[] = holder.stack ?? (new Error() as any).stack ?? []; - return Array.isArray(frames) ? frames.slice(skip, skip + limit) : []; + if (!Array.isArray(frames)) return []; + const sliced = frames.slice(skip, skip + limit); + // Under Bun the CallSite shim can return frames with no names at all + // (or a single collapsed frame) for a stack the default string form + // names correctly. When that happens, read the string form of a + // fresh error -- captured with the caller's own prepareStackTrace + // restored, so it is the runtime's default rendering -- and parse + // it. The first parsed frame is captureFrames itself, which the + // CallSite path excludes via captureStackTrace's second argument. + if (typeof (globalThis as any).Bun !== "undefined" && nameless(sliced)) { + E.prepareStackTrace = previous; + const parsed = parseStackString((new Error() as any).stack); + if (parsed.length > 1) { + const named = parsed.slice(1).slice(skip, skip + limit); + if (!nameless(named)) return named; + } + } + return sliced; } catch { return []; } finally { @@ -957,14 +1037,26 @@ export function errorFrames(err: Error, limit = 32): Frame[] { if (file) f.file = String(file).replace(/^file:\/\//, ""); const line = s.getLineNumber?.(); if (typeof line === "number") f.line = line; - const fn = s.getFunctionName?.(); + const fn = frameName(s); if (fn) f.function = fn; if (s.isAsync?.()) f.async = true; return f; }); // Reading .stack re-runs prepareStackTrace against the captured sites. const frames = (err as any).stack; - return Array.isArray(frames) ? frames.slice(0, limit) : []; + if (!Array.isArray(frames)) return []; + const sliced = frames.slice(0, limit); + // Same Bun shim gap as captureFrames: if the CallSite form names + // nothing, the error's own default string form may still name the + // throwing function. It is only readable if .stack has not already + // been memoised in CallSite form; when it has, keep the CallSite + // frames rather than failing. + if (typeof (globalThis as any).Bun !== "undefined" && nameless(sliced)) { + E.prepareStackTrace = previous; + const parsed = parseStackString((err as any).stack); + if (parsed.length && !nameless(parsed)) return parsed.slice(0, limit); + } + return sliced; } catch { return []; } finally { @@ -1193,13 +1285,18 @@ export function captureConsole(): void { // free to be the human form. const g = globalThis as any; const nodeInspect = builtin("node:util")?.inspect; + // Bun must be checked before Deno: Bun exposes a Deno compatibility + // global, so under Bun the Deno branch would otherwise win and values + // would render in Deno's format instead of the runtime's own. Bun's + // console renders with Bun.inspect at depth 2 (deeper values collapse + // to [Object ...]), so match both the function and the depth. const native: ((v: unknown) => string) | undefined = env("MCPX_RUNTIME") === "node" && typeof nodeInspect === "function" ? (v) => nodeInspect(v) + : typeof g.Bun?.inspect === "function" + ? (v) => g.Bun.inspect(v, { depth: 2 }) : typeof g.Deno?.inspect === "function" ? (v) => g.Deno.inspect(v, { colors: false, depth: 4 }) - : typeof g.Bun?.inspect === "function" - ? (v) => g.Bun.inspect(v) : typeof nodeInspect === "function" ? (v) => nodeInspect(v) : undefined; diff --git a/pkgs/mcpx/internal/e2e/e2e_test.go b/pkgs/mcpx/internal/e2e/e2e_test.go index a16b145d48..92aa5439ae 100644 --- a/pkgs/mcpx/internal/e2e/e2e_test.go +++ b/pkgs/mcpx/internal/e2e/e2e_test.go @@ -1666,6 +1666,40 @@ func TestErrorsCarryStructuredFramesAndAString(t *testing.T) { } } +// Bun fidelity for the emitted shim (#8350). Two gaps closed in emit.go: +// captureConsole picked the Deno inspect branch under Bun (Bun exposes a +// Deno compatibility global), rendering values in Deno's format instead of +// Bun's own; and captureFrames trusted Bun's V8 CallSite shim, which can +// return a single unnamed frame for a stack Bun's default stack string +// names correctly. The caller below is deliberately not a one-liner: +// JavaScriptCore inlines trivial wrappers, and a frame that was inlined +// away exists in no stack representation on any runtime -- that is the +// documented Bun exception, and it is why TestCaptureFramesIsAvailableTo +// Scripts keeps its one-liner assertion on the default runtime only. +func TestBunCaptureFramesAndConsoleMatchTheRuntime(t *testing.T) { + testsupport.RequireBinary(t, "bun") + e := newEnv(t, oneServer) + out := e.run("exec", "--runtime", "bun", "--format", "bare", + `function worker(n) { let acc = 0; for (let i = 0; i < n; i++) acc += i * 3; + const f = captureFrames(0, 4); return { acc, top: f[0]?.function }; } + console.log(JSON.stringify(worker(5)));`) + if !strings.Contains(out, `"top":"worker"`) { + t.Errorf("captureFrames should name its caller under Bun:\n%s", out) + } + // Bun's console renders an object multi-line with a trailing comma and + // collapses values deeper than depth 2 to [Object ...]; the captured + // record must read the same way. + out = e.run("exec", "--runtime", "bun", "--format", "compact", + `console.info("shaped", { a: 1, b: [1, 2] }); + console.info("obj", { nested: { deep: [1, { x: 2 }] } });`) + if !strings.Contains(out, "b: [ 1, 2 ],") { + t.Errorf("console records under Bun should use Bun's own formatting:\n%s", out) + } + if !strings.Contains(out, "[Object ...]") { + t.Errorf("console records under Bun should collapse past depth 2 like Bun's console:\n%s", out) + } +} + func TestConsoleTraceCapturesFrames(t *testing.T) { e := newEnv(t, oneServer) out := e.run("exec", "--format", "json", "--log-level", "debug",