diff --git a/src/runtime/bake/dev_server/source_map_store.rs b/src/runtime/bake/dev_server/source_map_store.rs index 4eb78f25b9a3..7e4d653d3e73 100644 --- a/src/runtime/bake/dev_server/source_map_store.rs +++ b/src/runtime/bake/dev_server/source_map_store.rs @@ -645,7 +645,8 @@ impl SourceMapStore { match source_map::mapping::parse( &vlq_bytes, None, - i32::try_from(entry.paths.len()).expect("int cast"), + // Source 0 is the HMR runtime, so `paths[i]` is source `i + 1`. + i32::try_from(entry.paths.len() + 1).expect("int cast"), Default::default(), ) { Err(fail) => { diff --git a/src/sourcemap/Mapping.rs b/src/sourcemap/Mapping.rs index 3fc525d34b2a..88c3d771d895 100644 --- a/src/sourcemap/Mapping.rs +++ b/src/sourcemap/Mapping.rs @@ -383,10 +383,6 @@ impl Lookup { } } - if index >= source_map.external_source_names.len() { - return None; - } - let name: &[u8] = &source_map.external_source_names[index]; let mut buf = bun_paths::path_buffer_pool::get(); diff --git a/src/sourcemap/lib.rs b/src/sourcemap/lib.rs index 5ba27ee24a31..8ba227ff74eb 100644 --- a/src/sourcemap/lib.rs +++ b/src/sourcemap/lib.rs @@ -951,7 +951,7 @@ pub(crate) fn parse_json(source: &[u8], hint: ParseUrlResultHint) -> crate::Resu let mut map_data = match mapping::parse( mappings_vlq, None, - i32::MAX, + i32::try_from(sources_paths.items().len()).unwrap_or(i32::MAX), mapping::ParseOptions { allow_names: matches!( hint, diff --git a/test/bake/dev/html.test.ts b/test/bake/dev/html.test.ts index 1166efda57a6..222b3411303f 100644 --- a/test/bake/dev/html.test.ts +++ b/test/bake/dev/html.test.ts @@ -1,6 +1,7 @@ // HTML tests are tests relating to HTML files themselves. import { expect } from "bun:test"; -import { devTest, emptyHtmlFile } from "../bake-harness"; +import { basename } from "node:path"; +import { Dev, devTest, emptyHtmlFile } from "../bake-harness"; devTest("html file is watched", { files: { @@ -463,6 +464,134 @@ devTest("error report endpoint blanks stray non-text bytes in reported frames", await dev.fetch("/").expect.toInclude("

Frame Bytes

"); }, }); + +// Posts frames to /_bun/report_error and returns the frames of the reply. Both use: i32 line, i32 column, +// string32 function name, string32 file name. The request starts with string32 error name, string32 message, +// string32 browser url and a u32 frame count. The reply starts with a u32 frame count. +async function reportErrorFrames( + dev: Dev, + frames: { line: number; column: number; functionName: string; file: string }[], +) { + function i32(n: number) { + const b = Buffer.alloc(4); + b.writeInt32LE(n, 0); + return b; + } + function str32(s: string) { + const bytes = Buffer.from(s, "utf8"); + return Buffer.concat([i32(bytes.length), bytes]); + } + const body = Buffer.concat([ + str32("Error"), + str32("remap-message"), + str32(dev.baseUrl + "/"), + i32(frames.length), + ...frames.flatMap(frame => [i32(frame.line), i32(frame.column), str32(frame.functionName), str32(frame.file)]), + ]); + const res = await dev.fetch("/_bun/report_error", { method: "POST", body }); + const reply = Buffer.from(await res.arrayBuffer()); + expect(res.status).toBe(200); + + let at = 0; + const readInt = () => ((at += 4), reply.readInt32LE(at - 4)); + const readString = () => { + const length = readInt(); + return reply.toString("utf8", at, (at += length)); + }; + return Array.from({ length: readInt() }, () => ({ + line: readInt(), + column: readInt(), + functionName: readString(), + // Relative to the project root, or absolute on Windows. + file: basename(readString()), + })); +} + +// The one-based line and column of `marker` in `script`. +function positionOf(script: string, marker: string) { + const offset = script.indexOf(marker); + expect(offset).toBeGreaterThan(0); + const lineStart = script.lastIndexOf("\n", offset) + 1; + return { line: script.slice(0, lineStart).split("\n").length, column: offset - lineStart + 1 }; +} + +devTest("error report endpoint remaps a frame in every file of the client bundle", { + files: { + "index.html": emptyHtmlFile({ + scripts: ["/index.ts"], + body: "

Remap

", + }), + "index.ts": ` + import { other } from "./other"; + console.log("index-frame-marker", other()); + `, + "other.ts": ` + // The marker is on line 3. + export function other() { + return "other-frame-marker"; + } + `, + }, + async test(dev) { + const page = await dev.fetch("/").text(); + const [scriptPath] = page.match(/\/_bun\/client\/index-[0-9a-f]{16}\.js/) ?? []; + const script = await dev.fetch(scriptPath).text(); + const file = dev.baseUrl + scriptPath; + + const frames = await reportErrorFrames(dev, [ + { ...positionOf(script, "index-frame-marker"), functionName: "inIndex", file }, + { ...positionOf(script, "other-frame-marker"), functionName: "inOther", file }, + ]); + expect(frames).toEqual([ + { line: 2, column: 'console.log("'.length, functionName: "inIndex", file: "index.ts" }, + { line: 3, column: ' return "'.length, functionName: "inOther", file: "other.ts" }, + ]); + }, +}); + +devTest("error report endpoint remaps a frame in a hot update chunk", { + files: { + "index.html": emptyHtmlFile({ + scripts: ["/index.ts"], + }), + "index.ts": ` + import { other } from "./other"; + console.log("index " + other()); + import.meta.hot.accept(); + `, + "other.ts": ` + export function other() { + return "first"; + } + import.meta.hot.accept(); + `, + }, + async test(dev) { + await using c = await dev.client("/", { storeHotChunks: true }); + await dev.write( + "other.ts", + ` + console.log("updated"); + export function other() { + return "chunk-frame-marker"; + } + import.meta.hot.accept(); + `, + ); + const chunk = await c.getMostRecentHmrChunk(); + const [, id] = chunk.match(/\n\/\/# sourceMappingURL=\S*?([0-9a-f]{16})\.js\.map/) ?? []; + + const frames = await reportErrorFrames(dev, [ + { + ...positionOf(chunk, "chunk-frame-marker"), + functionName: "inChunk", + file: `${dev.baseUrl}/_bun/client/hmr-${id}.js`, + }, + ]); + expect(frames).toEqual([{ line: 3, column: ' return "'.length, functionName: "inChunk", file: "other.ts" }]); + await c.expectMessage("index first", "updated"); + }, +}); devTest("client script route returns 404 when the route bundle index is out of range", { files: { "index.html": emptyHtmlFile({ scripts: ["/script.ts"] }), diff --git a/test/js/bun/sourcemap/negative-vlq-mapping.test.ts b/test/js/bun/sourcemap/negative-vlq-mapping.test.ts index 746ff863712c..675856613245 100644 --- a/test/js/bun/sourcemap/negative-vlq-mapping.test.ts +++ b/test/js/bun/sourcemap/negative-vlq-mapping.test.ts @@ -169,3 +169,121 @@ describe.concurrent("sourcemap: negative VLQ delta in mappings is rejected, not expect(exitCode).toBe(0); }); }); + +// A segment that names a source the map does not have. ";;EAIE" maps generated +// 3:3 to original 5:3 of source 0. ";;ECIE" maps it to source 1. +describe.concurrent("sourcemap: a source index past `sources` is rejected", () => { + const map = { version: 3, sources: ["original.ts"], sourcesContent: [null], names: [], mappings: ";;ECIE" }; + const maps = { + "last-source": { ...map, sources: ["other.ts", "original.ts"], sourcesContent: [null, null] }, + "past-end": map, + "no-sources": { ...map, sources: [], sourcesContent: [], mappings: ";;EAIE" }, + // Long enough for the SIMD decoder, which leaves the last segment of any input to the scalar loop. + "past-end-at-tail": { ...map, mappings: ";;EAIE" + Buffer.alloc(5 * 46, ",CAAC").toString() + ",CCAA" }, + // ",CCAA" names source 1 and ",CDAA" goes back to source 0. The SIMD decoder has to refuse it mid-input. + "past-end-mid-input": { + ...map, + mappings: + ";;EAIE" + Buffer.alloc(5 * 20, ",CAAC").toString() + ",CCAA,CDAA" + Buffer.alloc(5 * 20, ",CAAC").toString(), + }, + // The same with two-character VLQs, which take another path in the SIMD decoder. + "past-end-mid-input-wide": { + ...map, + mappings: + ";;EAIE" + + Buffer.alloc(7 * 20, ",gBAAgB").toString() + + ",CCAA,CDAA" + + Buffer.alloc(7 * 20, ",gBAAgB").toString(), + }, + }; + const throwsOnLine3 = `// @bun\nexport function t() {\n throw new Error("SI");\n}\n`; + const files: Record = { + "main.js": ` + for (const file of process.argv.slice(2)) { + const { t } = await import("./" + file); + for (let i = 0; i < 2; i++) { + try { + t(); + } catch (e) { + console.log(file + ": " + e.stack.split("\\n")[1].trim()); + } + } + } + `, + }; + for (const [name, map] of Object.entries(maps)) { + const json = JSON.stringify(map); + files[`${name}.js`] = throwsOnLine3 + `//# sourceMappingURL=${name}.js.map\n`; + files[`${name}.js.map`] = json; + files[`${name}.inline.js`] = throwsOnLine3 + `//# sourceMappingURL=data:application/json;base64,${btoa(json)}\n`; + } + const remapped = ["last-source.js", "last-source.inline.js"]; + const refused = Object.keys(maps) + .filter(name => name !== "last-source") + .flatMap(name => [`${name}.js`, `${name}.inline.js`]); + + for (const [decoder, env] of [ + ["SIMD", {}], + ["scalar", { BUN_FEATURE_FLAG_DISABLE_SIMD_SOURCEMAP: "1" }], + ] as const) { + test(`${decoder} decoder: one warning for each file, and its frames keep their built position`, async () => { + using dir = tempDir("source-index-past-end", files); + await using proc = Bun.spawn({ + cmd: [bunExe(), "main.js", ...remapped, ...refused], + env: { ...bunEnv, ...env }, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + const clean = (text: string) => text.replaceAll(String(dir), "").replaceAll("\\", "/"); + const twice = (line: string) => line + line; + expect({ stdout: clean(stdout), stderr: clean(stderr) }).toEqual({ + stdout: + remapped.map(file => twice(`${file}: at t (/original.ts:5:3)\n`)).join("") + + refused.map(file => twice(`${file}: at t (/${file}:3:18)\n`)).join(""), + stderr: refused + .map(file => `warn: Could not decode sourcemap in '/${file}': InvalidSourceIndexValue\n`) + .join(""), + }); + expect(exitCode).toBe(0); + }); + } + + test("a throw in the last source of a `bun build --sourcemap=external` bundle is remapped", async () => { + using dir = tempDir("source-index-last-of-bundle", { + "first.ts": `export function first() {}\n`, + "second.ts": `export function second() {}\n`, + "entry.ts": + `import { first } from "./first";\n` + + `import { second } from "./second";\n` + + `first();\n` + + `second();\n` + + `function last() {\n` + + ` throw new Error("SI");\n` + + `}\n` + + `last();\n`, + }); + const build = await Bun.build({ + entrypoints: [join(String(dir), "entry.ts")], + outdir: join(String(dir), "out"), + target: "bun", + sourcemap: "external", + }); + expect(build.success).toBe(true); + const { sources } = await Bun.file(join(String(dir), "out", "entry.js.map")).json(); + expect(sources).toEqual(["../first.ts", "../second.ts", "../entry.ts"]); + + await using proc = Bun.spawn({ + cmd: [bunExe(), join("out", "entry.js")], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toContain(`at last (${join(String(dir), "entry.ts")}:6:9)`); + expect(stdout).toBe(""); + expect(exitCode).toBe(1); + }); +});