Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 0 additions & 15 deletions src/runtime/webcore/Blob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2723,15 +2723,6 @@ impl BlobExt for Blob {
// SAFETY: `raw_bytes` is valid for reads for the duration of this call
// (either a leaked Box for `Temporary` or a store-backed view otherwise).
let (bom, buf) = strings::BOM::detect_and_split(unsafe { &*raw_bytes });
if buf.is_empty() {
if LIFETIME == Lifetime::Temporary {
// SAFETY: `Temporary` ⇒ caller passed a leaked `Box<[u8]>`; reclaim it.
unsafe { drop(bun_core::heap::take(raw_bytes)) };
}
return Err(global.throw_value(
global.create_syntax_error_instance(format_args!("Unexpected end of JSON input")),
));
}

if bom == Some(strings::BOM::Utf16Le) {
// Reinterpret as u16: drop a trailing odd byte.
Expand Down Expand Up @@ -6342,9 +6333,6 @@ impl Any {
match self {
Any::Blob(b) => b.to_json(global, lifetime),
Any::InternalBlob(ib) => {
if ib.bytes.is_empty() {
return Ok(JSValue::NULL);
}
let str = ib.to_json(global);
// the GC will collect the string
*self = Any::Blob(Blob::default());
Expand All @@ -6354,9 +6342,6 @@ impl Any {
let str =
BunString::adopt_wtf_impl(core::mem::replace(impl_, core::ptr::null_mut()));
*self = Any::Blob(Blob::default());
if str.length() == 0 {
return Ok(JSValue::NULL);
}
str.to_js_by_parse_json(global)
}
}
Expand Down
2 changes: 1 addition & 1 deletion test/js/bun/util/bun-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ test("Bun.file().json() with UTF-8 BOM does not free an interior pointer", async
expect(JSON.parse(stdout)).toEqual({
ascii: { a: 1, b: "two" },
utf8: { s: "wörld" },
emptyErr: "Unexpected end of JSON input",
emptyErr: "JSON Parse error: Unexpected EOF",
});
expect(exitCode).toBe(0);
});
71 changes: 64 additions & 7 deletions test/js/web/fetch/body.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -929,13 +929,10 @@ for (const { body, fn } of bodyTypes) {
for (const actual of invalidTests) {
test(actual || "<empty>", async () => {
expect(async () => await fn(actual).json()).toThrow(SyntaxError);
// An empty body is rejected before the parser runs, with its own message.
if (actual !== "") {
const error = await fn(actual)
.json()
.catch(error => error);
expect(error.message).toBe(jsonParseError(actual).message);
}
const error = await fn(actual)
.json()
.catch(error => error);
expect(error.message).toBe(jsonParseError(actual).message);
});
}
});
Expand Down Expand Up @@ -1534,3 +1531,63 @@ describe.concurrent("a fetch() Response that cannot have a body", () => {
expect(exitCode).toBe(0);
});
});

// #24955: an empty body must reject .json() the way JSON.parse("") throws, on
// every path that holds the body. A fetch() Response resolved null.
describe.concurrent("an empty body rejects .json() with the JSON.parse error", () => {
const expected = { name: "SyntaxError", message: jsonParseError("").message };
const settle = (promise: Promise<unknown>) =>
promise.then(
value => ({ resolved: value }),
(error: Error) => ({ name: error.name, message: error.message }),
);

test("fetch() Response", async () => {
await using server = Bun.serve({ port: 0, fetch: () => new Response("") });
const response = await fetch(server.url);
expect(await settle(response.json())).toEqual(expected);
});

test("fetch() Response with a Content-Type", async () => {
await using server = Bun.serve({
port: 0,
fetch: () => new Response("", { headers: { "Content-Type": "application/json" } }),
});
const response = await fetch(server.url);
expect(await settle(response.json())).toEqual(expected);
});

test("fetch() Response with no body (204)", async () => {
await using server = Bun.serve({ port: 0, fetch: () => new Response(null, { status: 204 }) });
const response = await fetch(server.url);
expect(await settle(response.json())).toEqual(expected);
});

test("Request received by Bun.serve()", async () => {
await using server = Bun.serve({
port: 0,
fetch: async request => Response.json(await settle(request.json())),
});
const response = await fetch(server.url, { method: "POST", body: "" });
expect(await response.json()).toEqual(expected);
});

test.each([
["Response('')", () => new Response("")],
["Response(null)", () => new Response(null)],
["Response(new Uint8Array(0))", () => new Response(new Uint8Array(0))],
["Request('')", () => new Request("http://example.com/", { method: "POST", body: "" })],
["Blob([])", () => new Blob([])],
["Blob(['\\uFEFF'])", () => new Blob(["\uFEFF"])],
["Blob([]).stream()", () => new Blob([]).stream()],
["Response(ReadableStream)", () => new Response(new ReadableStream({ start: controller => controller.close() }))],
])("%s", async (_, make) => {
expect(await settle(make().json())).toEqual(expected);
});

test("Bun.file()", async () => {
using dir = tempDir("empty-json", { "empty.json": "", "bom.json": "\uFEFF" });
expect(await settle(file(`${dir}/empty.json`).json())).toEqual(expected);
expect(await settle(file(`${dir}/bom.json`).json())).toEqual(expected);
});
});
Loading