Skip to content
Open
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
c94351c
node:stream: define the Readable operators with the class and load th…
robobun Nov 6, 2026
7989ac0
process.stdout: load the Writable chain, not the node:stream barrel
robobun Nov 6, 2026
51ec702
process.stdin takes the class from internal/fs/streams; tests
robobun Nov 6, 2026
c7d9240
aot: process.stdout and process.stderr load no node:fs behind the host
robobun Nov 6, 2026
e522dd1
review: stdin keeps node:fs's class, lint matches top-level requires …
robobun Nov 6, 2026
aa899ed
aot: keep the mock test as on main
robobun Nov 6, 2026
3e5904f
node:fs: void the prototype read that puts ReadStream below Readable
robobun Nov 6, 2026
742b65b
streams: one-line comments
robobun Nov 6, 2026
5208745
aot: _http_server's second text loads Duplex where the first text does
robobun Nov 6, 2026
d874690
node:fs: a stream over a FileHandle calls the functions node:fs write…
robobun Nov 7, 2026
839ca6e
Merge origin/main into robobun/1f3c2915/stdout-without-stream-barrel
robobun Nov 8, 2026
ce4a474
streams: a built-in module stands below what a program stored on node…
robobun Nov 8, 2026
bb8c9d2
node:http: read Stream and Duplex off the Stream function, not the no…
robobun Nov 8, 2026
af38b05
node:http: load all of node:stream again
robobun Nov 8, 2026
df4d1a7
node:fs: a stub under stream.Readable fails the load of the fs stream…
robobun Nov 8, 2026
97a4492
fs streams: kFs is set where it was, undefined on a stream that write…
robobun Nov 8, 2026
cf71189
fs streams: the write assertion is for node:fs alone; the stub test c…
robobun Nov 8, 2026
7671b94
fs streams: the first use of fs.ReadStream takes the Readable stored …
robobun Nov 8, 2026
33a2688
fs streams: one line on the prototype accessor
robobun Nov 8, 2026
e9d84ab
ci: retrigger
robobun Nov 8, 2026
e6509bf
node:fs: a null under stream.Readable takes the library's own Readable
robobun Nov 8, 2026
c12e24d
fs streams: fs.ReadStream takes the library's own Readable at its fir…
robobun Nov 9, 2026
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
12 changes: 8 additions & 4 deletions src/codegen/builtins/host/runtime-dependencies.builtins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ const standardStreamModulesThatTestsCanWatch = standardStreamModules.map(load =>
...load,
when: b.whenTestsReplaceBuiltins,
}));
// A standard output is a WriteStream, which writes through a FileSink and loads no node:fs. The input is a ReadStream, which reads through node:fs.
const standardOutputModulesThatTestsCanWatch = standardStreamModulesThatTestsCanWatch.filter(
load => load.module !== "node:fs",
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

const loadedModulesByPath: Readonly<Record<b.BuiltinPath, readonly b.ModuleLoadSpec[]>> = {
"node:fs/promises": evaluates("internal/fifo"),
Expand All @@ -81,14 +85,14 @@ const loadedModulesByPath: Readonly<Record<b.BuiltinPath, readonly b.ModuleLoadS
},
],
"process.openStdin": standardStreamModules,
"console._stderr": standardStreamModulesThatTestsCanWatch,
"console._stdout": standardStreamModulesThatTestsCanWatch,
"process.stderr": standardStreamModulesThatTestsCanWatch,
"console._stderr": standardOutputModulesThatTestsCanWatch,
"console._stdout": standardOutputModulesThatTestsCanWatch,
"process.stderr": standardOutputModulesThatTestsCanWatch,
"process.stdin": [
...standardStreamModulesThatTestsCanWatch,
...standardStreamModules.map(load => ({ ...load, when: b.whenProgramStores("process.nextTick") })),
],
"process.stdout": standardStreamModulesThatTestsCanWatch,
"process.stdout": standardOutputModulesThatTestsCanWatch,
};

const pluginFunctionsOfBuild = functionsIn(
Expand Down
7 changes: 4 additions & 3 deletions src/js/ahead-of-time/internal/http/FakeSocket.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
// What the compiler reads in place of src/js/internal/http/FakeSocket.ts, which `bun run` evaluates. The two do the same.
// Written against that file with the SHA-256 d93d41b56254446c0d11f40b311ed02bf9cfaa57ccb434b01ead3347bc42ae05.
// Written against that file with the SHA-256 55ebc3ff272f5d0435bcb10a81592f5f33009a63f0e0d0a3c9cedf8fb56d30ea.
// When that file changes, bring the change here and write the new hash: test/internal/second-texts-of-modules.test.ts.

const http = require("internal/http");
const { kAutoDestroyed } = require("internal/shared");
// A symbol taken out of a pattern is a plain `symbol` for the type checker, and what it keys is untyped.
const kInternalSocketData: typeof http.kInternalSocketData = http.kInternalSocketData;
const serverSymbol: typeof http.serverSymbol = http.serverSymbol;
// The other text takes what lies under `Duplex` on node:stream when it is loaded, where the program has loaded node:stream. Here the class above the socket is written into the compiled program.
const duplexOfProgram = $getByIdDirect(require("internal/streams/legacy").Stream, "Duplex") as unknown;
const Duplex = require("internal/streams/duplex");
// The other text takes what lies under `Duplex` on node:stream when it is loaded. Here the class above the socket is written into the compiled program.
if (require("internal/stream").Duplex !== Duplex)
if (duplexOfProgram !== undefined && duplexOfProgram !== Duplex)
throw new TypeError(
"stream.Duplex was replaced before node:http was loaded. In a compiled executable the classes of node:http extend the one that Bun made: add to stream.Duplex.prototype instead, or load node:http first.",
);
Expand Down
8 changes: 4 additions & 4 deletions src/js/ahead-of-time/node/_http_outgoing.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
// What the compiler reads in place of src/js/node/_http_outgoing.ts, which `bun run` evaluates. The two do the same.
// Written against that file with the SHA-256 7eb68379dcc85e37da343c90d1da52f21b0bd91937cea041c06b56a6db7551fc.
// Written against that file with the SHA-256 cc0966d587437dacd954e46c796d8ebc0cc7522b477bce1c3561885b0f86a5d1.
// When that file changes, bring the change here and write the new hash: test/internal/second-texts-of-modules.test.ts.

// Hardcoded module "node:_http_outgoing"
// This is a port of Node.js's lib/_http_outgoing.js
// https://github.com/nodejs/node/blob/v26.3.0/lib/_http_outgoing.js
const { Stream: streamOfProgram } = require("internal/stream");
const { Stream } = require("internal/streams/legacy");
// The other text takes what lies under `Stream` on node:stream when it is loaded. Here the class above OutgoingMessage is written into the compiled program.
if (streamOfProgram !== Stream)
// The other text takes what lies under `Stream` on node:stream when it is loaded, where the program has loaded node:stream. Here the class above OutgoingMessage is written into the compiled program.
const streamOfProgram = $getByIdDirect(Stream, "Stream") as unknown;
if (streamOfProgram !== undefined && streamOfProgram !== Stream)
throw new TypeError(
"stream.Stream was replaced before node:http was loaded. In a compiled executable the classes of node:http extend the one that Bun made: add to stream.Stream.prototype instead, or load node:http first.",
);
Expand Down
18 changes: 10 additions & 8 deletions src/js/ahead-of-time/node/_http_server.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,19 @@
// What the compiler reads in place of src/js/node/_http_server.ts, which `bun run` evaluates. The two do the same.
// Written against that file with the SHA-256 ff5fd0cf3ffd5e9a3fb246c83dbbefe854e635a64472500199657149d7819c82.
// Written against that file with the SHA-256 891cda33a3518db2ee872cfa62703f18ae3871083e67f1c5609f4dc0dfa6299e.
// When that file changes, bring the change here and write the new hash: test/internal/second-texts-of-modules.test.ts.

// Hardcoded module "node:_http_server"
const EventEmitter = require("node:events");
const { Stream } = require("node:stream");
const { Stream: StreamOfLibrary } = require("internal/streams/legacy");
// As the other text: what a program has stored under `Stream` on node:stream, where node:stream is loaded.
const Stream: $Node.StreamConstructor = $getByIdDirect(StreamOfLibrary, "Stream") ?? StreamOfLibrary;
const StreamPrototype = Stream.prototype;
// A name read from `plainStream` is looked up from Stream.prototype on. No constructor runs: the other text makes no stream here.
function PlainStream() {}
$toClass(PlainStream, "PlainStream", StreamOfLibrary);
if (Stream !== StreamOfLibrary) Object.setPrototypeOf(PlainStream.prototype, StreamPrototype);
const plainStream: any = new PlainStream();
// The library's own classes, which stand above the server's socket whatever a program has laid on node:stream.
const DuplexPrototype = require("internal/streams/duplex").prototype;
const ReadablePrototype = require("internal/streams/readable").prototype;
const { flagsOf, getDefaultHighWaterMark, internals: streamInternals } = require("internal/streams/state");
// As the streams defined it: the program may have stored another before this file was loaded.
const duplexResume = streamInternals.readableMethods!.resume;
const duplexRemoveListener = streamInternals.readableMethods!.removeListener;
const {
enqueueTick1,
queueTick1,
Expand Down Expand Up @@ -195,6 +190,13 @@ const enum HeaderBits {
unusual = date | connection | keep_alive | transfer_encoding | spilled,
}
const { FakeSocket } = require("internal/http/FakeSocket");
// The library's own classes, which stand above the server's socket whatever a program has laid on node:stream. Loaded here, where the other text's
// FakeSocket loads Duplex: a test that replaced built-in functions sees the same calls.
Comment thread
robobun marked this conversation as resolved.
Resolved
const DuplexPrototype = require("internal/streams/duplex").prototype;
const ReadablePrototype = require("internal/streams/readable").prototype;
// As the streams defined it: the program may have stored another before this file was loaded.
const duplexResume = streamInternals.readableMethods!.resume;
const duplexRemoveListener = streamInternals.readableMethods!.removeListener;
const NumberIsNaN = Number.isNaN;

const { IncomingMessage } = require("node:_http_incoming");
Expand Down
9 changes: 4 additions & 5 deletions src/js/builtins/ProcessObjectInternals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,9 @@ export function getStdioWriteStream(
});
stream._type = "tty";
} else {
const fs = require("node:fs");
stream = new fs.WriteStream(null, { autoClose: false, fd, $fastPath: true });
// The class itself, not fs.WriteStream: the stream does not load node:fs.
const { WriteStream } = require("internal/fs/streams");
stream = new WriteStream(null, { autoClose: false, fd, $fastPath: true });
stream.readable = false;
stream._type = "fs";

Expand Down Expand Up @@ -701,10 +702,8 @@ export function createOnWarning(
// process.stderr.write, not console.error: under an inspector Session console.* emits
// Runtime.consoleAPICalled, and a throwing listener there is surfaced via emitWarning,
// so console.error would re-enter and loop. writeWarning reads process.stderr per call, as Node does.
// A compiled program may write without making the stream, whose modules put the operators of node:stream on Readable.prototype.
if (IS_COMPILED_AHEAD_OF_TIME && !redirectPath) require("internal/streams/load_all").rest?.();
const wroteInPlaceOfStream = writeWarning(message + "\n", redirectPath);
// Those modules also load node:events, which puts its EventEmitter.prototype above the prototype of `process`. Behind writeWarning(), which reads the members
// The modules of the stream load node:events, which puts its EventEmitter.prototype above the prototype of `process`. Behind writeWarning(), which reads the members
// of built-in objects that they read, in their order. A program that cannot tell does without the module.
if (IS_COMPILED_AHEAD_OF_TIME && WARNINGS_LOAD_NODE_EVENTS && wroteInPlaceOfStream) require("node:events");
}
Expand Down
9 changes: 2 additions & 7 deletions src/js/builtins/stdio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,7 @@ export function getLightStdioWriteStreams(
// queued by the first read of it comes earlier than any other. And node:events puts its EventEmitter.prototype above the prototype of `process`.
const nextTick = process.nextTick;
require("node:events");
// And all of node:stream puts its operators on Readable.prototype, which a program that has loaded a part of it reaches.
const streams = require("internal/streams/load_all");
streams.rest?.();
const served: ServedByLightStream = streams.servedByLightOutputs;
const served: ServedByLightStream = require("internal/streams/load_all").servedByLightOutputs;
// What writeFast() of internal/fs/streams does with a receiver that is not a stream: it asks for the state of a stream and then calls _write().
function writeToForeignReceiver(receiver: any): never {
if (receiver === undefined)
Expand Down Expand Up @@ -163,9 +160,7 @@ export function getLightStdinStream(isTTY: boolean, needsWholeStream: NeedsWhole
// As in getLightStdioWriteStreams().
void process.nextTick;
require("node:events");
const streams = require("internal/streams/load_all");
streams.rest?.();
const served: ServedByLightStream = streams.servedByLightInput;
const served: ServedByLightStream = require("internal/streams/load_all").servedByLightInput;
return new Proxy(
{
get "%the whole stream%"() {
Expand Down
145 changes: 86 additions & 59 deletions src/js/internal/fs/streams.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
// fs.ReadStream and fs.WriteStream are lazily loaded to avoid importing 'node:stream' until required
const { Readable, Writable, finished } = require("node:stream");
const fs = require("node:fs");
const { read, write, fsync, writev } = fs;
// process.stdout is a WriteStream: the Writable class and finished() load here, not node:stream, Readable or node:fs.
// node:stream is `Stream` with its members. Where a program has loaded it, the classes here stand below what it has stored there.
Comment thread
robobun marked this conversation as resolved.
Resolved
const { Stream } = require("internal/streams/legacy");
const ReadableOfProgram = $getByIdDirect(Stream, "Readable") as $Node.ReadableConstructor | undefined;
const Writable: $Node.WritableConstructor = $getByIdDirect(Stream, "Writable") ?? require("internal/streams/writable");
Comment thread
robobun marked this conversation as resolved.
Resolved
const finished: typeof Stream.finished =
$getByIdDirect(Stream, "finished") ?? require("internal/streams/end-of-stream");
const fileHandles = require("internal/fs/file_handles");
type FileHandleInternals = NonNullable<typeof fileHandles.internals>;
type FileHandle = $Node.FileHandle;
Expand Down Expand Up @@ -132,51 +135,56 @@ const { internals } = fileHandles;
if (internals) takeFileHandleInternals(internals);
else fileHandles.whenLoaded = takeFileHandleInternals;

const fileHandleStreamFs = (fh: FileHandle) => ({
// try to use the basic fs.read/write/fsync if available, since they are less
// abstractions. however, node.js allows patching the file handle, so this has
// to be checked for.
read:
fh.read === fileHandlePrototypeRead
? read
: function (
fd: number | null,
buf: Buffer,
offset: number,
length: number,
pos: number | undefined,
cb: (error: Error | null, bytesRead?: number, buffer?: Buffer) => void,
) {
return fh.read(buf, offset, length, pos).then(
({ bytesRead, buffer }) => cb(null, bytesRead, buffer),
err => cb(err, 0, buf),
);
},
write:
fh.write === fileHandlePrototypeWrite
? write
: function (
fd: number | null,
buffer: Buffer,
offset: number,
length: number,
position: number | undefined,
cb: (error: Error | null, bytesWritten?: number, buffer?: Buffer) => void,
) {
return fh.write(buffer, offset, length, position).then(
({ bytesWritten, buffer }) => cb(null, bytesWritten, buffer),
err => cb(err, 0, buffer),
);
},
writev: fh.writev === fileHandlePrototypeWritev ? writev : undefined,
fsync:
fh.sync === fileHandlePrototypeFsync
? fsync
: function (fd: number, cb: ErrorCallback) {
return fh.sync().then(() => cb(), cb);
},
close: streamFileHandleClose.bind(fh),
});
// node:fs loads with the first stream over a FileHandle. The stream calls these as node:fs writes them, not what its exports hold now.
function fileHandleStreamFs(fh: FileHandle) {
require("node:fs");
const { read, write, fsync, writev } = require("internal/shared").originals.fs!;
return {
// try to use the basic fs.read/write/fsync if available, since they are less
// abstractions. however, node.js allows patching the file handle, so this has
// to be checked for.
Comment thread
robobun marked this conversation as resolved.
Resolved
read:
fh.read === fileHandlePrototypeRead
? read
: function (
fd: number | null,
buf: Buffer,
offset: number,
length: number,
pos: number | undefined,
cb: (error: Error | null, bytesRead?: number, buffer?: Buffer) => void,
) {
return fh.read(buf, offset, length, pos).then(
({ bytesRead, buffer }) => cb(null, bytesRead, buffer),
err => cb(err, 0, buf),
);
},
write:
fh.write === fileHandlePrototypeWrite
? write
: function (
fd: number | null,
buffer: Buffer,
offset: number,
length: number,
position: number | undefined,
cb: (error: Error | null, bytesWritten?: number, buffer?: Buffer) => void,
) {
return fh.write(buffer, offset, length, position).then(
({ bytesWritten, buffer }) => cb(null, bytesWritten, buffer),
err => cb(err, 0, buffer),
);
},
writev: fh.writev === fileHandlePrototypeWritev ? writev : undefined,
fsync:
fh.sync === fileHandlePrototypeFsync
? fsync
: function (fd: number, cb: ErrorCallback) {
return fh.sync().then(() => cb(), cb);
},
close: streamFileHandleClose.bind(fh),
};
}

function streamFileHandleClose(this: FileHandle, fd: FD, cb: ErrorCallback) {
$assert(this[kFd] == fd, "fd mismatch");
Expand Down Expand Up @@ -270,9 +278,9 @@ function ReadStream(

if (windowsHandle != null) {
validateWindowsHandle(windowsHandle, fd, customFs);
this[kFs] = fs;
this[kFs] = require("node:fs");
} else if (fd == null) {
this[kFs] = customFs || fs;
this[kFs] = customFs || require("node:fs");
this.fd = null;
this.path = getValidatedPath(path);
const { flags, mode } = options;
Expand All @@ -292,7 +300,7 @@ function ReadStream(
validateInt32(fd, "fd", 0, 2147483647);
}
this.fd = fd as number;
this[kFs] = customFs || fs;
this[kFs] = customFs || require("node:fs");
} else if (typeof fd === "object" && FileHandle !== undefined && fd instanceof FileHandle) {
if (options.fs) {
throw $ERR_METHOD_NOT_IMPLEMENTED("FileHandle with fs");
Expand Down Expand Up @@ -340,12 +348,28 @@ function ReadStream(
// such as highWaterMark and signal, and a throw there leaks the fd, as in Node.
if (windowsHandle != null) this.fd = windowsHandleToFd(windowsHandle);

Readable.$call(this, options);
(ReadableOfProgram ?? require("internal/streams/readable")).$call(this, options);
return this as unknown as void;
}
$toClass(ReadStream, "ReadStream", Readable);
$toClass(ReadStream, "ReadStream");
const readStreamPrototype = ReadStream.prototype;

// The class goes below Readable at its first use (`new`, `instanceof`, a read of `prototype`), so a WriteStream loads no Readable.
Object.defineProperty(ReadStream, "prototype", {
get() {
const Readable = ReadableOfProgram ?? require("internal/streams/readable");
Object.setPrototypeOf(readStreamPrototype, Readable.prototype);
Object.setPrototypeOf(ReadStream, Readable);
Object.defineProperty(ReadStream, "prototype", { value: readStreamPrototype, writable: true });
return readStreamPrototype;
},
set(value) {
Object.defineProperty(ReadStream, "prototype", { value, writable: true });
},
enumerable: false,
configurable: true,
});

Object.defineProperty(readStreamPrototype, "autoClose", {
get(this: $Node.ReadStream) {
return this._readableState.autoDestroy;
Expand Down Expand Up @@ -525,9 +549,7 @@ function WriteStream(
let { fd, autoClose, fs: customFs, start, flush, windowsHandle } = options;
if (windowsHandle != null) {
validateWindowsHandle(windowsHandle, fd, customFs);
this[kFs] = fs;
} else if (fd == null) {
this[kFs] = customFs || fs;
this.fd = null;
// Internal $fastPath callers (writableFromFileSink) discard .path; do not
// resolve it - path.resolve("") needs process.cwd(), which throws when
Expand All @@ -550,12 +572,11 @@ function WriteStream(
validateInt32(fd, "fd", 0, 2147483647);
}
this.fd = fd as number;
this[kFs] = customFs || fs;
} else if (typeof fd === "object" && FileHandle !== undefined && fd instanceof FileHandle) {
if (options.fs) {
throw $ERR_METHOD_NOT_IMPLEMENTED("FileHandle with fs");
}
this[kFs] = customFs = fileHandleStreamFs(fd);
customFs = fileHandleStreamFs(fd);
fd[kRef]();
fd.on("close", this.close.bind(this));
this.fd = fd = fd[kFd];
Expand All @@ -579,7 +600,6 @@ function WriteStream(
if (!writev) this._writev = null!;
} else {
this._writev = undefined;
$assert(this[kFs].write, "assuming user does not delete fs.write!");
}

if (flush == null) {
Expand Down Expand Up @@ -612,6 +632,13 @@ function WriteStream(
}
}

// A stream that writes through a FileSink never calls node:fs, and process.stdout does not load it.
if (customFs) this[kFs] = customFs;
else if (!fastPath) {
this[kFs] = require("node:fs");
$assert(this[kFs].write, "assuming user does not delete fs.write!");
}

// Enable fast path
if (fastPath) {
this[kWriteStreamFastPath] = fd != null ? fastWriter : true;
Expand Down
4 changes: 3 additions & 1 deletion src/js/internal/http/FakeSocket.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const { kInternalSocketData, serverSymbol } = require("internal/http");
const { kAutoDestroyed } = require("internal/shared");
const { Duplex } = require("internal/stream");
const { Stream } = require("internal/streams/legacy");
// node:stream is `Stream` with its members: what a program has stored under `Duplex` there, where node:stream is loaded. Else the class loads alone.
const Duplex: $Node.DuplexConstructor = $getByIdDirect(Stream, "Duplex") ?? require("internal/streams/duplex");

type FakeSocket = InstanceType<typeof FakeSocket>;
var FakeSocket = class Socket extends Duplex {
Expand Down
Loading
Loading