fix(http): narrow buffered bodies to what the runtime's Response accepts

A Node Buffer is a Uint8Array at runtime, but its declared backing store is
ArrayBufferLike, which admits SharedArrayBuffer — and BodyInit takes only
ArrayBuffer-backed views. Deno's lib rejected it outright at web.ts:112. This
is the app.fetch path, so the hole was on Deno, Bun and edge alike; it went
unnoticed because every implementation is forgiving about it at runtime.

Re-views rather than copies: this is the buffered-response path, and a copy
per response would cost real throughput on the runtimes that have no other
adapter. byteOffset and byteLength are load-bearing there — Buffer.from hands
back a window into a shared 8 KB pool, and dropping them returns the whole
pool. A direct test covers that; the static-serving one covers the integration.

The type is derived from Response's own constructor because BodyInit is not a
global under lib es2020 plus @types/node, though Response itself is.

Refs: Green-Tea/core#19
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-08-16 12:45:37 -05:00
1 parent 70bb9902dc
commit 30f33b6383
3 files changed
+70 -2

No files matched your search

+25 -1
View File
@@ -1,9 +1,33 @@
import { describe, it, expect } from 'vitest';
import { asReadableStream } from '../src/http/web';
import { asReadableStream, toBodyInit } from '../src/http/web';
import { sseEncoder } from '../src/encoders';
async function* nums() { yield { n: 1 }; yield { n: 2 }; }
describe('toBodyInit', () => {
it('passes a string through untouched', () => {
expect(toBodyInit('hello')).toBe('hello');
});
// `Buffer.from` allocates inside a shared 8 KB pool, so these bytes sit at a non-zero byteOffset.
// A conversion that re-views the backing store without the offset and length returns the entire
// pool — every other allocation in it included. Asserting the length alone catches that.
it('re-views a pooled Buffer as its own bytes, not the whole pool', async () => {
const buf = Buffer.from([0x00, 0x89, 0xff, 0xfe, 0x0a]);
expect(buf.byteOffset).toBeGreaterThan(0); // guards the premise: this Buffer really is pooled
expect(buf.buffer.byteLength).toBeGreaterThan(buf.byteLength);
const bytes = new Uint8Array(await new Response(toBodyInit(buf)).arrayBuffer());
expect(bytes.byteLength).toBe(5);
expect([...bytes]).toEqual([0x00, 0x89, 0xff, 0xfe, 0x0a]);
});
it('does not copy — the view shares the backing store', () => {
const buf = Buffer.from([1, 2, 3]);
expect((toBodyInit(buf) as Uint8Array).buffer).toBe(buf.buffer);
});
});
describe('asReadableStream', () => {
it('encodes each yielded value with the encoder', async () => {
const rs = asReadableStream(nums(), sseEncoder);