From 4f34d48029772676b6c0ea6656b0aac74ac3b39f Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Tue, 27 Jun 2023 13:42:25 -0700 Subject: getIfPropertyExists is safer than getDirect (#3391) Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com> --- src/bun.js/bindings/JSReadableState.cpp | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) (limited to 'src/bun.js/bindings/JSReadableState.cpp') diff --git a/src/bun.js/bindings/JSReadableState.cpp b/src/bun.js/bindings/JSReadableState.cpp index d09e30d44..2137e65d5 100644 --- a/src/bun.js/bindings/JSReadableState.cpp +++ b/src/bun.js/bindings/JSReadableState.cpp @@ -26,7 +26,7 @@ int64_t getHighWaterMark(JSC::VM& vm, JSC::JSGlobalObject* globalObject, bool is auto* clientData = WebCore::clientData(vm); if (JSValue highWaterMarkVal = options->getIfPropertyExists(globalObject, clientData->builtinNames().highWaterMarkPublicName())) { if (isDuplex && (highWaterMarkVal.isUndefined() || highWaterMarkVal.isNull())) { - highWaterMarkVal = options->getDirect(vm, JSC::Identifier::fromString(vm, "readableObjectMode"_s)); + highWaterMarkVal = options->getIfPropertyExists(globalObject, JSC::Identifier::fromString(vm, "readableObjectMode"_s)); } if (!highWaterMarkVal.isUndefinedOrNull()) { @@ -42,9 +42,9 @@ void JSReadableState::finishCreation(JSC::VM& vm, JSC::JSGlobalObject* globalObj Base::finishCreation(vm); if (options != nullptr) { - JSC::JSValue objectModeVal = options->getDirect(vm, JSC::Identifier::fromString(vm, "objectMode"_s)); + JSC::JSValue objectModeVal = options->getIfPropertyExists(globalObject, JSC::Identifier::fromString(vm, "objectMode"_s)); if (isDuplex && !objectModeVal) { - objectModeVal = options->getDirect(vm, JSC::Identifier::fromString(vm, "readableObjectMode"_s)); + objectModeVal = options->getIfPropertyExists(globalObject, JSC::Identifier::fromString(vm, "readableObjectMode"_s)); } if (objectModeVal && objectModeVal.toBoolean(globalObject)) setBool(JSReadableState::Mask::objectMode, true); @@ -65,11 +65,11 @@ void JSReadableState::finishCreation(JSC::VM& vm, JSC::JSGlobalObject* globalObj m_pipes.set(vm, this, JSC::constructEmptyArray(globalObject, nullptr, 0)); if (options != nullptr) { - JSC::JSValue emitCloseVal = options->getDirect(vm, JSC::Identifier::fromString(vm, "emitClose"_s)); + JSC::JSValue emitCloseVal = options->getIfPropertyExists(globalObject, JSC::Identifier::fromString(vm, "emitClose"_s)); if (!emitCloseVal.isBoolean() || emitCloseVal.toBoolean(globalObject)) setBool(JSReadableState::Mask::emitClose, true); // Has it been destroyed. - JSC::JSValue autoDestroyVal = options->getDirect(vm, JSC::Identifier::fromString(vm, "autoDestroy"_s)); + JSC::JSValue autoDestroyVal = options->getIfPropertyExists(globalObject, JSC::Identifier::fromString(vm, "autoDestroy"_s)); if (!autoDestroyVal.isBoolean() || autoDestroyVal.toBoolean(globalObject)) setBool(JSReadableState::Mask::autoDestroy, true); } @@ -90,26 +90,25 @@ void JSReadableState::finishCreation(JSC::VM& vm, JSC::JSGlobalObject* globalObj } m_awaitDrainWriters.set(vm, this, JSC::jsNull()); + JSValue decodeValue = JSC::jsNull(); + JSValue encodingValue = JSC::jsNull(); - if (options == nullptr) { - m_decoder.set(vm, this, JSC::jsNull()); - m_encoding.set(vm, this, JSC::jsNull()); - } else { - JSC::JSValue encodingVal = options->getDirect(vm, JSC::Identifier::fromString(vm, "encoding"_s)); + if (options != nullptr) { + JSC::JSValue encodingVal = options->getIfPropertyExists(globalObject, JSC::Identifier::fromString(vm, "encoding"_s)); if (encodingVal && encodingVal.isString()) { auto constructor = reinterpret_cast(globalObject)->JSStringDecoder(); auto constructData = JSC::getConstructData(constructor); MarkedArgumentBuffer args; args.append(encodingVal); JSObject* decoder = JSC::construct(globalObject, constructor, constructData, args); - m_decoder.set(vm, this, decoder); - m_encoding.set(vm, this, encodingVal); - } else { - m_decoder.set(vm, this, JSC::jsNull()); - m_encoding.set(vm, this, JSC::jsNull()); + decodeValue = decoder; + encodingValue = encodingVal; } } + m_decoder.set(vm, this, decodeValue); + m_encoding.set(vm, this, encodingValue); + // ReadableState.constructed is set to false during construction when a _construct method is implemented // this is here so that the ReadableState behavior tracks the behavior in node, and that calling Readable.read // will work when we return early from construct because there is no Readable._construct implemented @@ -403,10 +402,12 @@ JSC::EncodedJSValue JSReadableStateConstructor::construct(JSC::JSGlobalObject* l return JSValue::encode(jsUndefined()); } isDuplex = isDuplexVal.toBoolean(lexicalGlobalObject); + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); JSObject* options = nullptr; - if (optionsVal.toBoolean(lexicalGlobalObject) && optionsVal.isObject()) { + if (optionsVal && optionsVal.isObject()) { options = optionsVal.toObject(lexicalGlobalObject); } + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); JSReadableState* stringDecoder = JSReadableState::create( vm, lexicalGlobalObject, reinterpret_cast(lexicalGlobalObject)->JSReadableStateStructure(), isDuplex, options); -- cgit v1.2.3 From 940c9a8185cb0c27e03e804b7bdd01cf5a91ec3e Mon Sep 17 00:00:00 2001 From: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com> Date: Tue, 27 Jun 2023 16:16:35 -0700 Subject: Fix some checks --- src/bun.js/bindings/JSReadableState.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/bun.js/bindings/JSReadableState.cpp') diff --git a/src/bun.js/bindings/JSReadableState.cpp b/src/bun.js/bindings/JSReadableState.cpp index 2137e65d5..8a4ee746b 100644 --- a/src/bun.js/bindings/JSReadableState.cpp +++ b/src/bun.js/bindings/JSReadableState.cpp @@ -29,7 +29,7 @@ int64_t getHighWaterMark(JSC::VM& vm, JSC::JSGlobalObject* globalObject, bool is highWaterMarkVal = options->getIfPropertyExists(globalObject, JSC::Identifier::fromString(vm, "readableObjectMode"_s)); } - if (!highWaterMarkVal.isUndefinedOrNull()) { + if (highWaterMarkVal && !highWaterMarkVal.isUndefinedOrNull()) { return highWaterMarkVal.toInt32(globalObject); } } @@ -66,11 +66,11 @@ void JSReadableState::finishCreation(JSC::VM& vm, JSC::JSGlobalObject* globalObj if (options != nullptr) { JSC::JSValue emitCloseVal = options->getIfPropertyExists(globalObject, JSC::Identifier::fromString(vm, "emitClose"_s)); - if (!emitCloseVal.isBoolean() || emitCloseVal.toBoolean(globalObject)) + if (!emitCloseVal || emitCloseVal.toBoolean(globalObject)) setBool(JSReadableState::Mask::emitClose, true); // Has it been destroyed. JSC::JSValue autoDestroyVal = options->getIfPropertyExists(globalObject, JSC::Identifier::fromString(vm, "autoDestroy"_s)); - if (!autoDestroyVal.isBoolean() || autoDestroyVal.toBoolean(globalObject)) + if (!autoDestroyVal || autoDestroyVal.toBoolean(globalObject)) setBool(JSReadableState::Mask::autoDestroy, true); } -- cgit v1.2.3 From b9460087e391c454f323390a42902a3ed024c8bc Mon Sep 17 00:00:00 2001 From: dave caruso Date: Thu, 29 Jun 2023 23:36:18 -0400 Subject: Fixes `node:http` and `node:stream` so `ytdl-core` works. (#3452) * fix crash in readablestate * make node:https request+get actually use https * use a native readablestream in IncomingMessage * tweaks * fix abort crash * emit close by default * remove abort. this isnt a real function * add validate functions, fixup some other requested changes. not done yet * Update WebCoreJSBuiltins.cpp * Update JSReadableState.cpp * Add some missing exports --------- Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com> --- packages/bun-types/bun.d.ts | 6 +- packages/bun-types/globals.d.ts | 9 +- src/bun.js/api/server.zig | 3 +- src/bun.js/bindings/JSReadableState.cpp | 5 +- src/bun.js/webcore/body.zig | 6 +- src/js/builtins/ReadableStreamDefaultReader.ts | 4 +- src/js/builtins/builtins.d.ts | 6 +- src/js/node/events.js | 10 +- src/js/node/http.js | 1795 ----------------------- src/js/node/http.ts | 1810 ++++++++++++++++++++++++ src/js/node/https.js | 3 - src/js/node/https.ts | 65 + src/js/out/WebCoreJSBuiltins.cpp | 150 +- src/js/out/modules/node/assert.js | 84 +- src/js/out/modules/node/dns.promises.js | 3 + src/js/out/modules/node/events.js | 2 + src/js/out/modules/node/fs.promises.js | 2 +- src/js/out/modules/node/http.js | 103 +- src/js/out/modules/node/https.js | 55 +- src/js/private.d.ts | 1 + test/js/node/http/node-http.test.ts | 23 +- 21 files changed, 2163 insertions(+), 1982 deletions(-) delete mode 100644 src/js/node/http.js create mode 100644 src/js/node/http.ts delete mode 100644 src/js/node/https.js create mode 100644 src/js/node/https.ts (limited to 'src/bun.js/bindings/JSReadableState.cpp') diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index 4c10212f2..86ded9aa0 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -1912,7 +1912,9 @@ declare module "bun" { export interface TLSWebSocketServeOptions extends WebSocketServeOptions, - TLSOptions {} + TLSOptions { + tls?: TLSOptions; + } export interface Errorlike extends Error { code?: string; errno?: number; @@ -2023,6 +2025,8 @@ declare module "bun" { * The values are SSL options objects. */ serverNames?: Record; + + tls?: TLSOptions; } /** diff --git a/packages/bun-types/globals.d.ts b/packages/bun-types/globals.d.ts index a5d011b52..5784f91c2 100644 --- a/packages/bun-types/globals.d.ts +++ b/packages/bun-types/globals.d.ts @@ -888,6 +888,12 @@ type ReadableStreamController = ReadableStreamDefaultController; type ReadableStreamDefaultReadResult = | ReadableStreamDefaultReadValueResult | ReadableStreamDefaultReadDoneResult; +interface ReadableStreamDefaultReadManyResult { + done: boolean; + /** Number of bytes */ + size: number; + value: T[]; +} type ReadableStreamReader = ReadableStreamDefaultReader; interface RequestInit { @@ -2261,7 +2267,8 @@ declare var ReadableStreamDefaultController: { interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { read(): Promise>; - readMany(): Promise>; + /** Only available in Bun. If there are multiple chunks in the queue, this will return all of them at the same time. */ + readMany(): Promise>; releaseLock(): void; } diff --git a/src/bun.js/api/server.zig b/src/bun.js/api/server.zig index ebfacdcc9..32c4fd25c 100644 --- a/src/bun.js/api/server.zig +++ b/src/bun.js/api/server.zig @@ -1456,12 +1456,11 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp // the promise is pending if (body.value.Locked.action != .none or body.value.Locked.promise != null) { this.pending_promises_for_abort += 1; - body.value.toErrorInstance(JSC.toTypeError(.ABORT_ERR, "Request aborted", .{}, this.server.globalThis), this.server.globalThis); } else if (body.value.Locked.readable != null) { body.value.Locked.readable.?.abort(this.server.globalThis); - body.value.toErrorInstance(JSC.toTypeError(.ABORT_ERR, "Request aborted", .{}, this.server.globalThis), this.server.globalThis); body.value.Locked.readable = null; } + body.value.toErrorInstance(JSC.toTypeError(.ABORT_ERR, "Request aborted", .{}, this.server.globalThis), this.server.globalThis); } } diff --git a/src/bun.js/bindings/JSReadableState.cpp b/src/bun.js/bindings/JSReadableState.cpp index 8a4ee746b..1f3a36def 100644 --- a/src/bun.js/bindings/JSReadableState.cpp +++ b/src/bun.js/bindings/JSReadableState.cpp @@ -29,7 +29,7 @@ int64_t getHighWaterMark(JSC::VM& vm, JSC::JSGlobalObject* globalObject, bool is highWaterMarkVal = options->getIfPropertyExists(globalObject, JSC::Identifier::fromString(vm, "readableObjectMode"_s)); } - if (highWaterMarkVal && !highWaterMarkVal.isUndefinedOrNull()) { + if (highWaterMarkVal && highWaterMarkVal.isNumber()) { return highWaterMarkVal.toInt32(globalObject); } } @@ -72,6 +72,9 @@ void JSReadableState::finishCreation(JSC::VM& vm, JSC::JSGlobalObject* globalObj JSC::JSValue autoDestroyVal = options->getIfPropertyExists(globalObject, JSC::Identifier::fromString(vm, "autoDestroy"_s)); if (!autoDestroyVal || autoDestroyVal.toBoolean(globalObject)) setBool(JSReadableState::Mask::autoDestroy, true); + } else { + setBool(JSReadableState::Mask::emitClose, true); + setBool(JSReadableState::Mask::autoDestroy, true); } // Indicates whether the stream has finished destroying. diff --git a/src/bun.js/webcore/body.zig b/src/bun.js/webcore/body.zig index df3ba3ce1..028b104b2 100644 --- a/src/bun.js/webcore/body.zig +++ b/src/bun.js/webcore/body.zig @@ -496,8 +496,10 @@ pub const Body = struct { locked.readable.?.value.protect(); return locked.readable.?.value; }, - - else => unreachable, + .Error => { + // TODO: handle error properly + return JSC.WebCore.ReadableStream.empty(globalThis); + }, } } diff --git a/src/js/builtins/ReadableStreamDefaultReader.ts b/src/js/builtins/ReadableStreamDefaultReader.ts index ecd553ed5..70c6df8c3 100644 --- a/src/js/builtins/ReadableStreamDefaultReader.ts +++ b/src/js/builtins/ReadableStreamDefaultReader.ts @@ -43,7 +43,7 @@ export function cancel(this, reason) { return $readableStreamReaderGenericCancel(this, reason); } -export function readMany(this) { +export function readMany(this: ReadableStreamDefaultReader): ReadableStreamDefaultReadManyResult { if (!$isReadableStreamDefaultReader(this)) throw new TypeError("ReadableStreamDefaultReader.readMany() should not be called directly"); @@ -75,7 +75,7 @@ export function readMany(this) { var length = values.length; if (length > 0) { - var outValues = $newArrayWithSize(length); + var outValues = $newArrayWithSize(length); if ($isReadableByteStreamController(controller)) { { const buf = values[0]; diff --git a/src/js/builtins/builtins.d.ts b/src/js/builtins/builtins.d.ts index 449c9c128..2de8d8206 100644 --- a/src/js/builtins/builtins.d.ts +++ b/src/js/builtins/builtins.d.ts @@ -433,9 +433,9 @@ declare interface ArrayBufferConstructor extends ClassWithIntrinsics extends ClassWithIntrinsics> {} declare interface UnderlyingSource { - $lazy: boolean; - $bunNativeType: number; - $bunNativePtr: number; + $lazy?: boolean; + $bunNativeType?: number; + $bunNativePtr?: number; autoAllocateChunkSize?: number; } diff --git a/src/js/node/events.js b/src/js/node/events.js index 4fd16a85b..111fdb524 100644 --- a/src/js/node/events.js +++ b/src/js/node/events.js @@ -463,12 +463,14 @@ const usingDomains = false; Object.assign(EventEmitter, { once, on, getEventListeners, setMaxListeners, listenerCount, EventEmitterAsyncResource }); export { EventEmitter, - once, - on, + captureRejectionSymbol, + kErrorMonitor as errorMonitor, getEventListeners, - setMaxListeners, listenerCount, + on, + once, + setMaxListeners, usingDomains, - captureRejectionSymbol, + EventEmitterAsyncResource, }; export default EventEmitter; diff --git a/src/js/node/http.js b/src/js/node/http.js deleted file mode 100644 index fe9730101..000000000 --- a/src/js/node/http.js +++ /dev/null @@ -1,1795 +0,0 @@ -// Hardcoded module "node:http" -import { EventEmitter } from "node:events"; -import { Readable, Writable, Duplex } from "node:stream"; -import { isTypedArray } from "util/types"; - -// Cheaper to duplicate this than to import it from node:net -function isIPv6(input) { - const v4Seg = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; - const v4Str = `(${v4Seg}[.]){3}${v4Seg}`; - const v6Seg = "(?:[0-9a-fA-F]{1,4})"; - const IPv6Reg = new RegExp( - "^(" + - `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` + - `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` + - `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` + - `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` + - `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` + - `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` + - `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` + - `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` + - ")(%[0-9a-zA-Z-.:]{1,})?$", - ); - - return IPv6Reg.test(input); -} - -// TODO: add primordial for URL -// Importing from node:url is unnecessary -const { URL } = globalThis; - -const { newArrayWithSize, String, Object, Array } = globalThis[Symbol.for("Bun.lazy")]("primordials"); - -const globalReportError = globalThis.reportError; -const setTimeout = globalThis.setTimeout; -const fetch = Bun.fetch; -const nop = () => {}; - -const __DEBUG__ = process.env.__DEBUG__; -const debug = __DEBUG__ ? (...args) => console.log("node:http", ...args) : nop; - -const kEmptyObject = Object.freeze(Object.create(null)); -const kOutHeaders = Symbol.for("kOutHeaders"); -const kEndCalled = Symbol.for("kEndCalled"); -const kAbortController = Symbol.for("kAbortController"); -const kClearTimeout = Symbol("kClearTimeout"); - -const kCorked = Symbol.for("kCorked"); -const searchParamsSymbol = Symbol.for("query"); // This is the symbol used in Node - -// Primordials -const StringPrototypeSlice = String.prototype.slice; -const StringPrototypeStartsWith = String.prototype.startsWith; -const StringPrototypeToUpperCase = String.prototype.toUpperCase; -const StringPrototypeIncludes = String.prototype.includes; -const StringPrototypeCharCodeAt = String.prototype.charCodeAt; -const StringPrototypeIndexOf = String.prototype.indexOf; -const ArrayIsArray = Array.isArray; -const RegExpPrototypeExec = RegExp.prototype.exec; -const ObjectAssign = Object.assign; -const ObjectPrototypeHasOwnProperty = Object.prototype.hasOwnProperty; - -const INVALID_PATH_REGEX = /[^\u0021-\u00ff]/; -const NODE_HTTP_WARNING = - "WARN: Agent is mostly unused in Bun's implementation of http. If you see strange behavior, this is probably the cause."; - -var _globalAgent; -var _defaultHTTPSAgent; -var kInternalRequest = Symbol("kInternalRequest"); -var kInternalSocketData = Symbol.for("::bunternal::"); - -const kEmptyBuffer = Buffer.alloc(0); - -function isValidTLSArray(obj) { - if (typeof obj === "string" || isTypedArray(obj) || obj instanceof ArrayBuffer || obj instanceof Blob) return true; - if (Array.isArray(obj)) { - for (var i = 0; i < obj.length; i++) { - if (typeof obj !== "string" && !isTypedArray(obj) && !(obj instanceof ArrayBuffer) && !(obj instanceof Blob)) - return false; - } - return true; - } -} - -function getHeader(headers, name) { - if (!headers) return; - const result = headers.get(name); - return result == null ? undefined : result; -} - -var FakeSocket = class Socket extends Duplex { - bytesRead = 0; - bytesWritten = 0; - connecting = false; - remoteAddress = null; - localAddress = "127.0.0.1"; - remotePort; - timeout = 0; - - isServer = false; - - address() { - return { - address: this.localAddress, - family: this.localFamily, - port: this.localPort, - }; - } - - get bufferSize() { - return this.writableLength; - } - - connect(port, host, connectListener) { - return this; - } - - _destroy(err, callback) {} - - _final(callback) {} - - get localAddress() { - return "127.0.0.1"; - } - - get localFamily() { - return "IPv4"; - } - - get localPort() { - return 80; - } - - get pending() { - return this.connecting; - } - - _read(size) {} - - get readyState() { - if (this.connecting) return "opening"; - if (this.readable) { - return this.writable ? "open" : "readOnly"; - } else { - return this.writable ? "writeOnly" : "closed"; - } - } - - ref() {} - - get remoteFamily() { - return "IPv4"; - } - - resetAndDestroy() {} - - setKeepAlive(enable = false, initialDelay = 0) {} - - setNoDelay(noDelay = true) { - return this; - } - - setTimeout(timeout, callback) { - return this; - } - - unref() {} - - _write(chunk, encoding, callback) {} -}; - -export function createServer(options, callback) { - return new Server(options, callback); -} - -export class Agent extends EventEmitter { - defaultPort = 80; - protocol = "http:"; - options; - requests; - sockets; - freeSockets; - - keepAliveMsecs; - keepAlive; - maxSockets; - maxFreeSockets; - scheduling; - maxTotalSockets; - totalSocketCount; - - #fakeSocket; - - static get globalAgent() { - return (_globalAgent ??= new Agent()); - } - - static get defaultMaxSockets() { - return Infinity; - } - - constructor(options = kEmptyObject) { - super(); - this.options = options = { ...options, path: null }; - if (options.noDelay === undefined) options.noDelay = true; - - // Don't confuse net and make it think that we're connecting to a pipe - this.requests = kEmptyObject; - this.sockets = kEmptyObject; - this.freeSockets = kEmptyObject; - - this.keepAliveMsecs = options.keepAliveMsecs || 1000; - this.keepAlive = options.keepAlive || false; - this.maxSockets = options.maxSockets || Agent.defaultMaxSockets; - this.maxFreeSockets = options.maxFreeSockets || 256; - this.scheduling = options.scheduling || "lifo"; - this.maxTotalSockets = options.maxTotalSockets; - this.totalSocketCount = 0; - this.defaultPort = options.defaultPort || 80; - this.protocol = options.protocol || "http:"; - } - - createConnection() { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.createConnection is a no-op, returns fake socket"); - return (this.#fakeSocket ??= new FakeSocket()); - } - - getName(options = kEmptyObject) { - let name = `http:${options.host || "localhost"}:`; - if (options.port) name += options.port; - name += ":"; - if (options.localAddress) name += options.localAddress; - // Pacify parallel/test-http-agent-getname by only appending - // the ':' when options.family is set. - if (options.family === 4 || options.family === 6) name += `:${options.family}`; - if (options.socketPath) name += `:${options.socketPath}`; - return name; - } - - addRequest() { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.addRequest is a no-op"); - } - - createSocket(req, options, cb) { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.createSocket returns fake socket"); - cb(null, (this.#fakeSocket ??= new FakeSocket())); - } - - removeSocket() { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.removeSocket is a no-op"); - } - - keepSocketAlive() { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.keepSocketAlive is a no-op"); - - return true; - } - - reuseSocket() { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.reuseSocket is a no-op"); - } - - destroy() { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.destroy is a no-op"); - } -} -function emitListeningNextTick(self, onListen, err, hostname, port) { - if (typeof onListen === "function") { - try { - onListen(err, hostname, port); - } catch (err) { - self.emit("error", err); - } - } - - self.listening = !err; - - if (err) { - self.emit("error", err); - } else { - self.emit("listening", hostname, port); - } -} - -export class Server extends EventEmitter { - #server; - #options; - #tls; - #is_tls = false; - listening = false; - - constructor(options, callback) { - super(); - - if (typeof options === "function") { - callback = options; - options = {}; - } else if (options == null || typeof options === "object") { - options = { ...options }; - this.#tls = null; - let key = options.key; - if (key) { - if (!isValidTLSArray(key)) { - throw new TypeError( - "key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", - ); - } - this.#is_tls = true; - } - let cert = options.cert; - if (cert) { - if (!isValidTLSArray(cert)) { - throw new TypeError( - "cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", - ); - } - this.#is_tls = true; - } - - let ca = options.ca; - if (ca) { - if (!isValidTLSArray(ca)) { - throw new TypeError( - "ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", - ); - } - this.#is_tls = true; - } - let passphrase = options.passphrase; - if (passphrase && typeof passphrase !== "string") { - throw new TypeError("passphrase argument must be an string"); - } - - let serverName = options.servername; - if (serverName && typeof serverName !== "string") { - throw new TypeError("servername argument must be an string"); - } - - let secureOptions = options.secureOptions || 0; - if (secureOptions && typeof secureOptions !== "number") { - throw new TypeError("secureOptions argument must be an number"); - } - - if (this.#is_tls) { - this.#tls = { - serverName, - key: key, - cert: cert, - ca: ca, - passphrase: passphrase, - secureOptions: secureOptions, - }; - } else { - this.#tls = null; - } - } else { - throw new Error("bun-http-polyfill: invalid arguments"); - } - - this.#options = options; - - if (callback) this.on("request", callback); - } - - closeAllConnections() { - const server = this.#server; - if (!server) { - return; - } - this.#server = undefined; - server.stop(true); - this.emit("close"); - } - - closeIdleConnections() { - // not actually implemented - } - - close(optionalCallback) { - const server = this.#server; - if (!server) { - if (typeof optionalCallback === "function") - process.nextTick(optionalCallback, new Error("Server is not running")); - return; - } - this.#server = undefined; - if (typeof optionalCallback === "function") this.once("close", optionalCallback); - server.stop(); - this.emit("close"); - } - - address() { - if (!this.#server) return null; - - const address = this.#server.hostname; - return { - address, - family: isIPv6(address) ? "IPv6" : "IPv4", - port: this.#server.port, - }; - } - - listen(port, host, backlog, onListen) { - const server = this; - if (typeof host === "function") { - onListen = host; - host = undefined; - } - - if (typeof port === "function") { - onListen = port; - } else if (typeof port === "object") { - port?.signal?.addEventListener("abort", () => { - this.close(); - }); - - host = port?.host; - port = port?.port; - - if (typeof port?.callback === "function") onListen = port?.callback; - } - - if (typeof backlog === "function") { - onListen = backlog; - } - - const ResponseClass = this.#options.ServerResponse || ServerResponse; - const RequestClass = this.#options.IncomingMessage || IncomingMessage; - - try { - const tls = this.#tls; - if (tls) { - this.serverName = tls.serverName || host || "localhost"; - } - this.#server = Bun.serve({ - tls, - port, - hostname: host, - // Bindings to be used for WS Server - websocket: { - open(ws) { - ws.data.open(ws); - }, - message(ws, message) { - ws.data.message(ws, message); - }, - close(ws, code, reason) { - ws.data.close(ws, code, reason); - }, - drain(ws) { - ws.data.drain(ws); - }, - }, - fetch(req, _server) { - var pendingResponse; - var pendingError; - var rejectFunction, resolveFunction; - var reject = err => { - if (pendingError) return; - pendingError = err; - if (rejectFunction) rejectFunction(err); - }; - - var reply = function (resp) { - if (pendingResponse) return; - pendingResponse = resp; - if (resolveFunction) resolveFunction(resp); - }; - - const http_req = new RequestClass(req); - const http_res = new ResponseClass({ reply, req: http_req }); - - http_req.once("error", err => reject(err)); - http_res.once("error", err => reject(err)); - - const upgrade = req.headers.get("upgrade"); - if (upgrade) { - const socket = new FakeSocket(); - socket[kInternalSocketData] = [_server, http_res, req]; - server.emit("upgrade", http_req, socket, kEmptyBuffer); - } else { - server.emit("request", http_req, http_res); - } - - if (pendingError) { - throw pendingError; - } - - if (pendingResponse) { - return pendingResponse; - } - - return new Promise((resolve, reject) => { - resolveFunction = resolve; - rejectFunction = reject; - }); - }, - }); - setTimeout(emitListeningNextTick, 1, this, onListen, null, this.#server.hostname, this.#server.port); - } catch (err) { - setTimeout(emitListeningNextTick, 1, this, onListen, err); - } - - return this; - } - setTimeout(msecs, callback) {} -} - -function assignHeaders(object, req) { - var headers = req.headers.toJSON(); - const rawHeaders = newArrayWithSize(req.headers.count * 2); - var i = 0; - for (const key in headers) { - rawHeaders[i++] = key; - rawHeaders[i++] = headers[key]; - } - object.headers = headers; - object.rawHeaders = rawHeaders; -} -function destroyBodyStreamNT(bodyStream) { - bodyStream.destroy(); -} - -var defaultIncomingOpts = { type: "request" }; - -function getDefaultHTTPSAgent() { - return (_defaultHTTPSAgent ??= new Agent({ defaultPort: 443, protocol: "https:" })); -} - -export class IncomingMessage extends Readable { - constructor(req, defaultIncomingOpts) { - const method = req.method; - - super(); - - const url = new URL(req.url); - - var { type = "request", [kInternalRequest]: nodeReq } = defaultIncomingOpts || {}; - - this.#noBody = - type === "request" // TODO: Add logic for checking for body on response - ? "GET" === method || - "HEAD" === method || - "TRACE" === method || - "CONNECT" === method || - "OPTIONS" === method || - (parseInt(req.headers.get("Content-Length") || "") || 0) === 0 - : false; - - this.#req = req; - this.method = method; - this.#type = type; - this.complete = !!this.#noBody; - - this.#bodyStream = null; - const socket = new FakeSocket(); - socket.remoteAddress = url.hostname; - socket.remotePort = url.port; - this.#fakeSocket = socket; - - this.url = url.pathname + url.search; - this.#nodeReq = nodeReq; - assignHeaders(this, req); - } - - headers; - rawHeaders; - _consuming = false; - _dumped = false; - #bodyStream = null; - #fakeSocket = undefined; - #noBody = false; - #aborted = false; - #req; - url; - #type; - #nodeReq; - - get req() { - return this.#nodeReq; - } - - _construct(callback) { - // TODO: streaming - if (this.#type === "response" || this.#noBody) { - callback(); - return; - } - - const contentLength = this.#req.headers.get("content-length"); - const length = contentLength ? parseInt(contentLength, 10) : 0; - if (length === 0) { - this.#noBody = true; - callback(); - return; - } - - callback(); - } - - #closeBodyStream() { - debug("closeBodyStream()"); - var bodyStream = this.#bodyStream; - if (bodyStream == null) return; - this.complete = true; - this.#bodyStream = undefined; - this.push(null); - // process.nextTick(destroyBodyStreamNT, bodyStream); - } - - _read(size) { - if (this.#noBody) { - this.push(null); - this.complete = true; - } else if (this.#bodyStream == null) { - const contentLength = this.#req.headers.get("content-length"); - let remaining = contentLength ? parseInt(contentLength, 10) : 0; - this.#bodyStream = Readable.fromWeb(this.#req.body, { - highWaterMark: Number.isFinite(remaining) ? Math.min(remaining, 16384) : 16384, - }); - - const isBodySizeKnown = remaining > 0 && Number.isSafeInteger(remaining); - - if (isBodySizeKnown) { - this.#bodyStream.on("data", chunk => { - debug("body size known", remaining); - this.push(chunk); - // when we are streaming a known body size, automatically close the stream when we have read enough - remaining -= chunk?.byteLength ?? 0; - if (remaining <= 0) { - this.#closeBodyStream(); - } - }); - } else { - this.#bodyStream.on("data", chunk => { - this.push(chunk); - }); - } - - // this can be closed by the time we get here if enough data was synchronously available - this.#bodyStream && - this.#bodyStream.on("end", () => { - this.#closeBodyStream(); - }); - } else { - // this.#bodyStream.read(size); - } - } - - get aborted() { - return this.#aborted; - } - - abort() { - if (this.#aborted) return; - this.#aborted = true; - - this.#closeBodyStream(); - } - - get connection() { - return this.#fakeSocket; - } - - get statusCode() { - return this.#req.status; - } - - get statusMessage() { - return STATUS_CODES[this.#req.status]; - } - - get httpVersion() { - return "1.1"; - } - - get rawTrailers() { - return []; - } - - get httpVersionMajor() { - return 1; - } - - get httpVersionMinor() { - return 1; - } - - get trailers() { - return kEmptyObject; - } - - get socket() { - return (this.#fakeSocket ??= new FakeSocket()); - } - - set socket(val) { - this.#fakeSocket = val; - } - - setTimeout(msecs, callback) { - throw new Error("not implemented"); - } -} - -function emitErrorNt(msg, err, callback) { - callback(err); - if (typeof msg.emit === "function" && !msg._closed) { - msg.emit("error", err); - } -} - -function onError(self, err, cb) { - process.nextTick(() => emitErrorNt(self, err, cb)); -} - -function write_(msg, chunk, encoding, callback, fromEnd) { - if (typeof callback !== "function") callback = nop; - - let len; - if (chunk === null) { - // throw new ERR_STREAM_NULL_VALUES(); - throw new Error("ERR_STREAM_NULL_VALUES"); - } else if (typeof chunk === "string") { - len = Buffer.byteLength(chunk, encoding); - } else { - throw new Error("Invalid arg type for chunk"); - // throw new ERR_INVALID_ARG_TYPE( - // "chunk", - // ["string", "Buffer", "Uint8Array"], - // chunk, - // ); - } - - let err; - if (msg.finished) { - // err = new ERR_STREAM_WRITE_AFTER_END(); - err = new Error("ERR_STREAM_WRITE_AFTER_END"); - } else if (msg.destroyed) { - // err = new ERR_STREAM_DESTROYED("write"); - err = new Error("ERR_STREAM_DESTROYED"); - } - - if (err) { - if (!msg.destroyed) { - onError(msg, err, callback); - } else { - process.nextTick(callback, err); - } - return false; - } - - if (!msg._header) { - if (fromEnd) { - msg._contentLength = len; - } - // msg._implicitHeader(); - } - - if (!msg._hasBody) { - debug("This type of response MUST NOT have a body. " + "Ignoring write() calls."); - process.nextTick(callback); - return true; - } - - // if (!fromEnd && msg.socket && !msg.socket.writableCorked) { - // msg.socket.cork(); - // process.nextTick(connectionCorkNT, msg.socket); - // } - - return true; -} - -export class OutgoingMessage extends Writable { - #headers; - headersSent = false; - sendDate = true; - req; - - #finished = false; - [kEndCalled] = false; - - #fakeSocket; - #timeoutTimer = null; - [kAbortController] = null; - - // Express "compress" package uses this - _implicitHeader() {} - - // For compat with IncomingRequest - get headers() { - if (!this.#headers) return kEmptyObject; - return this.#headers.toJSON(); - } - - get shouldKeepAlive() { - return true; - } - - get chunkedEncoding() { - return false; - } - - set chunkedEncoding(value) { - // throw new Error('not implemented'); - } - - set shouldKeepAlive(value) { - // throw new Error('not implemented'); - } - - get useChunkedEncodingByDefault() { - return true; - } - - set useChunkedEncodingByDefault(value) { - // throw new Error('not implemented'); - } - - get socket() { - return (this.#fakeSocket ??= new FakeSocket()); - } - - set socket(val) { - this.#fakeSocket = val; - } - - get connection() { - return this.socket; - } - - get finished() { - return this.#finished; - } - - appendHeader(name, value) { - var headers = (this.#headers ??= new Headers()); - headers.append(name, value); - } - - flushHeaders() {} - - getHeader(name) { - return getHeader(this.#headers, name); - } - - getHeaders() { - if (!this.#headers) return kEmptyObject; - return this.#headers.toJSON(); - } - - getHeaderNames() { - var headers = this.#headers; - if (!headers) return []; - return Array.from(headers.keys()); - } - - removeHeader(name) { - if (!this.#headers) return; - this.#headers.delete(name); - } - - setHeader(name, value) { - var headers = (this.#headers ??= new Headers()); - headers.set(name, value); - return this; - } - - hasHeader(name) { - if (!this.#headers) return false; - return this.#headers.has(name); - } - - addTrailers(headers) { - throw new Error("not implemented"); - } - - [kClearTimeout]() { - if (this.#timeoutTimer) { - clearTimeout(this.#timeoutTimer); - this.#timeoutTimer = null; - } - } - - setTimeout(msecs, callback) { - if (this.#timeoutTimer) return this; - if (callback) { - this.on("timeout", callback); - } - - this.#timeoutTimer = setTimeout(async () => { - this.#timeoutTimer = null; - this[kAbortController]?.abort(); - this.emit("timeout"); - }, msecs); - - return this; - } -} - -export class ServerResponse extends Writable { - constructor({ req, reply }) { - super(); - this.req = req; - this._reply = reply; - this.sendDate = true; - this.statusCode = 200; - this.headersSent = false; - this.statusMessage = undefined; - this.#controller = undefined; - this.#firstWrite = undefined; - this._writableState.decodeStrings = false; - this.#deferred = undefined; - } - - req; - _reply; - sendDate; - statusCode; - #headers; - headersSent = false; - statusMessage; - #controller; - #firstWrite; - _sent100 = false; - _defaultKeepAlive = false; - _removedConnection = false; - _removedContLen = false; - #deferred = undefined; - #finished = false; - - // Express "compress" package uses this - _implicitHeader() {} - - _write(chunk, encoding, callback) { - if (!this.#firstWrite && !this.headersSent) { - this.#firstWrite = chunk; - callback(); - return; - } - - this.#ensureReadableStreamController(controller => { - controller.write(chunk); - callback(); - }); - } - - _writev(chunks, callback) { - if (chunks.length === 1 && !this.headersSent && !this.#firstWrite) { - this.#firstWrite = chunks[0].chunk; - callback(); - return; - } - - this.#ensureReadableStreamController(controller => { - for (const chunk of chunks) { - controller.write(chunk.chunk); - } - - callback(); - }); - } - - #ensureReadableStreamController(run) { - var thisController = this.#controller; - if (thisController) return run(thisController); - this.headersSent = true; - var firstWrite = this.#firstWrite; - this.#firstWrite = undefined; - this._reply( - new Response( - new ReadableStream({ - type: "direct", - pull: controller => { - this.#controller = controller; - if (firstWrite) controller.write(firstWrite); - firstWrite = undefined; - run(controller); - if (!this.#finished) { - return new Promise(resolve => { - this.#deferred = resolve; - }); - } - }, - }), - { - headers: this.#headers, - status: this.statusCode, - statusText: this.statusMessage ?? STATUS_CODES[this.statusCode], - }, - ), - ); - } - - _final(callback) { - if (!this.headersSent) { - var data = this.#firstWrite || ""; - this.#firstWrite = undefined; - this.#finished = true; - this._reply( - new Response(data, { - headers: this.#headers, - status: this.statusCode, - statusText: this.statusMessage ?? STATUS_CODES[this.statusCode], - }), - ); - callback && callback(); - return; - } - - this.#finished = true; - this.#ensureReadableStreamController(controller => { - controller.end(); - - callback(); - var deferred = this.#deferred; - if (deferred) { - this.#deferred = undefined; - deferred(); - } - }); - } - - writeProcessing() { - throw new Error("not implemented"); - } - - addTrailers(headers) { - throw new Error("not implemented"); - } - - assignSocket(socket) { - throw new Error("not implemented"); - } - - detachSocket(socket) { - throw new Error("not implemented"); - } - - writeContinue(callback) { - throw new Error("not implemented"); - } - - setTimeout(msecs, callback) { - throw new Error("not implemented"); - } - - get shouldKeepAlive() { - return true; - } - - get chunkedEncoding() { - return false; - } - - set chunkedEncoding(value) { - // throw new Error('not implemented'); - } - - set shouldKeepAlive(value) { - // throw new Error('not implemented'); - } - - get useChunkedEncodingByDefault() { - return true; - } - - set useChunkedEncodingByDefault(value) { - // throw new Error('not implemented'); - } - - appendHeader(name, value) { - var headers = (this.#headers ??= new Headers()); - headers.append(name, value); - } - - flushHeaders() {} - - getHeader(name) { - return getHeader(this.#headers, name); - } - - getHeaders() { - var headers = this.#headers; - if (!headers) return kEmptyObject; - return headers.toJSON(); - } - - getHeaderNames() { - var headers = this.#headers; - if (!headers) return []; - return Array.from(headers.keys()); - } - - removeHeader(name) { - if (!this.#headers) return; - this.#headers.delete(name); - } - - setHeader(name, value) { - var headers = (this.#headers ??= new Headers()); - headers.set(name, value); - return this; - } - - hasHeader(name) { - if (!this.#headers) return false; - return this.#headers.has(name); - } - - writeHead(statusCode, statusMessage, headers) { - _writeHead(statusCode, statusMessage, headers, this); - - return this; - } -} - -export class ClientRequest extends OutgoingMessage { - #timeout; - #res = null; - #upgradeOrConnect = false; - #parser = null; - #maxHeadersCount = null; - #reusedSocket = false; - #host; - #protocol; - #method; - #port; - #useDefaultPort; - #joinDuplicateHeaders; - #maxHeaderSize; - #agent = _globalAgent; - #path; - #socketPath; - - #body = null; - #fetchRequest; - #signal = null; - [kAbortController] = null; - #timeoutTimer = null; - #options; - #finished; - - get path() { - return this.#path; - } - - get port() { - return this.#port; - } - - get method() { - return this.#method; - } - - get host() { - return this.#host; - } - - get protocol() { - return this.#protocol; - } - - _write(chunk, encoding, callback) { - var body = this.#body; - if (!body) { - this.#body = chunk; - callback(); - return; - } - this.#body = body + chunk; - callback(); - } - - _writev(chunks, callback) { - var body = this.#body; - if (!body) { - this.#body = chunks.join(); - callback(); - return; - } - this.#body = body + chunks.join(); - callback(); - } - - _final(callback) { - this.#finished = true; - this[kAbortController] = new AbortController(); - this[kAbortController].signal.addEventListener("abort", () => { - this[kClearTimeout](); - }); - if (this.#signal?.aborted) { - this[kAbortController].abort(); - } - - var method = this.#method, - body = this.#body; - - try { - this.#fetchRequest = fetch( - `${this.#protocol}//${this.#host}${this.#useDefaultPort ? "" : ":" + this.#port}${this.#path}`, - { - method, - headers: this.getHeaders(), - body: body && method !== "GET" && method !== "HEAD" && method !== "OPTIONS" ? body : undefined, - redirect: "manual", - verbose: Boolean(__DEBUG__), - signal: this[kAbortController].signal, - }, - ) - .then(response => { - var res = (this.#res = new IncomingMessage(response, { - type: "response", - [kInternalRequest]: this, - })); - this.emit("response", res); - }) - .catch(err => { - if (__DEBUG__) globalReportError(err); - this.emit("error", err); - }) - .finally(() => { - this.#fetchRequest = null; - this[kClearTimeout](); - }); - } catch (err) { - if (__DEBUG__) globalReportError(err); - this.emit("error", err); - } finally { - callback(); - } - } - - get aborted() { - return this.#signal?.aborted || !!this[kAbortController]?.signal.aborted; - } - - abort() { - if (this.aborted) return; - this[kAbortController].abort(); - // TODO: Close stream if body streaming - } - - constructor(input, options, cb) { - super(); - - if (typeof input === "string") { - const urlStr = input; - try { - var urlObject = new URL(urlStr); - } catch (e) { - throw new TypeError(`Invalid URL: ${urlStr}`); - } - input = urlToHttpOptions(urlObject); - } else if (input && typeof input === "object" && input instanceof URL) { - // url.URL instance - input = urlToHttpOptions(input); - } else { - cb = options; - options = input; - input = null; - } - - if (typeof options === "function") { - cb = options; - options = input || kEmptyObject; - } else { - options = ObjectAssign(input || {}, options); - } - - var defaultAgent = options._defaultAgent || Agent.globalAgent; - - let protocol = options.protocol; - if (!protocol) { - if (options.port === 443) { - protocol = "https:"; - } else { - protocol = defaultAgent.protocol || "http:"; - } - this.#protocol = protocol; - } - - switch (this.#agent?.protocol) { - case undefined: { - break; - } - case "http:": { - if (protocol === "https:") { - defaultAgent = this.#agent = getDefaultHTTPSAgent(); - break; - } - } - case "https:": { - if (protocol === "https") { - defaultAgent = this.#agent = Agent.globalAgent; - break; - } - } - default: { - break; - } - } - - if (options.path) { - const path = String(options.path); - if (RegExpPrototypeExec.call(INVALID_PATH_REGEX, path) !== null) { - debug('Path contains unescaped characters: "%s"', path); - throw new Error("Path contains unescaped characters"); - // throw new ERR_UNESCAPED_CHARACTERS("Request path"); - } - } - - // Since we don't implement Agent, we don't need this - if (protocol !== "http:" && protocol !== "https:" && protocol) { - const expectedProtocol = defaultAgent?.protocol ?? "http:"; - throw new Error(`Protocol mismatch. Expected: ${expectedProtocol}. Got: ${protocol}`); - // throw new ERR_INVALID_PROTOCOL(protocol, expectedProtocol); - } - - const defaultPort = protocol === "https:" ? 443 : 80; - - this.#port = options.port || options.defaultPort || this.#agent?.defaultPort || defaultPort; - this.#useDefaultPort = this.#port === defaultPort; - const host = - (this.#host = - options.host = - validateHost(options.hostname, "hostname") || validateHost(options.host, "host") || "localhost"); - - // const setHost = options.setHost === undefined || Boolean(options.setHost); - - this.#socketPath = options.socketPath; - - if (options.timeout !== undefined) this.setTimeout(options.timeout, null); - - const signal = options.signal; - if (signal) { - //We still want to control abort function and timeout so signal call our AbortController - signal.addEventListener("abort", () => { - this[kAbortController]?.abort(); - }); - this.#signal = signal; - } - let method = options.method; - const methodIsString = typeof method === "string"; - if (method !== null && method !== undefined && !methodIsString) { - // throw new ERR_INVALID_ARG_TYPE("options.method", "string", method); - throw new Error("ERR_INVALID_ARG_TYPE: options.method"); - } - - if (methodIsString && method) { - if (!checkIsHttpToken(method)) { - // throw new ERR_INVALID_HTTP_TOKEN("Method", method); - throw new Error("ERR_INVALID_HTTP_TOKEN: Method"); - } - method = this.#method = StringPrototypeToUpperCase.call(method); - } else { - method = this.#method = "GET"; - } - - const _maxHeaderSize = options.maxHeaderSize; - // TODO: Validators - // if (maxHeaderSize !== undefined) - // validateInteger(maxHeaderSize, "maxHeaderSize", 0); - this.#maxHeaderSize = _maxHeaderSize; - - // const insecureHTTPParser = options.insecureHTTPParser; - // if (insecureHTTPParser !== undefined) { - // validateBoolean(insecureHTTPParser, 'options.insecureHTTPParser'); - // } - - // this.insecureHTTPParser = insecureHTTPParser; - var _joinDuplicateHeaders = options.joinDuplicateHeaders; - if (_joinDuplicateHeaders !== undefined) { - // TODO: Validators - // validateBoolean( - // options.joinDuplicateHeaders, - // "options.joinDuplicateHeaders", - // ); - } - - this.#joinDuplicateHeaders = _joinDuplicateHeaders; - - this.#path = options.path || "/"; - if (cb) { - this.once("response", cb); - } - - __DEBUG__ && - debug(`new ClientRequest: ${this.#method} ${this.#protocol}//${this.#host}:${this.#port}${this.#path}`); - - // if ( - // method === "GET" || - // method === "HEAD" || - // method === "DELETE" || - // method === "OPTIONS" || - // method === "TRACE" || - // method === "CONNECT" - // ) { - // this.useChunkedEncodingByDefault = false; - // } else { - // this.useChunkedEncodingByDefault = true; - // } - - this.#finished = false; - this.#res = null; - this.#upgradeOrConnect = false; - this.#parser = null; - this.#maxHeadersCount = null; - this.#reusedSocket = false; - this.#host = host; - this.#protocol = protocol; - this.#timeoutTimer = null; - const headersArray = ArrayIsArray(headers); - if (!headersArray) { - var headers = options.headers; - if (headers) { - for (let key in headers) { - this.setHeader(key, headers[key]); - } - } - - // if (host && !this.getHeader("host") && setHost) { - // let hostHeader = host; - - // // For the Host header, ensure that IPv6 addresses are enclosed - // // in square brackets, as defined by URI formatting - // // https://tools.ietf.org/html/rfc3986#section-3.2.2 - // const posColon = StringPrototypeIndexOf.call(hostHeader, ":"); - // if ( - // posColon !== -1 && - // StringPrototypeIncludes(hostHeader, ":", posColon + 1) && - // StringPrototypeCharCodeAt(hostHeader, 0) !== 91 /* '[' */ - // ) { - // hostHeader = `[${hostHeader}]`; - // } - - // if (port && +port !== defaultPort) { - // hostHeader += ":" + port; - // } - // this.setHeader("Host", hostHeader); - // } - - var auth = options.auth; - if (auth && !this.getHeader("Authorization")) { - this.setHeader("Authorization", "Basic " + Buffer.from(auth).toString("base64")); - } - - // if (this.getHeader("expect")) { - // if (this._header) { - // throw new ERR_HTTP_HEADERS_SENT("render"); - // } - - // this._storeHeader( - // this.method + " " + this.path + " HTTP/1.1\r\n", - // this[kOutHeaders], - // ); - // } - // } else { - // this._storeHeader( - // this.method + " " + this.path + " HTTP/1.1\r\n", - // options.headers, - // ); - } - - // this[kUniqueHeaders] = parseUniqueHeadersOption(options.uniqueHeaders); - - var optsWithoutSignal = options; - if (optsWithoutSignal.signal) { - optsWithoutSignal = ObjectAssign({}, options); - delete optsWithoutSignal.signal; - } - this.#options = optsWithoutSignal; - - var timeout = options.timeout; - if (timeout) { - this.setTimeout(timeout); - } - } - - setSocketKeepAlive(enable = true, initialDelay = 0) { - __DEBUG__ && debug(`${NODE_HTTP_WARNING}\n`, "WARN: ClientRequest.setSocketKeepAlive is a no-op"); - } - - setNoDelay(noDelay = true) { - __DEBUG__ && debug(`${NODE_HTTP_WARNING}\n`, "WARN: ClientRequest.setNoDelay is a no-op"); - } - [kClearTimeout]() { - if (this.#timeoutTimer) { - clearTimeout(this.#timeoutTimer); - this.#timeoutTimer = null; - } - } - - setTimeout(msecs, callback) { - if (this.#timeoutTimer) return this; - if (callback) { - this.on("timeout", callback); - } - - this.#timeoutTimer = setTimeout(async () => { - this.#timeoutTimer = null; - this[kAbortController]?.abort(); - this.emit("timeout"); - }, msecs); - - return this; - } -} - -function urlToHttpOptions(url) { - var { protocol, hostname, hash, search, pathname, href, port, username, password } = url; - return { - protocol, - hostname: - typeof hostname === "string" && StringPrototypeStartsWith.call(hostname, "[") - ? StringPrototypeSlice.call(hostname, 1, -1) - : hostname, - hash, - search, - pathname, - path: `${pathname || ""}${search || ""}`, - href, - port: port ? Number(port) : protocol === "https:" ? 443 : protocol === "http:" ? 80 : undefined, - auth: username || password ? `${decodeURIComponent(username)}:${decodeURIComponent(password)}` : undefined, - }; -} - -function validateHost(host, name) { - if (host !== null && host !== undefined && typeof host !== "string") { - // throw new ERR_INVALID_ARG_TYPE( - // `options.${name}`, - // ["string", "undefined", "null"], - // host, - // ); - throw new Error("Invalid arg type in options"); - } - return host; -} - -const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/; -/** - * Verifies that the given val is a valid HTTP token - * per the rules defined in RFC 7230 - * See https://tools.ietf.org/html/rfc7230#section-3.2.6 - */ -function checkIsHttpToken(val) { - return RegExpPrototypeExec.call(tokenRegExp, val) !== null; -} - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -export const METHODS = [ - "ACL", - "BIND", - "CHECKOUT", - "CONNECT", - "COPY", - "DELETE", - "GET", - "HEAD", - "LINK", - "LOCK", - "M-SEARCH", - "MERGE", - "MKACTIVITY", - "MKCALENDAR", - "MKCOL", - "MOVE", - "NOTIFY", - "OPTIONS", - "PATCH", - "POST", - "PROPFIND", - "PROPPATCH", - "PURGE", - "PUT", - "REBIND", - "REPORT", - "SEARCH", - "SOURCE", - "SUBSCRIBE", - "TRACE", - "UNBIND", - "UNLINK", - "UNLOCK", - "UNSUBSCRIBE", -]; - -export const STATUS_CODES = { - 100: "Continue", - 101: "Switching Protocols", - 102: "Processing", - 103: "Early Hints", - 200: "OK", - 201: "Created", - 202: "Accepted", - 203: "Non-Authoritative Information", - 204: "No Content", - 205: "Reset Content", - 206: "Partial Content", - 207: "Multi-Status", - 208: "Already Reported", - 226: "IM Used", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Found", - 303: "See Other", - 304: "Not Modified", - 305: "Use Proxy", - 307: "Temporary Redirect", - 308: "Permanent Redirect", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 409: "Conflict", - 410: "Gone", - 411: "Length Required", - 412: "Precondition Failed", - 413: "Payload Too Large", - 414: "URI Too Long", - 415: "Unsupported Media Type", - 416: "Range Not Satisfiable", - 417: "Expectation Failed", - 418: "I'm a Teapot", - 421: "Misdirected Request", - 422: "Unprocessable Entity", - 423: "Locked", - 424: "Failed Dependency", - 425: "Too Early", - 426: "Upgrade Required", - 428: "Precondition Required", - 429: "Too Many Requests", - 431: "Request Header Fields Too Large", - 451: "Unavailable For Legal Reasons", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Gateway Timeout", - 505: "HTTP Version Not Supported", - 506: "Variant Also Negotiates", - 507: "Insufficient Storage", - 508: "Loop Detected", - 509: "Bandwidth Limit Exceeded", - 510: "Not Extended", - 511: "Network Authentication Required", -}; - -function _normalizeArgs(args) { - let arr; - - if (args.length === 0) { - arr = [{}, null]; - // arr[normalizedArgsSymbol] = true; - return arr; - } - - const arg0 = args[0]; - let options = {}; - if (typeof arg0 === "object" && arg0 !== null) { - // (options[...][, cb]) - options = arg0; - // } else if (isPipeName(arg0)) { - // (path[...][, cb]) - // options.path = arg0; - } else { - // ([port][, host][...][, cb]) - options.port = arg0; - if (args.length > 1 && typeof args[1] === "string") { - options.host = args[1]; - } - } - - const cb = args[args.length - 1]; - if (typeof cb !== "function") arr = [options, null]; - else arr = [options, cb]; - - // arr[normalizedArgsSymbol] = true; - return arr; -} - -function _writeHead(statusCode, reason, obj, response) { - statusCode |= 0; - if (statusCode < 100 || statusCode > 999) { - throw new Error("status code must be between 100 and 999"); - } - - if (typeof reason === "string") { - // writeHead(statusCode, reasonPhrase[, headers]) - response.statusMessage = reason; - } else { - // writeHead(statusCode[, headers]) - if (!response.statusMessage) response.statusMessage = STATUS_CODES[statusCode] || "unknown"; - obj = reason; - } - response.statusCode = statusCode; - - { - // Slow-case: when progressive API and header fields are passed. - let k; - if (Array.isArray(obj)) { - if (obj.length % 2 !== 0) { - throw new Error("raw headers must have an even number of elements"); - } - - for (let n = 0; n < obj.length; n += 2) { - k = obj[n + 0]; - if (k) response.setHeader(k, obj[n + 1]); - } - } else if (obj) { - const keys = Object.keys(obj); - // Retain for(;;) loop for performance reasons - // Refs: https://github.com/nodejs/node/pull/30958 - for (let i = 0; i < keys.length; i++) { - k = keys[i]; - if (k) response.setHeader(k, obj[k]); - } - } - } -} - -/** - * Makes an HTTP request. - * @param {string | URL} url - * @param {HTTPRequestOptions} [options] - * @param {Function} [cb] - * @returns {ClientRequest} - */ -export function request(url, options, cb) { - return new ClientRequest(url, options, cb); -} - -/** - * Makes a `GET` HTTP request. - * @param {string | URL} url - * @param {HTTPRequestOptions} [options] - * @param {Function} [cb] - * @returns {ClientRequest} - */ -export function get(url, options, cb) { - const req = request(url, options, cb); - req.end(); - return req; -} -_globalAgent ??= new Agent(); -var defaultObject = { - Agent, - Server, - METHODS, - STATUS_CODES, - createServer, - ServerResponse, - IncomingMessage, - request, - get, - maxHeaderSize: 16384, - // validateHeaderName, - // validateHeaderValue, - setMaxIdleHTTPParsers(max) { - debug(`${NODE_HTTP_WARNING}\n`, "setMaxIdleHTTPParsers() is a no-op"); - }, - get globalAgent() { - return _globalAgent; - }, - set globalAgent(agent) {}, - [Symbol.for("CommonJS")]: 0, -}; - -export default defaultObject; - -export { _globalAgent as globalAgent }; diff --git a/src/js/node/http.ts b/src/js/node/http.ts new file mode 100644 index 000000000..5f21a791c --- /dev/null +++ b/src/js/node/http.ts @@ -0,0 +1,1810 @@ +// Hardcoded module "node:http" +import { EventEmitter } from "node:events"; +import { Readable, Writable, Duplex } from "node:stream"; +import { isTypedArray } from "util/types"; + +const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/; +/** + * True if val contains an invalid field-vchar + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + */ +function checkInvalidHeaderChar(val: string) { + return RegExpPrototypeExec.call(headerCharRegex, val) !== null; +} + +export const validateHeaderName = (name, label) => { + if (typeof name !== "string" || !name || !checkIsHttpToken(name)) { + // throw new ERR_INVALID_HTTP_TOKEN(label || "Header name", name); + throw new Error("ERR_INVALID_HTTP_TOKEN"); + } +}; + +export const validateHeaderValue = (name, value) => { + if (value === undefined) { + // throw new ERR_HTTP_INVALID_HEADER_VALUE(value, name); + throw new Error("ERR_HTTP_INVALID_HEADER_VALUE"); + } + if (checkInvalidHeaderChar(value)) { + // throw new ERR_INVALID_CHAR("header content", name); + throw new Error("ERR_INVALID_CHAR"); + } +}; + +// Cheaper to duplicate this than to import it from node:net +function isIPv6(input) { + const v4Seg = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; + const v4Str = `(${v4Seg}[.]){3}${v4Seg}`; + const v6Seg = "(?:[0-9a-fA-F]{1,4})"; + const IPv6Reg = new RegExp( + "^(" + + `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` + + `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` + + `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` + + `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` + + `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` + + `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` + + `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` + + `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` + + ")(%[0-9a-zA-Z-.:]{1,})?$", + ); + + return IPv6Reg.test(input); +} + +// TODO: add primordial for URL +// Importing from node:url is unnecessary +const { URL } = globalThis; + +const { newArrayWithSize, String, Object, Array } = globalThis[Symbol.for("Bun.lazy")]("primordials"); + +const globalReportError = globalThis.reportError; +const setTimeout = globalThis.setTimeout; +const fetch = Bun.fetch; +const nop = () => {}; + +const __DEBUG__ = process.env.__DEBUG__; +const debug = __DEBUG__ ? (...args) => console.log("node:http", ...args) : nop; + +const kEmptyObject = Object.freeze(Object.create(null)); +const kOutHeaders = Symbol.for("kOutHeaders"); +const kEndCalled = Symbol.for("kEndCalled"); +const kAbortController = Symbol.for("kAbortController"); +const kClearTimeout = Symbol("kClearTimeout"); + +const kCorked = Symbol.for("kCorked"); +const searchParamsSymbol = Symbol.for("query"); // This is the symbol used in Node + +// Primordials +const StringPrototypeSlice = String.prototype.slice; +const StringPrototypeStartsWith = String.prototype.startsWith; +const StringPrototypeToUpperCase = String.prototype.toUpperCase; +const StringPrototypeIncludes = String.prototype.includes; +const StringPrototypeCharCodeAt = String.prototype.charCodeAt; +const StringPrototypeIndexOf = String.prototype.indexOf; +const ArrayIsArray = Array.isArray; +const RegExpPrototypeExec = RegExp.prototype.exec; +const ObjectAssign = Object.assign; +const ObjectPrototypeHasOwnProperty = Object.prototype.hasOwnProperty; + +const INVALID_PATH_REGEX = /[^\u0021-\u00ff]/; +const NODE_HTTP_WARNING = + "WARN: Agent is mostly unused in Bun's implementation of http. If you see strange behavior, this is probably the cause."; + +var _defaultHTTPSAgent; +var kInternalRequest = Symbol("kInternalRequest"); +var kInternalSocketData = Symbol.for("::bunternal::"); + +const kEmptyBuffer = Buffer.alloc(0); + +function isValidTLSArray(obj) { + if (typeof obj === "string" || isTypedArray(obj) || obj instanceof ArrayBuffer || obj instanceof Blob) return true; + if (Array.isArray(obj)) { + for (var i = 0; i < obj.length; i++) { + if (typeof obj !== "string" && !isTypedArray(obj) && !(obj instanceof ArrayBuffer) && !(obj instanceof Blob)) + return false; + } + return true; + } +} + +function getHeader(headers, name) { + if (!headers) return; + const result = headers.get(name); + return result == null ? undefined : result; +} + +type FakeSocket = InstanceType; +var FakeSocket = class Socket extends Duplex { + bytesRead = 0; + bytesWritten = 0; + connecting = false; + remoteAddress: string | null = null; + remotePort; + timeout = 0; + + isServer = false; + + address() { + return { + address: this.localAddress, + family: this.localFamily, + port: this.localPort, + }; + } + + get bufferSize() { + return this.writableLength; + } + + connect(port, host, connectListener) { + return this; + } + + _destroy(err, callback) {} + + _final(callback) {} + + get localAddress() { + return "127.0.0.1"; + } + + get localFamily() { + return "IPv4"; + } + + get localPort() { + return 80; + } + + get pending() { + return this.connecting; + } + + _read(size) {} + + get readyState() { + if (this.connecting) return "opening"; + if (this.readable) { + return this.writable ? "open" : "readOnly"; + } else { + return this.writable ? "writeOnly" : "closed"; + } + } + + ref() {} + + get remoteFamily() { + return "IPv4"; + } + + resetAndDestroy() {} + + setKeepAlive(enable = false, initialDelay = 0) {} + + setNoDelay(noDelay = true) { + return this; + } + + setTimeout(timeout, callback) { + return this; + } + + unref() {} + + _write(chunk, encoding, callback) {} +}; + +export function createServer(options, callback) { + return new Server(options, callback); +} + +export class Agent extends EventEmitter { + defaultPort = 80; + protocol = "http:"; + options; + requests; + sockets; + freeSockets; + + keepAliveMsecs; + keepAlive; + maxSockets; + maxFreeSockets; + scheduling; + maxTotalSockets; + totalSocketCount; + + #fakeSocket; + + static get globalAgent() { + return globalAgent; + } + + static get defaultMaxSockets() { + return Infinity; + } + + constructor(options = kEmptyObject) { + super(); + this.options = options = { ...options, path: null }; + if (options.noDelay === undefined) options.noDelay = true; + + // Don't confuse net and make it think that we're connecting to a pipe + this.requests = kEmptyObject; + this.sockets = kEmptyObject; + this.freeSockets = kEmptyObject; + + this.keepAliveMsecs = options.keepAliveMsecs || 1000; + this.keepAlive = options.keepAlive || false; + this.maxSockets = options.maxSockets || Agent.defaultMaxSockets; + this.maxFreeSockets = options.maxFreeSockets || 256; + this.scheduling = options.scheduling || "lifo"; + this.maxTotalSockets = options.maxTotalSockets; + this.totalSocketCount = 0; + this.defaultPort = options.defaultPort || 80; + this.protocol = options.protocol || "http:"; + } + + createConnection() { + debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.createConnection is a no-op, returns fake socket"); + return (this.#fakeSocket ??= new FakeSocket()); + } + + getName(options = kEmptyObject) { + let name = `http:${options.host || "localhost"}:`; + if (options.port) name += options.port; + name += ":"; + if (options.localAddress) name += options.localAddress; + // Pacify parallel/test-http-agent-getname by only appending + // the ':' when options.family is set. + if (options.family === 4 || options.family === 6) name += `:${options.family}`; + if (options.socketPath) name += `:${options.socketPath}`; + return name; + } + + addRequest() { + debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.addRequest is a no-op"); + } + + createSocket(req, options, cb) { + debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.createSocket returns fake socket"); + cb(null, (this.#fakeSocket ??= new FakeSocket())); + } + + removeSocket() { + debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.removeSocket is a no-op"); + } + + keepSocketAlive() { + debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.keepSocketAlive is a no-op"); + + return true; + } + + reuseSocket() { + debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.reuseSocket is a no-op"); + } + + destroy() { + debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.destroy is a no-op"); + } +} +function emitListeningNextTick(self, onListen, err, hostname, port) { + if (typeof onListen === "function") { + try { + onListen(err, hostname, port); + } catch (err) { + self.emit("error", err); + } + } + + self.listening = !err; + + if (err) { + self.emit("error", err); + } else { + self.emit("listening", hostname, port); + } +} + +export class Server extends EventEmitter { + #server; + #options; + #tls; + #is_tls = false; + listening = false; + serverName; + + constructor(options, callback) { + super(); + + if (typeof options === "function") { + callback = options; + options = {}; + } else if (options == null || typeof options === "object") { + options = { ...options }; + this.#tls = null; + let key = options.key; + if (key) { + if (!isValidTLSArray(key)) { + throw new TypeError( + "key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", + ); + } + this.#is_tls = true; + } + let cert = options.cert; + if (cert) { + if (!isValidTLSArray(cert)) { + throw new TypeError( + "cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", + ); + } + this.#is_tls = true; + } + + let ca = options.ca; + if (ca) { + if (!isValidTLSArray(ca)) { + throw new TypeError( + "ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", + ); + } + this.#is_tls = true; + } + let passphrase = options.passphrase; + if (passphrase && typeof passphrase !== "string") { + throw new TypeError("passphrase argument must be an string"); + } + + let serverName = options.servername; + if (serverName && typeof serverName !== "string") { + throw new TypeError("servername argument must be an string"); + } + + let secureOptions = options.secureOptions || 0; + if (secureOptions && typeof secureOptions !== "number") { + throw new TypeError("secureOptions argument must be an number"); + } + + if (this.#is_tls) { + this.#tls = { + serverName, + key: key, + cert: cert, + ca: ca, + passphrase: passphrase, + secureOptions: secureOptions, + }; + } else { + this.#tls = null; + } + } else { + throw new Error("bun-http-polyfill: invalid arguments"); + } + + this.#options = options; + + if (callback) this.on("request", callback); + } + + closeAllConnections() { + const server = this.#server; + if (!server) { + return; + } + this.#server = undefined; + server.stop(true); + this.emit("close"); + } + + closeIdleConnections() { + // not actually implemented + } + + close(optionalCallback?) { + const server = this.#server; + if (!server) { + if (typeof optionalCallback === "function") + process.nextTick(optionalCallback, new Error("Server is not running")); + return; + } + this.#server = undefined; + if (typeof optionalCallback === "function") this.once("close", optionalCallback); + server.stop(); + this.emit("close"); + } + + address() { + if (!this.#server) return null; + + const address = this.#server.hostname; + return { + address, + family: isIPv6(address) ? "IPv6" : "IPv4", + port: this.#server.port, + }; + } + + listen(port, host, backlog, onListen) { + const server = this; + if (typeof host === "function") { + onListen = host; + host = undefined; + } + + if (typeof port === "function") { + onListen = port; + } else if (typeof port === "object") { + port?.signal?.addEventListener("abort", () => { + this.close(); + }); + + host = port?.host; + port = port?.port; + + if (typeof port?.callback === "function") onListen = port?.callback; + } + + if (typeof backlog === "function") { + onListen = backlog; + } + + const ResponseClass = this.#options.ServerResponse || ServerResponse; + const RequestClass = this.#options.IncomingMessage || IncomingMessage; + + try { + const tls = this.#tls; + if (tls) { + this.serverName = tls.serverName || host || "localhost"; + } + this.#server = Bun.serve({ + tls, + port, + hostname: host, + // Bindings to be used for WS Server + websocket: { + open(ws) { + ws.data.open(ws); + }, + message(ws, message) { + ws.data.message(ws, message); + }, + close(ws, code, reason) { + ws.data.close(ws, code, reason); + }, + drain(ws) { + ws.data.drain(ws); + }, + }, + fetch(req, _server) { + var pendingResponse; + var pendingError; + var rejectFunction, resolveFunction; + var reject = err => { + if (pendingError) return; + pendingError = err; + if (rejectFunction) rejectFunction(err); + }; + + var reply = function (resp) { + if (pendingResponse) return; + pendingResponse = resp; + if (resolveFunction) resolveFunction(resp); + }; + + const http_req = new RequestClass(req); + const http_res = new ResponseClass({ reply, req: http_req }); + + http_req.once("error", err => reject(err)); + http_res.once("error", err => reject(err)); + + const upgrade = req.headers.get("upgrade"); + if (upgrade) { + const socket = new FakeSocket(); + socket[kInternalSocketData] = [_server, http_res, req]; + server.emit("upgrade", http_req, socket, kEmptyBuffer); + } else { + server.emit("request", http_req, http_res); + } + + if (pendingError) { + throw pendingError; + } + + if (pendingResponse) { + return pendingResponse; + } + + return new Promise((resolve, reject) => { + resolveFunction = resolve; + rejectFunction = reject; + }); + }, + }); + setTimeout(emitListeningNextTick, 1, this, onListen, null, this.#server.hostname, this.#server.port); + } catch (err) { + setTimeout(emitListeningNextTick, 1, this, onListen, err); + } + + return this; + } + setTimeout(msecs, callback) {} +} + +function assignHeaders(object, req) { + var headers = req.headers.toJSON(); + const rawHeaders = newArrayWithSize(req.headers.count * 2); + var i = 0; + for (const key in headers) { + rawHeaders[i++] = key; + rawHeaders[i++] = headers[key]; + } + object.headers = headers; + object.rawHeaders = rawHeaders; +} +function destroyBodyStreamNT(bodyStream) { + bodyStream.destroy(); +} + +var defaultIncomingOpts = { type: "request" }; + +function getDefaultHTTPSAgent() { + return (_defaultHTTPSAgent ??= new Agent({ defaultPort: 443, protocol: "https:" })); +} + +export class IncomingMessage extends Readable { + method: string; + complete: boolean; + + constructor(req, defaultIncomingOpts) { + const method = req.method; + + super(); + + const url = new URL(req.url); + + var { type = "request", [kInternalRequest]: nodeReq } = defaultIncomingOpts || {}; + + this.#noBody = + type === "request" // TODO: Add logic for checking for body on response + ? "GET" === method || + "HEAD" === method || + "TRACE" === method || + "CONNECT" === method || + "OPTIONS" === method || + (parseInt(req.headers.get("Content-Length") || "") || 0) === 0 + : false; + + this.#req = req; + this.method = method; + this.#type = type; + this.complete = !!this.#noBody; + + this.#bodyStream = undefined; + const socket = new FakeSocket(); + socket.remoteAddress = url.hostname; + socket.remotePort = url.port; + this.#fakeSocket = socket; + + this.url = url.pathname + url.search; + this.#nodeReq = nodeReq; + assignHeaders(this, req); + } + + headers; + rawHeaders; + _consuming = false; + _dumped = false; + #bodyStream: ReadableStreamDefaultReader | undefined; + #fakeSocket: FakeSocket | undefined; + #noBody = false; + #aborted = false; + #req; + url; + #type; + #nodeReq; + + get req() { + return this.#nodeReq; + } + + _construct(callback) { + // TODO: streaming + if (this.#type === "response" || this.#noBody) { + callback(); + return; + } + + const contentLength = this.#req.headers.get("content-length"); + const length = contentLength ? parseInt(contentLength, 10) : 0; + if (length === 0) { + this.#noBody = true; + callback(); + return; + } + + callback(); + } + + async #consumeStream(reader: ReadableStreamDefaultReader) { + while (true) { + var { done, value } = await reader.readMany(); + if (this.#aborted) return; + if (done) { + this.push(null); + this.destroy(); + break; + } + for (var v of value) { + this.push(v); + } + } + } + + _read(size) { + if (this.#noBody) { + this.push(null); + this.complete = true; + } else if (this.#bodyStream == null) { + const reader = this.#req.body?.getReader() as ReadableStreamDefaultReader; + if (!reader) { + this.push(null); + return; + } + this.#bodyStream = reader; + this.#consumeStream(reader); + } + } + + get aborted() { + return this.#aborted; + } + + #abort() { + if (this.#aborted) return; + this.#aborted = true; + var bodyStream = this.#bodyStream; + if (!bodyStream) return; + bodyStream.cancel(); + this.complete = true; + this.#bodyStream = undefined; + this.push(null); + } + + get connection() { + return this.#fakeSocket; + } + + get statusCode() { + return this.#req.status; + } + + get statusMessage() { + return STATUS_CODES[this.#req.status]; + } + + get httpVersion() { + return "1.1"; + } + + get rawTrailers() { + return []; + } + + get httpVersionMajor() { + return 1; + } + + get httpVersionMinor() { + return 1; + } + + get trailers() { + return kEmptyObject; + } + + get socket() { + return (this.#fakeSocket ??= new FakeSocket()); + } + + set socket(val) { + this.#fakeSocket = val; + } + + setTimeout(msecs, callback) { + throw new Error("not implemented"); + } +} + +function emitErrorNt(msg, err, callback) { + callback(err); + if (typeof msg.emit === "function" && !msg._closed) { + msg.emit("error", err); + } +} + +function onError(self, err, cb) { + process.nextTick(() => emitErrorNt(self, err, cb)); +} + +function write_(msg, chunk, encoding, callback, fromEnd) { + if (typeof callback !== "function") callback = nop; + + let len; + if (chunk === null) { + // throw new ERR_STREAM_NULL_VALUES(); + throw new Error("ERR_STREAM_NULL_VALUES"); + } else if (typeof chunk === "string") { + len = Buffer.byteLength(chunk, encoding); + } else { + throw new Error("Invalid arg type for chunk"); + // throw new ERR_INVALID_ARG_TYPE( + // "chunk", + // ["string", "Buffer", "Uint8Array"], + // chunk, + // ); + } + + let err; + if (msg.finished) { + // err = new ERR_STREAM_WRITE_AFTER_END(); + err = new Error("ERR_STREAM_WRITE_AFTER_END"); + } else if (msg.destroyed) { + // err = new ERR_STREAM_DESTROYED("write"); + err = new Error("ERR_STREAM_DESTROYED"); + } + + if (err) { + if (!msg.destroyed) { + onError(msg, err, callback); + } else { + process.nextTick(callback, err); + } + return false; + } + + if (!msg._header) { + if (fromEnd) { + msg._contentLength = len; + } + // msg._implicitHeader(); + } + + if (!msg._hasBody) { + debug("This type of response MUST NOT have a body. " + "Ignoring write() calls."); + process.nextTick(callback); + return true; + } + + // if (!fromEnd && msg.socket && !msg.socket.writableCorked) { + // msg.socket.cork(); + // process.nextTick(connectionCorkNT, msg.socket); + // } + + return true; +} + +export class OutgoingMessage extends Writable { + #headers; + headersSent = false; + sendDate = true; + req; + + #finished = false; + [kEndCalled] = false; + + #fakeSocket; + #timeoutTimer: Timer | null = null; + [kAbortController]: AbortController | null = null; + + // Express "compress" package uses this + _implicitHeader() {} + + // For compat with IncomingRequest + get headers() { + if (!this.#headers) return kEmptyObject; + return this.#headers.toJSON(); + } + + get shouldKeepAlive() { + return true; + } + + get chunkedEncoding() { + return false; + } + + set chunkedEncoding(value) { + // throw new Error('not implemented'); + } + + set shouldKeepAlive(value) { + // throw new Error('not implemented'); + } + + get useChunkedEncodingByDefault() { + return true; + } + + set useChunkedEncodingByDefault(value) { + // throw new Error('not implemented'); + } + + get socket() { + return (this.#fakeSocket ??= new FakeSocket()); + } + + set socket(val) { + this.#fakeSocket = val; + } + + get connection() { + return this.socket; + } + + get finished() { + return this.#finished; + } + + appendHeader(name, value) { + var headers = (this.#headers ??= new Headers()); + headers.append(name, value); + } + + flushHeaders() {} + + getHeader(name) { + return getHeader(this.#headers, name); + } + + getHeaders() { + if (!this.#headers) return kEmptyObject; + return this.#headers.toJSON(); + } + + getHeaderNames() { + var headers = this.#headers; + if (!headers) return []; + return Array.from(headers.keys()); + } + + removeHeader(name) { + if (!this.#headers) return; + this.#headers.delete(name); + } + + setHeader(name, value) { + var headers = (this.#headers ??= new Headers()); + headers.set(name, value); + return this; + } + + hasHeader(name) { + if (!this.#headers) return false; + return this.#headers.has(name); + } + + addTrailers(headers) { + throw new Error("not implemented"); + } + + [kClearTimeout]() { + if (this.#timeoutTimer) { + clearTimeout(this.#timeoutTimer); + this.#timeoutTimer = null; + } + } + + setTimeout(msecs, callback) { + if (this.#timeoutTimer) return this; + if (callback) { + this.on("timeout", callback); + } + + this.#timeoutTimer = setTimeout(async () => { + this.#timeoutTimer = null; + this[kAbortController]?.abort(); + this.emit("timeout"); + }, msecs); + + return this; + } +} + +export class ServerResponse extends Writable { + declare _writableState: any; + + constructor({ req, reply }) { + super(); + this.req = req; + this._reply = reply; + this.sendDate = true; + this.statusCode = 200; + this.headersSent = false; + this.statusMessage = undefined; + this.#controller = undefined; + this.#firstWrite = undefined; + this._writableState.decodeStrings = false; + this.#deferred = undefined; + } + + req; + _reply; + sendDate; + statusCode; + #headers; + headersSent = false; + statusMessage; + #controller; + #firstWrite; + _sent100 = false; + _defaultKeepAlive = false; + _removedConnection = false; + _removedContLen = false; + #deferred: (() => void) | undefined = undefined; + #finished = false; + + // Express "compress" package uses this + _implicitHeader() {} + + _write(chunk, encoding, callback) { + if (!this.#firstWrite && !this.headersSent) { + this.#firstWrite = chunk; + callback(); + return; + } + + this.#ensureReadableStreamController(controller => { + controller.write(chunk); + callback(); + }); + } + + _writev(chunks, callback) { + if (chunks.length === 1 && !this.headersSent && !this.#firstWrite) { + this.#firstWrite = chunks[0].chunk; + callback(); + return; + } + + this.#ensureReadableStreamController(controller => { + for (const chunk of chunks) { + controller.write(chunk.chunk); + } + + callback(); + }); + } + + #ensureReadableStreamController(run) { + var thisController = this.#controller; + if (thisController) return run(thisController); + this.headersSent = true; + var firstWrite = this.#firstWrite; + this.#firstWrite = undefined; + this._reply( + new Response( + new ReadableStream({ + type: "direct", + pull: controller => { + this.#controller = controller; + if (firstWrite) controller.write(firstWrite); + firstWrite = undefined; + run(controller); + if (!this.#finished) { + return new Promise(resolve => { + this.#deferred = resolve; + }); + } + }, + }), + { + headers: this.#headers, + status: this.statusCode, + statusText: this.statusMessage ?? STATUS_CODES[this.statusCode], + }, + ), + ); + } + + _final(callback) { + if (!this.headersSent) { + var data = this.#firstWrite || ""; + this.#firstWrite = undefined; + this.#finished = true; + this._reply( + new Response(data, { + headers: this.#headers, + status: this.statusCode, + statusText: this.statusMessage ?? STATUS_CODES[this.statusCode], + }), + ); + callback && callback(); + return; + } + + this.#finished = true; + this.#ensureReadableStreamController(controller => { + controller.end(); + + callback(); + var deferred = this.#deferred; + if (deferred) { + this.#deferred = undefined; + deferred(); + } + }); + } + + writeProcessing() { + throw new Error("not implemented"); + } + + addTrailers(headers) { + throw new Error("not implemented"); + } + + assignSocket(socket) { + throw new Error("not implemented"); + } + + detachSocket(socket) { + throw new Error("not implemented"); + } + + writeContinue(callback) { + throw new Error("not implemented"); + } + + setTimeout(msecs, callback) { + throw new Error("not implemented"); + } + + get shouldKeepAlive() { + return true; + } + + get chunkedEncoding() { + return false; + } + + set chunkedEncoding(value) { + // throw new Error('not implemented'); + } + + set shouldKeepAlive(value) { + // throw new Error('not implemented'); + } + + get useChunkedEncodingByDefault() { + return true; + } + + set useChunkedEncodingByDefault(value) { + // throw new Error('not implemented'); + } + + appendHeader(name, value) { + var headers = (this.#headers ??= new Headers()); + headers.append(name, value); + } + + flushHeaders() {} + + getHeader(name) { + return getHeader(this.#headers, name); + } + + getHeaders() { + var headers = this.#headers; + if (!headers) return kEmptyObject; + return headers.toJSON(); + } + + getHeaderNames() { + var headers = this.#headers; + if (!headers) return []; + return Array.from(headers.keys()); + } + + removeHeader(name) { + if (!this.#headers) return; + this.#headers.delete(name); + } + + setHeader(name, value) { + var headers = (this.#headers ??= new Headers()); + headers.set(name, value); + return this; + } + + hasHeader(name) { + if (!this.#headers) return false; + return this.#headers.has(name); + } + + writeHead(statusCode, statusMessage, headers) { + _writeHead(statusCode, statusMessage, headers, this); + + return this; + } +} + +export class ClientRequest extends OutgoingMessage { + #timeout; + #res: IncomingMessage | null = null; + #upgradeOrConnect = false; + #parser = null; + #maxHeadersCount = null; + #reusedSocket = false; + #host; + #protocol; + #method; + #port; + #useDefaultPort; + #joinDuplicateHeaders; + #maxHeaderSize; + #agent = globalAgent; + #path; + #socketPath; + + #body: string | null = null; + #fetchRequest; + #signal: AbortSignal | null = null; + [kAbortController]: AbortController | null = null; + #timeoutTimer: Timer | null = null; + #options; + #finished; + + get path() { + return this.#path; + } + + get port() { + return this.#port; + } + + get method() { + return this.#method; + } + + get host() { + return this.#host; + } + + get protocol() { + return this.#protocol; + } + + _write(chunk, encoding, callback) { + var body = this.#body; + if (!body) { + this.#body = chunk; + callback(); + return; + } + this.#body = body + chunk; + callback(); + } + + _writev(chunks, callback) { + var body = this.#body; + if (!body) { + this.#body = chunks.join(); + callback(); + return; + } + this.#body = body + chunks.join(); + callback(); + } + + _final(callback) { + this.#finished = true; + this[kAbortController] = new AbortController(); + this[kAbortController].signal.addEventListener("abort", () => { + this[kClearTimeout](); + }); + if (this.#signal?.aborted) { + this[kAbortController].abort(); + } + + var method = this.#method, + body = this.#body; + + try { + this.#fetchRequest = fetch( + `${this.#protocol}//${this.#host}${this.#useDefaultPort ? "" : ":" + this.#port}${this.#path}`, + { + method, + headers: this.getHeaders(), + body: body && method !== "GET" && method !== "HEAD" && method !== "OPTIONS" ? body : undefined, + redirect: "manual", + verbose: Boolean(__DEBUG__), + signal: this[kAbortController].signal, + }, + ) + .then(response => { + var res = (this.#res = new IncomingMessage(response, { + type: "response", + [kInternalRequest]: this, + })); + this.emit("response", res); + }) + .catch(err => { + if (__DEBUG__) globalReportError(err); + this.emit("error", err); + }) + .finally(() => { + this.#fetchRequest = null; + this[kClearTimeout](); + }); + } catch (err) { + if (__DEBUG__) globalReportError(err); + this.emit("error", err); + } finally { + callback(); + } + } + + get aborted() { + return this.#signal?.aborted || !!this[kAbortController]?.signal.aborted; + } + + abort() { + if (this.aborted) return; + this[kAbortController]!.abort(); + // TODO: Close stream if body streaming + } + + constructor(input, options, cb) { + super(); + + if (typeof input === "string") { + const urlStr = input; + try { + var urlObject = new URL(urlStr); + } catch (e) { + throw new TypeError(`Invalid URL: ${urlStr}`); + } + input = urlToHttpOptions(urlObject); + } else if (input && typeof input === "object" && input instanceof URL) { + // url.URL instance + input = urlToHttpOptions(input); + } else { + cb = options; + options = input; + input = null; + } + + if (typeof options === "function") { + cb = options; + options = input || kEmptyObject; + } else { + options = ObjectAssign(input || {}, options); + } + + var defaultAgent = options._defaultAgent || Agent.globalAgent; + + let protocol = options.protocol; + if (!protocol) { + if (options.port === 443) { + protocol = "https:"; + } else { + protocol = defaultAgent.protocol || "http:"; + } + } + this.#protocol = protocol; + + switch (this.#agent?.protocol) { + case undefined: { + break; + } + case "http:": { + if (protocol === "https:") { + defaultAgent = this.#agent = getDefaultHTTPSAgent(); + break; + } + } + case "https:": { + if (protocol === "https") { + defaultAgent = this.#agent = Agent.globalAgent; + break; + } + } + default: { + break; + } + } + + if (options.path) { + const path = String(options.path); + if (RegExpPrototypeExec.call(INVALID_PATH_REGEX, path) !== null) { + debug('Path contains unescaped characters: "%s"', path); + throw new Error("Path contains unescaped characters"); + // throw new ERR_UNESCAPED_CHARACTERS("Request path"); + } + } + + // Since we don't implement Agent, we don't need this + if (protocol !== "http:" && protocol !== "https:" && protocol) { + const expectedProtocol = defaultAgent?.protocol ?? "http:"; + throw new Error(`Protocol mismatch. Expected: ${expectedProtocol}. Got: ${protocol}`); + // throw new ERR_INVALID_PROTOCOL(protocol, expectedProtocol); + } + + const defaultPort = protocol === "https:" ? 443 : 80; + + this.#port = options.port || options.defaultPort || this.#agent?.defaultPort || defaultPort; + this.#useDefaultPort = this.#port === defaultPort; + const host = + (this.#host = + options.host = + validateHost(options.hostname, "hostname") || validateHost(options.host, "host") || "localhost"); + + // const setHost = options.setHost === undefined || Boolean(options.setHost); + + this.#socketPath = options.socketPath; + + if (options.timeout !== undefined) this.setTimeout(options.timeout, null); + + const signal = options.signal; + if (signal) { + //We still want to control abort function and timeout so signal call our AbortController + signal.addEventListener("abort", () => { + this[kAbortController]?.abort(); + }); + this.#signal = signal; + } + let method = options.method; + const methodIsString = typeof method === "string"; + if (method !== null && method !== undefined && !methodIsString) { + // throw new ERR_INVALID_ARG_TYPE("options.method", "string", method); + throw new Error("ERR_INVALID_ARG_TYPE: options.method"); + } + + if (methodIsString && method) { + if (!checkIsHttpToken(method)) { + // throw new ERR_INVALID_HTTP_TOKEN("Method", method); + throw new Error("ERR_INVALID_HTTP_TOKEN: Method"); + } + method = this.#method = StringPrototypeToUpperCase.call(method); + } else { + method = this.#method = "GET"; + } + + const _maxHeaderSize = options.maxHeaderSize; + // TODO: Validators + // if (maxHeaderSize !== undefined) + // validateInteger(maxHeaderSize, "maxHeaderSize", 0); + this.#maxHeaderSize = _maxHeaderSize; + + // const insecureHTTPParser = options.insecureHTTPParser; + // if (insecureHTTPParser !== undefined) { + // validateBoolean(insecureHTTPParser, 'options.insecureHTTPParser'); + // } + + // this.insecureHTTPParser = insecureHTTPParser; + var _joinDuplicateHeaders = options.joinDuplicateHeaders; + if (_joinDuplicateHeaders !== undefined) { + // TODO: Validators + // validateBoolean( + // options.joinDuplicateHeaders, + // "options.joinDuplicateHeaders", + // ); + } + + this.#joinDuplicateHeaders = _joinDuplicateHeaders; + + this.#path = options.path || "/"; + if (cb) { + this.once("response", cb); + } + + __DEBUG__ && + debug(`new ClientRequest: ${this.#method} ${this.#protocol}//${this.#host}:${this.#port}${this.#path}`); + + // if ( + // method === "GET" || + // method === "HEAD" || + // method === "DELETE" || + // method === "OPTIONS" || + // method === "TRACE" || + // method === "CONNECT" + // ) { + // this.useChunkedEncodingByDefault = false; + // } else { + // this.useChunkedEncodingByDefault = true; + // } + + this.#finished = false; + this.#res = null; + this.#upgradeOrConnect = false; + this.#parser = null; + this.#maxHeadersCount = null; + this.#reusedSocket = false; + this.#host = host; + this.#protocol = protocol; + this.#timeoutTimer = null; + const headersArray = ArrayIsArray(headers); + if (!headersArray) { + var headers = options.headers; + if (headers) { + for (let key in headers) { + this.setHeader(key, headers[key]); + } + } + + // if (host && !this.getHeader("host") && setHost) { + // let hostHeader = host; + + // // For the Host header, ensure that IPv6 addresses are enclosed + // // in square brackets, as defined by URI formatting + // // https://tools.ietf.org/html/rfc3986#section-3.2.2 + // const posColon = StringPrototypeIndexOf.call(hostHeader, ":"); + // if ( + // posColon !== -1 && + // StringPrototypeIncludes(hostHeader, ":", posColon + 1) && + // StringPrototypeCharCodeAt(hostHeader, 0) !== 91 /* '[' */ + // ) { + // hostHeader = `[${hostHeader}]`; + // } + + // if (port && +port !== defaultPort) { + // hostHeader += ":" + port; + // } + // this.setHeader("Host", hostHeader); + // } + + var auth = options.auth; + if (auth && !this.getHeader("Authorization")) { + this.setHeader("Authorization", "Basic " + Buffer.from(auth).toString("base64")); + } + + // if (this.getHeader("expect")) { + // if (this._header) { + // throw new ERR_HTTP_HEADERS_SENT("render"); + // } + + // this._storeHeader( + // this.method + " " + this.path + " HTTP/1.1\r\n", + // this[kOutHeaders], + // ); + // } + // } else { + // this._storeHeader( + // this.method + " " + this.path + " HTTP/1.1\r\n", + // options.headers, + // ); + } + + // this[kUniqueHeaders] = parseUniqueHeadersOption(options.uniqueHeaders); + + var optsWithoutSignal = options; + if (optsWithoutSignal.signal) { + optsWithoutSignal = ObjectAssign({}, options); + delete optsWithoutSignal.signal; + } + this.#options = optsWithoutSignal; + + var timeout = options.timeout; + if (timeout) { + this.setTimeout(timeout); + } + } + + setSocketKeepAlive(enable = true, initialDelay = 0) { + __DEBUG__ && debug(`${NODE_HTTP_WARNING}\n`, "WARN: ClientRequest.setSocketKeepAlive is a no-op"); + } + + setNoDelay(noDelay = true) { + __DEBUG__ && debug(`${NODE_HTTP_WARNING}\n`, "WARN: ClientRequest.setNoDelay is a no-op"); + } + [kClearTimeout]() { + if (this.#timeoutTimer) { + clearTimeout(this.#timeoutTimer); + this.#timeoutTimer = null; + } + } + + setTimeout(msecs, callback?) { + if (this.#timeoutTimer) return this; + if (callback) { + this.on("timeout", callback); + } + + this.#timeoutTimer = setTimeout(async () => { + this.#timeoutTimer = null; + this[kAbortController]?.abort(); + this.emit("timeout"); + }, msecs); + + return this; + } +} + +function urlToHttpOptions(url) { + var { protocol, hostname, hash, search, pathname, href, port, username, password } = url; + return { + protocol, + hostname: + typeof hostname === "string" && StringPrototypeStartsWith.call(hostname, "[") + ? StringPrototypeSlice.call(hostname, 1, -1) + : hostname, + hash, + search, + pathname, + path: `${pathname || ""}${search || ""}`, + href, + port: port ? Number(port) : protocol === "https:" ? 443 : protocol === "http:" ? 80 : undefined, + auth: username || password ? `${decodeURIComponent(username)}:${decodeURIComponent(password)}` : undefined, + }; +} + +function validateHost(host, name) { + if (host !== null && host !== undefined && typeof host !== "string") { + // throw new ERR_INVALID_ARG_TYPE( + // `options.${name}`, + // ["string", "undefined", "null"], + // host, + // ); + throw new Error("Invalid arg type in options"); + } + return host; +} + +const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/; +/** + * Verifies that the given val is a valid HTTP token + * per the rules defined in RFC 7230 + * See https://tools.ietf.org/html/rfc7230#section-3.2.6 + */ +function checkIsHttpToken(val) { + return RegExpPrototypeExec.call(tokenRegExp, val) !== null; +} + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +export const METHODS = [ + "ACL", + "BIND", + "CHECKOUT", + "CONNECT", + "COPY", + "DELETE", + "GET", + "HEAD", + "LINK", + "LOCK", + "M-SEARCH", + "MERGE", + "MKACTIVITY", + "MKCALENDAR", + "MKCOL", + "MOVE", + "NOTIFY", + "OPTIONS", + "PATCH", + "POST", + "PROPFIND", + "PROPPATCH", + "PURGE", + "PUT", + "REBIND", + "REPORT", + "SEARCH", + "SOURCE", + "SUBSCRIBE", + "TRACE", + "UNBIND", + "UNLINK", + "UNLOCK", + "UNSUBSCRIBE", +]; + +export const STATUS_CODES = { + 100: "Continue", + 101: "Switching Protocols", + 102: "Processing", + 103: "Early Hints", + 200: "OK", + 201: "Created", + 202: "Accepted", + 203: "Non-Authoritative Information", + 204: "No Content", + 205: "Reset Content", + 206: "Partial Content", + 207: "Multi-Status", + 208: "Already Reported", + 226: "IM Used", + 300: "Multiple Choices", + 301: "Moved Permanently", + 302: "Found", + 303: "See Other", + 304: "Not Modified", + 305: "Use Proxy", + 307: "Temporary Redirect", + 308: "Permanent Redirect", + 400: "Bad Request", + 401: "Unauthorized", + 402: "Payment Required", + 403: "Forbidden", + 404: "Not Found", + 405: "Method Not Allowed", + 406: "Not Acceptable", + 407: "Proxy Authentication Required", + 408: "Request Timeout", + 409: "Conflict", + 410: "Gone", + 411: "Length Required", + 412: "Precondition Failed", + 413: "Payload Too Large", + 414: "URI Too Long", + 415: "Unsupported Media Type", + 416: "Range Not Satisfiable", + 417: "Expectation Failed", + 418: "I'm a Teapot", + 421: "Misdirected Request", + 422: "Unprocessable Entity", + 423: "Locked", + 424: "Failed Dependency", + 425: "Too Early", + 426: "Upgrade Required", + 428: "Precondition Required", + 429: "Too Many Requests", + 431: "Request Header Fields Too Large", + 451: "Unavailable For Legal Reasons", + 500: "Internal Server Error", + 501: "Not Implemented", + 502: "Bad Gateway", + 503: "Service Unavailable", + 504: "Gateway Timeout", + 505: "HTTP Version Not Supported", + 506: "Variant Also Negotiates", + 507: "Insufficient Storage", + 508: "Loop Detected", + 509: "Bandwidth Limit Exceeded", + 510: "Not Extended", + 511: "Network Authentication Required", +}; + +function _normalizeArgs(args) { + let arr; + + if (args.length === 0) { + arr = [{}, null]; + // arr[normalizedArgsSymbol] = true; + return arr; + } + + const arg0 = args[0]; + let options: any = {}; + if (typeof arg0 === "object" && arg0 !== null) { + // (options[...][, cb]) + options = arg0; + // } else if (isPipeName(arg0)) { + // (path[...][, cb]) + // options.path = arg0; + } else { + // ([port][, host][...][, cb]) + options.port = arg0; + if (args.length > 1 && typeof args[1] === "string") { + options.host = args[1]; + } + } + + const cb = args[args.length - 1]; + if (typeof cb !== "function") arr = [options, null]; + else arr = [options, cb]; + + // arr[normalizedArgsSymbol] = true; + return arr; +} + +function _writeHead(statusCode, reason, obj, response) { + statusCode |= 0; + if (statusCode < 100 || statusCode > 999) { + throw new Error("status code must be between 100 and 999"); + } + + if (typeof reason === "string") { + // writeHead(statusCode, reasonPhrase[, headers]) + response.statusMessage = reason; + } else { + // writeHead(statusCode[, headers]) + if (!response.statusMessage) response.statusMessage = STATUS_CODES[statusCode] || "unknown"; + obj = reason; + } + response.statusCode = statusCode; + + { + // Slow-case: when progressive API and header fields are passed. + let k; + if (Array.isArray(obj)) { + if (obj.length % 2 !== 0) { + throw new Error("raw headers must have an even number of elements"); + } + + for (let n = 0; n < obj.length; n += 2) { + k = obj[n + 0]; + if (k) response.setHeader(k, obj[n + 1]); + } + } else if (obj) { + const keys = Object.keys(obj); + // Retain for(;;) loop for performance reasons + // Refs: https://github.com/nodejs/node/pull/30958 + for (let i = 0; i < keys.length; i++) { + k = keys[i]; + if (k) response.setHeader(k, obj[k]); + } + } + } +} + +/** + * Makes an HTTP request. + * @param {string | URL} url + * @param {HTTPRequestOptions} [options] + * @param {Function} [cb] + * @returns {ClientRequest} + */ +export function request(url, options, cb) { + return new ClientRequest(url, options, cb); +} + +/** + * Makes a `GET` HTTP request. + * @param {string | URL} url + * @param {HTTPRequestOptions} [options] + * @param {Function} [cb] + * @returns {ClientRequest} + */ +export function get(url, options, cb) { + const req = request(url, options, cb); + req.end(); + return req; +} + +export var globalAgent = new Agent(); +var defaultObject = { + Agent, + Server, + METHODS, + STATUS_CODES, + createServer, + ServerResponse, + IncomingMessage, + request, + get, + maxHeaderSize: 16384, + validateHeaderName, + validateHeaderValue, + setMaxIdleHTTPParsers(max) { + debug(`${NODE_HTTP_WARNING}\n`, "setMaxIdleHTTPParsers() is a no-op"); + }, + globalAgent, + [Symbol.for("CommonJS")]: 0, +}; + +export default defaultObject; diff --git a/src/js/node/https.js b/src/js/node/https.js deleted file mode 100644 index 5bef145ff..000000000 --- a/src/js/node/https.js +++ /dev/null @@ -1,3 +0,0 @@ -// Hardcoded module "node:https" -export * from "node:http"; -export { default as default } from "node:http"; diff --git a/src/js/node/https.ts b/src/js/node/https.ts new file mode 100644 index 000000000..08eb89a01 --- /dev/null +++ b/src/js/node/https.ts @@ -0,0 +1,65 @@ +// Hardcoded module "node:https" +import * as http from "node:http"; + +var { + Agent, + Server, + METHODS, + STATUS_CODES, + createServer, + ServerResponse, + IncomingMessage, + maxHeaderSize, + validateHeaderName, + validateHeaderValue, + globalAgent, +} = http; + +function request(input, options, cb) { + if (input && typeof input === "object" && !(input instanceof URL)) { + input.protocol ??= "https:"; + } else if (typeof options === "object") { + options.protocol ??= "https:"; + } + + return http.request(input, options, cb); +} + +function get(input, options, cb) { + const req = request(input, options, cb); + req.end(); + return req; +} + +var defaultExport = { + Agent, + Server, + METHODS, + STATUS_CODES, + createServer, + ServerResponse, + IncomingMessage, + request, + get, + maxHeaderSize, + validateHeaderName, + validateHeaderValue, + globalAgent, +}; + +export { + Agent, + Server, + METHODS, + STATUS_CODES, + createServer, + ServerResponse, + IncomingMessage, + request, + get, + maxHeaderSize, + validateHeaderName, + validateHeaderValue, + globalAgent, +}; +export default defaultExport; diff --git a/src/js/out/WebCoreJSBuiltins.cpp b/src/js/out/WebCoreJSBuiltins.cpp index f5d39d398..df64669b5 100644 --- a/src/js/out/WebCoreJSBuiltins.cpp +++ b/src/js/out/WebCoreJSBuiltins.cpp @@ -32,7 +32,7 @@ const JSC::ConstructorKind s_bundlerPluginRunOnLoadPluginsCodeConstructorKind = const JSC::ImplementationVisibility s_bundlerPluginRunOnLoadPluginsCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_bundlerPluginRunOnLoadPluginsCodeLength = 1325; static const JSC::Intrinsic s_bundlerPluginRunOnLoadPluginsCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_bundlerPluginRunOnLoadPluginsCode = "(function (w,G,H,x){\"use strict\";const C={jsx:0,js:1,ts:2,tsx:3,css:4,file:5,json:6,toml:7,wasm:8,napi:9,base64:10,dataurl:11,text:12},b=[\"jsx\",\"js\",\"ts\",\"tsx\",\"css\",\"file\",\"json\",\"toml\",\"wasm\",\"napi\",\"base64\",\"dataurl\",\"text\"][x];var J=(async(K,z,Q,F)=>{var g=this.onLoad.@get(Q);if(!g)return this.onLoadAsync(K,null,null),null;for(let[B,v]of g)if(B.test(z)){var q=v({path:z,namespace:Q,loader:F});while(q&&@isPromise(q)&&(@getPromiseInternalField(q,@promiseFieldFlags)&@promiseStateMask)===@promiseStateFulfilled)q=@getPromiseInternalField(q,@promiseFieldReactionsOrResult);if(q&&@isPromise(q))q=await q;if(!q||!@isObject(q))continue;var{contents:T,loader:y=F}=q;if(typeof T!==\"string\"&&!@isTypedArrayView(T))@throwTypeError('onLoad plugins must return an object with \"contents\" as a string or Uint8Array');if(typeof y!==\"string\")@throwTypeError('onLoad plugins must return an object with \"loader\" as a string');const j=C[y];if(j===@undefined)@throwTypeError(`Loader ${y} is not supported.`);return this.onLoadAsync(K,T,j),null}return this.onLoadAsync(K,null,null),null})(w,G,H,b);while(J&&@isPromise(J)&&(@getPromiseInternalField(J,@promiseFieldFlags)&@promiseStateMask)===@promiseStateFulfilled)J=@getPromiseInternalField(J,@promiseFieldReactionsOrResult);if(J&&@isPromise(J))J.then(()=>{},(K)=>{this.addError(w,K,1)})})\n"; +const char* const s_bundlerPluginRunOnLoadPluginsCode = "(function (b,g,j,q){\"use strict\";const v={jsx:0,js:1,ts:2,tsx:3,css:4,file:5,json:6,toml:7,wasm:8,napi:9,base64:10,dataurl:11,text:12},w=[\"jsx\",\"js\",\"ts\",\"tsx\",\"css\",\"file\",\"json\",\"toml\",\"wasm\",\"napi\",\"base64\",\"dataurl\",\"text\"][q];var x=(async(y,z,B,C)=>{var F=this.onLoad.@get(B);if(!F)return this.onLoadAsync(y,null,null),null;for(let[K,Q]of F)if(K.test(z)){var G=Q({path:z,namespace:B,loader:C});while(G&&@isPromise(G)&&(@getPromiseInternalField(G,@promiseFieldFlags)&@promiseStateMask)===@promiseStateFulfilled)G=@getPromiseInternalField(G,@promiseFieldReactionsOrResult);if(G&&@isPromise(G))G=await G;if(!G||!@isObject(G))continue;var{contents:H,loader:J=C}=G;if(typeof H!==\"string\"&&!@isTypedArrayView(H))@throwTypeError('onLoad plugins must return an object with \"contents\" as a string or Uint8Array');if(typeof J!==\"string\")@throwTypeError('onLoad plugins must return an object with \"loader\" as a string');const T=v[J];if(T===@undefined)@throwTypeError(`Loader ${J} is not supported.`);return this.onLoadAsync(y,H,T),null}return this.onLoadAsync(y,null,null),null})(b,g,j,w);while(x&&@isPromise(x)&&(@getPromiseInternalField(x,@promiseFieldFlags)&@promiseStateMask)===@promiseStateFulfilled)x=@getPromiseInternalField(x,@promiseFieldReactionsOrResult);if(x&&@isPromise(x))x.then(()=>{},(y)=>{this.addError(b,y,1)})})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -116,7 +116,7 @@ const JSC::ConstructorKind s_writableStreamInternalsCreateInternalWritableStream const JSC::ImplementationVisibility s_writableStreamInternalsCreateInternalWritableStreamFromUnderlyingSinkCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_writableStreamInternalsCreateInternalWritableStreamFromUnderlyingSinkCodeLength = 956; static const JSC::Intrinsic s_writableStreamInternalsCreateInternalWritableStreamFromUnderlyingSinkCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsCreateInternalWritableStreamFromUnderlyingSinkCode = "(function (o,w){\"use strict\";const C={};if(o===@undefined)o={};if(w===@undefined)w={};if(!@isObject(o))@throwTypeError(\"WritableStream constructor takes an object as first argument\");if(\"type\"in o)@throwRangeError(\"Invalid type is specified\");const E=@extractSizeAlgorithm(w),_=@extractHighWaterMark(w,1),f={};if(\"start\"in o){if(f[\"start\"]=o[\"start\"],typeof f[\"start\"]!==\"function\")@throwTypeError(\"underlyingSink.start should be a function\")}if(\"write\"in o){if(f[\"write\"]=o[\"write\"],typeof f[\"write\"]!==\"function\")@throwTypeError(\"underlyingSink.write should be a function\")}if(\"close\"in o){if(f[\"close\"]=o[\"close\"],typeof f[\"close\"]!==\"function\")@throwTypeError(\"underlyingSink.close should be a function\")}if(\"abort\"in o){if(f[\"abort\"]=o[\"abort\"],typeof f[\"abort\"]!==\"function\")@throwTypeError(\"underlyingSink.abort should be a function\")}return @initializeWritableStreamSlots(C,o),@setUpWritableStreamDefaultControllerFromUnderlyingSink(C,o,f,_,E),C})\n"; +const char* const s_writableStreamInternalsCreateInternalWritableStreamFromUnderlyingSinkCode = "(function (f,o){\"use strict\";const w={};if(f===@undefined)f={};if(o===@undefined)o={};if(!@isObject(f))@throwTypeError(\"WritableStream constructor takes an object as first argument\");if(\"type\"in f)@throwRangeError(\"Invalid type is specified\");const C=@extractSizeAlgorithm(o),E=@extractHighWaterMark(o,1),_={};if(\"start\"in f){if(_[\"start\"]=f[\"start\"],typeof _[\"start\"]!==\"function\")@throwTypeError(\"underlyingSink.start should be a function\")}if(\"write\"in f){if(_[\"write\"]=f[\"write\"],typeof _[\"write\"]!==\"function\")@throwTypeError(\"underlyingSink.write should be a function\")}if(\"close\"in f){if(_[\"close\"]=f[\"close\"],typeof _[\"close\"]!==\"function\")@throwTypeError(\"underlyingSink.close should be a function\")}if(\"abort\"in f){if(_[\"abort\"]=f[\"abort\"],typeof _[\"abort\"]!==\"function\")@throwTypeError(\"underlyingSink.abort should be a function\")}return @initializeWritableStreamSlots(w,f),@setUpWritableStreamDefaultControllerFromUnderlyingSink(w,f,_,E,C),w})\n"; // initializeWritableStreamSlots const JSC::ConstructAbility s_writableStreamInternalsInitializeWritableStreamSlotsCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -164,7 +164,7 @@ const JSC::ConstructorKind s_writableStreamInternalsWritableStreamAbortCodeConst const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamAbortCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_writableStreamInternalsWritableStreamAbortCodeLength = 501; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamAbortCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamAbortCode = "(function (c,h){\"use strict\";const B=@getByIdDirectPrivate(c,\"state\");if(B===\"closed\"||B===\"errored\")return @Promise.@resolve();const _=@getByIdDirectPrivate(c,\"pendingAbortRequest\");if(_!==@undefined)return _.promise.@promise;@assert(B===\"writable\"||B===\"erroring\");let f=!1;if(B===\"erroring\")f=!0,h=@undefined;const j=@newPromiseCapability(@Promise);if(@putByIdDirectPrivate(c,\"pendingAbortRequest\",{promise:j,reason:h,wasAlreadyErroring:f}),!f)@writableStreamStartErroring(c,h);return j.@promise})\n"; +const char* const s_writableStreamInternalsWritableStreamAbortCode = "(function (c,B){\"use strict\";const h=@getByIdDirectPrivate(c,\"state\");if(h===\"closed\"||h===\"errored\")return @Promise.@resolve();const _=@getByIdDirectPrivate(c,\"pendingAbortRequest\");if(_!==@undefined)return _.promise.@promise;@assert(h===\"writable\"||h===\"erroring\");let f=!1;if(h===\"erroring\")f=!0,B=@undefined;const j=@newPromiseCapability(@Promise);if(@putByIdDirectPrivate(c,\"pendingAbortRequest\",{promise:j,reason:B,wasAlreadyErroring:f}),!f)@writableStreamStartErroring(c,B);return j.@promise})\n"; // writableStreamClose const JSC::ConstructAbility s_writableStreamInternalsWritableStreamCloseCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -204,7 +204,7 @@ const JSC::ConstructorKind s_writableStreamInternalsWritableStreamFinishErroring const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamFinishErroringCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_writableStreamInternalsWritableStreamFinishErroringCodeLength = 1058; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamFinishErroringCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamFinishErroringCode = "(function (_){\"use strict\";@assert(@getByIdDirectPrivate(_,\"state\")===\"erroring\"),@assert(!@writableStreamHasOperationMarkedInFlight(_)),@putByIdDirectPrivate(_,\"state\",\"errored\");const p=@getByIdDirectPrivate(_,\"controller\");@getByIdDirectPrivate(p,\"errorSteps\").@call();const h=@getByIdDirectPrivate(_,\"storedError\"),A=@getByIdDirectPrivate(_,\"writeRequests\");for(var I=A.shift();I;I=A.shift())I.@reject.@call(@undefined,h);@putByIdDirectPrivate(_,\"writeRequests\",@createFIFO());const i=@getByIdDirectPrivate(_,\"pendingAbortRequest\");if(i===@undefined){@writableStreamRejectCloseAndClosedPromiseIfNeeded(_);return}if(@putByIdDirectPrivate(_,\"pendingAbortRequest\",@undefined),i.wasAlreadyErroring){i.promise.@reject.@call(@undefined,h),@writableStreamRejectCloseAndClosedPromiseIfNeeded(_);return}@getByIdDirectPrivate(p,\"abortSteps\").@call(@undefined,i.reason).@then(()=>{i.promise.@resolve.@call(),@writableStreamRejectCloseAndClosedPromiseIfNeeded(_)},(B)=>{i.promise.@reject.@call(@undefined,B),@writableStreamRejectCloseAndClosedPromiseIfNeeded(_)})})\n"; +const char* const s_writableStreamInternalsWritableStreamFinishErroringCode = "(function (i){\"use strict\";@assert(@getByIdDirectPrivate(i,\"state\")===\"erroring\"),@assert(!@writableStreamHasOperationMarkedInFlight(i)),@putByIdDirectPrivate(i,\"state\",\"errored\");const _=@getByIdDirectPrivate(i,\"controller\");@getByIdDirectPrivate(_,\"errorSteps\").@call();const p=@getByIdDirectPrivate(i,\"storedError\"),h=@getByIdDirectPrivate(i,\"writeRequests\");for(var A=h.shift();A;A=h.shift())A.@reject.@call(@undefined,p);@putByIdDirectPrivate(i,\"writeRequests\",@createFIFO());const B=@getByIdDirectPrivate(i,\"pendingAbortRequest\");if(B===@undefined){@writableStreamRejectCloseAndClosedPromiseIfNeeded(i);return}if(@putByIdDirectPrivate(i,\"pendingAbortRequest\",@undefined),B.wasAlreadyErroring){B.promise.@reject.@call(@undefined,p),@writableStreamRejectCloseAndClosedPromiseIfNeeded(i);return}@getByIdDirectPrivate(_,\"abortSteps\").@call(@undefined,B.reason).@then(()=>{B.promise.@resolve.@call(),@writableStreamRejectCloseAndClosedPromiseIfNeeded(i)},(I)=>{B.promise.@reject.@call(@undefined,I),@writableStreamRejectCloseAndClosedPromiseIfNeeded(i)})})\n"; // writableStreamFinishInFlightClose const JSC::ConstructAbility s_writableStreamInternalsWritableStreamFinishInFlightCloseCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -212,7 +212,7 @@ const JSC::ConstructorKind s_writableStreamInternalsWritableStreamFinishInFlight const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamFinishInFlightCloseCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_writableStreamInternalsWritableStreamFinishInFlightCloseCodeLength = 751; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamFinishInFlightCloseCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamFinishInFlightCloseCode = "(function (d){\"use strict\";@getByIdDirectPrivate(d,\"inFlightCloseRequest\").@resolve.@call(),@putByIdDirectPrivate(d,\"inFlightCloseRequest\",@undefined);const n=@getByIdDirectPrivate(d,\"state\");if(@assert(n===\"writable\"||n===\"erroring\"),n===\"erroring\"){@putByIdDirectPrivate(d,\"storedError\",@undefined);const c=@getByIdDirectPrivate(d,\"pendingAbortRequest\");if(c!==@undefined)c.promise.@resolve.@call(),@putByIdDirectPrivate(d,\"pendingAbortRequest\",@undefined)}@putByIdDirectPrivate(d,\"state\",\"closed\");const _=@getByIdDirectPrivate(d,\"writer\");if(_!==@undefined)@getByIdDirectPrivate(_,\"closedPromise\").@resolve.@call();@assert(@getByIdDirectPrivate(d,\"pendingAbortRequest\")===@undefined),@assert(@getByIdDirectPrivate(d,\"storedError\")===@undefined)})\n"; +const char* const s_writableStreamInternalsWritableStreamFinishInFlightCloseCode = "(function (d){\"use strict\";@getByIdDirectPrivate(d,\"inFlightCloseRequest\").@resolve.@call(),@putByIdDirectPrivate(d,\"inFlightCloseRequest\",@undefined);const _=@getByIdDirectPrivate(d,\"state\");if(@assert(_===\"writable\"||_===\"erroring\"),_===\"erroring\"){@putByIdDirectPrivate(d,\"storedError\",@undefined);const c=@getByIdDirectPrivate(d,\"pendingAbortRequest\");if(c!==@undefined)c.promise.@resolve.@call(),@putByIdDirectPrivate(d,\"pendingAbortRequest\",@undefined)}@putByIdDirectPrivate(d,\"state\",\"closed\");const n=@getByIdDirectPrivate(d,\"writer\");if(n!==@undefined)@getByIdDirectPrivate(n,\"closedPromise\").@resolve.@call();@assert(@getByIdDirectPrivate(d,\"pendingAbortRequest\")===@undefined),@assert(@getByIdDirectPrivate(d,\"storedError\")===@undefined)})\n"; // writableStreamFinishInFlightCloseWithError const JSC::ConstructAbility s_writableStreamInternalsWritableStreamFinishInFlightCloseWithErrorCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -348,7 +348,7 @@ const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultWriterW const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultWriterWriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_writableStreamInternalsWritableStreamDefaultWriterWriteCodeLength = 919; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultWriterWriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultWriterWriteCode = "(function (g,P){\"use strict\";const W=@getByIdDirectPrivate(g,\"stream\");@assert(W!==@undefined);const _=@getByIdDirectPrivate(W,\"controller\");@assert(_!==@undefined);const f=@writableStreamDefaultControllerGetChunkSize(_,P);if(W!==@getByIdDirectPrivate(g,\"stream\"))return @Promise.@reject(@makeTypeError(\"writer is not stream's writer\"));const d=@getByIdDirectPrivate(W,\"state\");if(d===\"errored\")return @Promise.@reject(@getByIdDirectPrivate(W,\"storedError\"));if(@writableStreamCloseQueuedOrInFlight(W)||d===\"closed\")return @Promise.@reject(@makeTypeError(\"stream is closing or closed\"));if(@writableStreamCloseQueuedOrInFlight(W)||d===\"closed\")return @Promise.@reject(@makeTypeError(\"stream is closing or closed\"));if(d===\"erroring\")return @Promise.@reject(@getByIdDirectPrivate(W,\"storedError\"));@assert(d===\"writable\");const b=@writableStreamAddWriteRequest(W);return @writableStreamDefaultControllerWrite(_,P,f),b})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultWriterWriteCode = "(function (d,g){\"use strict\";const P=@getByIdDirectPrivate(d,\"stream\");@assert(P!==@undefined);const W=@getByIdDirectPrivate(P,\"controller\");@assert(W!==@undefined);const _=@writableStreamDefaultControllerGetChunkSize(W,g);if(P!==@getByIdDirectPrivate(d,\"stream\"))return @Promise.@reject(@makeTypeError(\"writer is not stream's writer\"));const b=@getByIdDirectPrivate(P,\"state\");if(b===\"errored\")return @Promise.@reject(@getByIdDirectPrivate(P,\"storedError\"));if(@writableStreamCloseQueuedOrInFlight(P)||b===\"closed\")return @Promise.@reject(@makeTypeError(\"stream is closing or closed\"));if(@writableStreamCloseQueuedOrInFlight(P)||b===\"closed\")return @Promise.@reject(@makeTypeError(\"stream is closing or closed\"));if(b===\"erroring\")return @Promise.@reject(@getByIdDirectPrivate(P,\"storedError\"));@assert(b===\"writable\");const f=@writableStreamAddWriteRequest(P);return @writableStreamDefaultControllerWrite(W,g,_),f})\n"; // setUpWritableStreamDefaultController const JSC::ConstructAbility s_writableStreamInternalsSetUpWritableStreamDefaultControllerCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -468,7 +468,7 @@ const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultControl const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultControllerWriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_writableStreamInternalsWritableStreamDefaultControllerWriteCodeLength = 450; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultControllerWriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultControllerWriteCode = "(function (y,B,D){\"use strict\";try{@enqueueValueWithSize(@getByIdDirectPrivate(y,\"queue\"),B,D);const I=@getByIdDirectPrivate(y,\"stream\"),_=@getByIdDirectPrivate(I,\"state\");if(!@writableStreamCloseQueuedOrInFlight(I)&&_===\"writable\"){const d=@writableStreamDefaultControllerGetBackpressure(y);@writableStreamUpdateBackpressure(I,d)}@writableStreamDefaultControllerAdvanceQueueIfNeeded(y)}catch(I){@writableStreamDefaultControllerErrorIfNeeded(y,I)}})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultControllerWriteCode = "(function (d,y,B){\"use strict\";try{@enqueueValueWithSize(@getByIdDirectPrivate(d,\"queue\"),y,B);const D=@getByIdDirectPrivate(d,\"stream\"),I=@getByIdDirectPrivate(D,\"state\");if(!@writableStreamCloseQueuedOrInFlight(D)&&I===\"writable\"){const _=@writableStreamDefaultControllerGetBackpressure(d);@writableStreamUpdateBackpressure(D,_)}@writableStreamDefaultControllerAdvanceQueueIfNeeded(d)}catch(D){@writableStreamDefaultControllerErrorIfNeeded(d,D)}})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -502,7 +502,7 @@ const JSC::ConstructorKind s_transformStreamInternalsCreateTransformStreamCodeCo const JSC::ImplementationVisibility s_transformStreamInternalsCreateTransformStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_transformStreamInternalsCreateTransformStreamCodeLength = 513; static const JSC::Intrinsic s_transformStreamInternalsCreateTransformStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsCreateTransformStreamCode = "(function (q,x,B,D,c,F,j){\"use strict\";if(D===@undefined)D=1;if(c===@undefined)c=()=>1;if(F===@undefined)F=0;if(j===@undefined)j=()=>1;@assert(D>=0),@assert(F>=0);const G={};@putByIdDirectPrivate(G,\"TransformStream\",!0);const I=new @TransformStream(G),v=@newPromiseCapability(@Promise);@initializeTransformStream(I,v.@promise,D,c,F,j);const E=new @TransformStreamDefaultController;return @setUpTransformStreamDefaultController(I,E,x,B),q().@then(()=>{v.@resolve.@call()},(_)=>{v.@reject.@call(@undefined,_)}),I})\n"; +const char* const s_transformStreamInternalsCreateTransformStreamCode = "(function (_,c,j,q,v,x,B){\"use strict\";if(q===@undefined)q=1;if(v===@undefined)v=()=>1;if(x===@undefined)x=0;if(B===@undefined)B=()=>1;@assert(q>=0),@assert(x>=0);const D={};@putByIdDirectPrivate(D,\"TransformStream\",!0);const E=new @TransformStream(D),F=@newPromiseCapability(@Promise);@initializeTransformStream(E,F.@promise,q,v,x,B);const G=new @TransformStreamDefaultController;return @setUpTransformStreamDefaultController(E,G,c,j),_().@then(()=>{F.@resolve.@call()},(I)=>{F.@reject.@call(@undefined,I)}),E})\n"; // initializeTransformStream const JSC::ConstructAbility s_transformStreamInternalsInitializeTransformStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -510,7 +510,7 @@ const JSC::ConstructorKind s_transformStreamInternalsInitializeTransformStreamCo const JSC::ImplementationVisibility s_transformStreamInternalsInitializeTransformStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_transformStreamInternalsInitializeTransformStreamCodeLength = 1015; static const JSC::Intrinsic s_transformStreamInternalsInitializeTransformStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsInitializeTransformStreamCode = "(function (T,j,v,C,D,E){\"use strict\";const F=()=>{return j},G=(N)=>{return @transformStreamDefaultSinkWriteAlgorithm(T,N)},I=(N)=>{return @transformStreamDefaultSinkAbortAlgorithm(T,N)},J=()=>{return @transformStreamDefaultSinkCloseAlgorithm(T)},f=@createWritableStream(F,G,J,I,v,C),B=()=>{return @transformStreamDefaultSourcePullAlgorithm(T)},q=(N)=>{return @transformStreamErrorWritableAndUnblockWrite(T,N),@Promise.@resolve()},x={};@putByIdDirectPrivate(x,\"start\",F),@putByIdDirectPrivate(x,\"pull\",B),@putByIdDirectPrivate(x,\"cancel\",q);const K={};@putByIdDirectPrivate(K,\"size\",E),@putByIdDirectPrivate(K,\"highWaterMark\",D);const L=new @ReadableStream(x,K);@putByIdDirectPrivate(T,\"writable\",f),@putByIdDirectPrivate(T,\"internalWritable\",@getInternalWritableStream(f)),@putByIdDirectPrivate(T,\"readable\",L),@putByIdDirectPrivate(T,\"backpressure\",@undefined),@putByIdDirectPrivate(T,\"backpressureChangePromise\",@undefined),@transformStreamSetBackpressure(T,!0),@putByIdDirectPrivate(T,\"controller\",@undefined)})\n"; +const char* const s_transformStreamInternalsInitializeTransformStreamCode = "(function (f,G,B,T,C,F){\"use strict\";const I=()=>{return G},J=(x)=>{return @transformStreamDefaultSinkWriteAlgorithm(f,x)},K=(x)=>{return @transformStreamDefaultSinkAbortAlgorithm(f,x)},j=()=>{return @transformStreamDefaultSinkCloseAlgorithm(f)},L=@createWritableStream(I,J,j,K,B,T),N=()=>{return @transformStreamDefaultSourcePullAlgorithm(f)},q=(x)=>{return @transformStreamErrorWritableAndUnblockWrite(f,x),@Promise.@resolve()},D={};@putByIdDirectPrivate(D,\"start\",I),@putByIdDirectPrivate(D,\"pull\",N),@putByIdDirectPrivate(D,\"cancel\",q);const E={};@putByIdDirectPrivate(E,\"size\",F),@putByIdDirectPrivate(E,\"highWaterMark\",C);const v=new @ReadableStream(D,E);@putByIdDirectPrivate(f,\"writable\",L),@putByIdDirectPrivate(f,\"internalWritable\",@getInternalWritableStream(L)),@putByIdDirectPrivate(f,\"readable\",v),@putByIdDirectPrivate(f,\"backpressure\",@undefined),@putByIdDirectPrivate(f,\"backpressureChangePromise\",@undefined),@transformStreamSetBackpressure(f,!0),@putByIdDirectPrivate(f,\"controller\",@undefined)})\n"; // transformStreamError const JSC::ConstructAbility s_transformStreamInternalsTransformStreamErrorCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -598,7 +598,7 @@ const JSC::ConstructorKind s_transformStreamInternalsTransformStreamDefaultSinkW const JSC::ImplementationVisibility s_transformStreamInternalsTransformStreamDefaultSinkWriteAlgorithmCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_transformStreamInternalsTransformStreamDefaultSinkWriteAlgorithmCodeLength = 764; static const JSC::Intrinsic s_transformStreamInternalsTransformStreamDefaultSinkWriteAlgorithmCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsTransformStreamDefaultSinkWriteAlgorithmCode = "(function (d,v){\"use strict\";const f=@getByIdDirectPrivate(d,\"internalWritable\");@assert(@getByIdDirectPrivate(f,\"state\")===\"writable\");const j=@getByIdDirectPrivate(d,\"controller\");if(@getByIdDirectPrivate(d,\"backpressure\")){const x=@newPromiseCapability(@Promise),_=@getByIdDirectPrivate(d,\"backpressureChangePromise\");return @assert(_!==@undefined),_.@promise.@then(()=>{const q=@getByIdDirectPrivate(f,\"state\");if(q===\"erroring\"){x.@reject.@call(@undefined,@getByIdDirectPrivate(f,\"storedError\"));return}@assert(q===\"writable\"),@transformStreamDefaultControllerPerformTransform(j,v).@then(()=>{x.@resolve()},(z)=>{x.@reject.@call(@undefined,z)})},(q)=>{x.@reject.@call(@undefined,q)}),x.@promise}return @transformStreamDefaultControllerPerformTransform(j,v)})\n"; +const char* const s_transformStreamInternalsTransformStreamDefaultSinkWriteAlgorithmCode = "(function (_,d){\"use strict\";const v=@getByIdDirectPrivate(_,\"internalWritable\");@assert(@getByIdDirectPrivate(v,\"state\")===\"writable\");const f=@getByIdDirectPrivate(_,\"controller\");if(@getByIdDirectPrivate(_,\"backpressure\")){const j=@newPromiseCapability(@Promise),q=@getByIdDirectPrivate(_,\"backpressureChangePromise\");return @assert(q!==@undefined),q.@promise.@then(()=>{const x=@getByIdDirectPrivate(v,\"state\");if(x===\"erroring\"){j.@reject.@call(@undefined,@getByIdDirectPrivate(v,\"storedError\"));return}@assert(x===\"writable\"),@transformStreamDefaultControllerPerformTransform(f,d).@then(()=>{j.@resolve()},(z)=>{j.@reject.@call(@undefined,z)})},(x)=>{j.@reject.@call(@undefined,x)}),j.@promise}return @transformStreamDefaultControllerPerformTransform(f,d)})\n"; // transformStreamDefaultSinkAbortAlgorithm const JSC::ConstructAbility s_transformStreamInternalsTransformStreamDefaultSinkAbortAlgorithmCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -648,7 +648,7 @@ const JSC::ConstructorKind s_processObjectInternalsGetStdioWriteStreamCodeConstr const JSC::ImplementationVisibility s_processObjectInternalsGetStdioWriteStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_processObjectInternalsGetStdioWriteStreamCodeLength = 4250; static const JSC::Intrinsic s_processObjectInternalsGetStdioWriteStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_processObjectInternalsGetStdioWriteStreamCode = "(function (j,z){\"use strict\";var L={path:\"node:process\",require:z},K=(N)=>L.require(N);function G(N){var{Duplex:O,eos:Q,destroy:U}=K(\"node:stream\"),V=class X extends O{#$;#B;#j=!0;#z=!0;#G;#H;#J;#K;#L;#M;get isTTY(){return this.#M\?\?=K(\"node:tty\").isatty(N)}get fd(){return N}constructor(Z){super({readable:!0,writable:!0});this.#G=`/dev/fd/${Z}`}#N(Z){const Y=this.#H;if(this.#H=null,Y)Y(Z);else if(Z)this.destroy(Z);else if(!this.#j&&!this.#z)this.destroy()}_destroy(Z,Y){if(!Z&&this.#H!==null){var P=class A extends Error{code;name;constructor(T=\"The operation was aborted\",x=void 0){if(x!==void 0&&typeof x!==\"object\")throw new Error(`Invalid AbortError options:\\n\\n${JSON.stringify(x,null,2)}`);super(T,x);this.code=\"ABORT_ERR\",this.name=\"AbortError\"}};Z=new P}if(this.#J=null,this.#K=null,this.#H===null)Y(Z);else{if(this.#H=Y,this.#$)U(this.#$,Z);if(this.#B)U(this.#B,Z)}}_write(Z,Y,P){if(!this.#$){var{createWriteStream:A}=K(\"node:fs\"),T=this.#$=A(this.#G);T.on(\"finish\",()=>{if(this.#K){const x=this.#K;this.#K=null,x()}}),T.on(\"drain\",()=>{if(this.#J){const x=this.#J;this.#J=null,x()}}),Q(T,(x)=>{if(this.#z=!1,x)U(T,x);this.#N(x)})}if(T.write(Z,Y))P();else this.#J=P}_final(Z){this.#$&&this.#$.end(),this.#K=Z}#O(){var{createReadStream:Z}=K(\"node:fs\"),Y=this.#B=Z(this.#G);return Y.on(\"readable\",()=>{if(this.#L){const P=this.#L;this.#L=null,P()}else this.read()}),Y.on(\"end\",()=>{this.push(null)}),Q(Y,(P)=>{if(this.#j=!1,P)U(Y,P);this.#N(P)}),Y}_read(){var Z=this.#B;if(!Z)Z=this.#O();while(!0){const Y=Z.read();if(Y===null||!this.push(Y))return}}};return new V(N)}var{EventEmitter:H}=K(\"node:events\");function M(N){if(!N)return!0;var O=N.toLowerCase();return O===\"utf8\"||O===\"utf-8\"||O===\"buffer\"||O===\"binary\"}var J,B=class N extends H{#$;#B;#j;#z;bytesWritten=0;setDefaultEncoding(O){if(this.#B||!M(O))return this.#J(),this.#B.setDefaultEncoding(O)}#G(){switch(this.#$){case 1:{var O=@Bun.stdout.writer({highWaterMark:0});return O.unref(),O}case 2:{var O=@Bun.stderr.writer({highWaterMark:0});return O.unref(),O}default:throw new Error(\"Unsupported writer\")}}#H(){return this.#j\?\?=this.#G()}constructor(O){super();this.#$=O}get fd(){return this.#$}get isTTY(){return this.#z\?\?=K(\"node:tty\").isatty(this.#$)}cursorTo(O,Q,U){return(J\?\?=K(\"readline\")).cursorTo(this,O,Q,U)}moveCursor(O,Q,U){return(J\?\?=K(\"readline\")).moveCursor(this,O,Q,U)}clearLine(O,Q){return(J\?\?=K(\"readline\")).clearLine(this,O,Q)}clearScreenDown(O){return(J\?\?=K(\"readline\")).clearScreenDown(this,O)}ref(){this.#H().ref()}unref(){this.#H().unref()}on(O,Q){if(O===\"close\"||O===\"finish\")return this.#J(),this.#B.on(O,Q);if(O===\"drain\")return super.on(\"drain\",Q);if(O===\"error\")return super.on(\"error\",Q);return super.on(O,Q)}get _writableState(){return this.#J(),this.#B._writableState}get _readableState(){return this.#J(),this.#B._readableState}pipe(O){return this.#J(),this.#B.pipe(O)}unpipe(O){return this.#J(),this.#B.unpipe(O)}#J(){if(this.#B)return;this.#B=G(this.#$);const O=this.eventNames();for(let Q of O)this.#B.on(Q,(...U)=>{this.emit(Q,...U)})}#K(O){var Q=this.#H();const U=Q.write(O);this.bytesWritten+=U;const V=Q.flush(!1);return!!(U||V)}#L(O,Q){if(!M(Q))return this.#J(),this.#B.write(O,Q);return this.#K(O)}#M(O,Q){if(Q)this.emit(\"error\",Q);try{O(Q\?Q:null)}catch(U){this.emit(\"error\",U)}}#N(O,Q,U){if(!M(Q))return this.#J(),this.#B.write(O,Q,U);var V=this.#H();const X=V.write(O),Z=V.flush(!0);if(Z\?.then)return Z.then(()=>{this.#M(U),this.emit(\"drain\")},(Y)=>this.#M(U,Y)),!1;return queueMicrotask(()=>{this.#M(U)}),!!(X||Z)}write(O,Q,U){const V=this._write(O,Q,U);if(V)this.emit(\"drain\");return V}get hasColors(){return @Bun.tty[this.#$].hasColors}_write(O,Q,U){var V=this.#B;if(V)return V.write(O,Q,U);switch(arguments.length){case 0:{var X=new Error(\"Invalid arguments\");throw X.code=\"ERR_INVALID_ARG_TYPE\",X}case 1:return this.#K(O);case 2:if(typeof Q===\"function\")return this.#N(O,\"\",Q);else if(typeof Q===\"string\")return this.#L(O,Q);default:{if(typeof Q!==\"undefined\"&&typeof Q!==\"string\"||typeof U!==\"undefined\"&&typeof U!==\"function\"){var X=new Error(\"Invalid arguments\");throw X.code=\"ERR_INVALID_ARG_TYPE\",X}if(typeof U===\"undefined\")return this.#L(O,Q);return this.#N(O,Q,U)}}}destroy(){return this}end(){return this}};return new B(j)})\n"; +const char* const s_processObjectInternalsGetStdioWriteStreamCode = "(function (A,M){\"use strict\";var N={path:\"node:process\",require:M},O=(Z)=>N.require(Z);function Q(Z){var{Duplex:T,eos:x,destroy:Y}=O(\"node:stream\"),j=class H extends T{#$;#B;#j=!0;#z=!0;#G;#H;#J;#K;#L;#M;get isTTY(){return this.#M\?\?=O(\"node:tty\").isatty(Z)}get fd(){return Z}constructor(V){super({readable:!0,writable:!0});this.#G=`/dev/fd/${V}`}#N(V){const L=this.#H;if(this.#H=null,L)L(V);else if(V)this.destroy(V);else if(!this.#j&&!this.#z)this.destroy()}_destroy(V,L){if(!V&&this.#H!==null){var X=class J extends Error{code;name;constructor(z=\"The operation was aborted\",P=void 0){if(P!==void 0&&typeof P!==\"object\")throw new Error(`Invalid AbortError options:\\n\\n${JSON.stringify(P,null,2)}`);super(z,P);this.code=\"ABORT_ERR\",this.name=\"AbortError\"}};V=new X}if(this.#J=null,this.#K=null,this.#H===null)L(V);else{if(this.#H=L,this.#$)Y(this.#$,V);if(this.#B)Y(this.#B,V)}}_write(V,L,X){if(!this.#$){var{createWriteStream:J}=O(\"node:fs\"),z=this.#$=J(this.#G);z.on(\"finish\",()=>{if(this.#K){const P=this.#K;this.#K=null,P()}}),z.on(\"drain\",()=>{if(this.#J){const P=this.#J;this.#J=null,P()}}),x(z,(P)=>{if(this.#z=!1,P)Y(z,P);this.#N(P)})}if(z.write(V,L))X();else this.#J=X}_final(V){this.#$&&this.#$.end(),this.#K=V}#O(){var{createReadStream:V}=O(\"node:fs\"),L=this.#B=V(this.#G);return L.on(\"readable\",()=>{if(this.#L){const X=this.#L;this.#L=null,X()}else this.read()}),L.on(\"end\",()=>{this.push(null)}),x(L,(X)=>{if(this.#j=!1,X)Y(L,X);this.#N(X)}),L}_read(){var V=this.#B;if(!V)V=this.#O();while(!0){const L=V.read();if(L===null||!this.push(L))return}}};return new j(Z)}var{EventEmitter:B}=O(\"node:events\");function G(Z){if(!Z)return!0;var T=Z.toLowerCase();return T===\"utf8\"||T===\"utf-8\"||T===\"buffer\"||T===\"binary\"}var U,K=class Z extends B{#$;#B;#j;#z;bytesWritten=0;setDefaultEncoding(T){if(this.#B||!G(T))return this.#J(),this.#B.setDefaultEncoding(T)}#G(){switch(this.#$){case 1:{var T=@Bun.stdout.writer({highWaterMark:0});return T.unref(),T}case 2:{var T=@Bun.stderr.writer({highWaterMark:0});return T.unref(),T}default:throw new Error(\"Unsupported writer\")}}#H(){return this.#j\?\?=this.#G()}constructor(T){super();this.#$=T}get fd(){return this.#$}get isTTY(){return this.#z\?\?=O(\"node:tty\").isatty(this.#$)}cursorTo(T,x,Y){return(U\?\?=O(\"readline\")).cursorTo(this,T,x,Y)}moveCursor(T,x,Y){return(U\?\?=O(\"readline\")).moveCursor(this,T,x,Y)}clearLine(T,x){return(U\?\?=O(\"readline\")).clearLine(this,T,x)}clearScreenDown(T){return(U\?\?=O(\"readline\")).clearScreenDown(this,T)}ref(){this.#H().ref()}unref(){this.#H().unref()}on(T,x){if(T===\"close\"||T===\"finish\")return this.#J(),this.#B.on(T,x);if(T===\"drain\")return super.on(\"drain\",x);if(T===\"error\")return super.on(\"error\",x);return super.on(T,x)}get _writableState(){return this.#J(),this.#B._writableState}get _readableState(){return this.#J(),this.#B._readableState}pipe(T){return this.#J(),this.#B.pipe(T)}unpipe(T){return this.#J(),this.#B.unpipe(T)}#J(){if(this.#B)return;this.#B=Q(this.#$);const T=this.eventNames();for(let x of T)this.#B.on(x,(...Y)=>{this.emit(x,...Y)})}#K(T){var x=this.#H();const Y=x.write(T);this.bytesWritten+=Y;const j=x.flush(!1);return!!(Y||j)}#L(T,x){if(!G(x))return this.#J(),this.#B.write(T,x);return this.#K(T)}#M(T,x){if(x)this.emit(\"error\",x);try{T(x\?x:null)}catch(Y){this.emit(\"error\",Y)}}#N(T,x,Y){if(!G(x))return this.#J(),this.#B.write(T,x,Y);var j=this.#H();const H=j.write(T),V=j.flush(!0);if(V\?.then)return V.then(()=>{this.#M(Y),this.emit(\"drain\")},(L)=>this.#M(Y,L)),!1;return queueMicrotask(()=>{this.#M(Y)}),!!(H||V)}write(T,x,Y){const j=this._write(T,x,Y);if(j)this.emit(\"drain\");return j}get hasColors(){return @Bun.tty[this.#$].hasColors}_write(T,x,Y){var j=this.#B;if(j)return j.write(T,x,Y);switch(arguments.length){case 0:{var H=new Error(\"Invalid arguments\");throw H.code=\"ERR_INVALID_ARG_TYPE\",H}case 1:return this.#K(T);case 2:if(typeof x===\"function\")return this.#N(T,\"\",x);else if(typeof x===\"string\")return this.#L(T,x);default:{if(typeof x!==\"undefined\"&&typeof x!==\"string\"||typeof Y!==\"undefined\"&&typeof Y!==\"function\"){var H=new Error(\"Invalid arguments\");throw H.code=\"ERR_INVALID_ARG_TYPE\",H}if(typeof Y===\"undefined\")return this.#L(T,x);return this.#N(T,x,Y)}}}destroy(){return this}end(){return this}};return new K(A)})\n"; // getStdinStream const JSC::ConstructAbility s_processObjectInternalsGetStdinStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -656,7 +656,7 @@ const JSC::ConstructorKind s_processObjectInternalsGetStdinStreamCodeConstructor const JSC::ImplementationVisibility s_processObjectInternalsGetStdinStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_processObjectInternalsGetStdinStreamCodeLength = 1799; static const JSC::Intrinsic s_processObjectInternalsGetStdinStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_processObjectInternalsGetStdinStreamCode = "(function (z,G,H){\"use strict\";var K={path:\"node:process\",require:G},L=(T)=>K.require(T),{Duplex:M,eos:N,destroy:P}=L(\"node:stream\"),Q=class T extends M{#Y;#$;#j;#z=!0;#G=!1;#H=!0;#I;#J;#K;get isTTY(){return L(\"tty\").isatty(z)}get fd(){return z}constructor(){super({readable:!0,writable:!0})}#L(Y){const j=this.#J;if(this.#J=null,j)j(Y);else if(Y)this.destroy(Y);else if(!this.#z&&!this.#H)this.destroy()}_destroy(Y,j){if(!Y&&this.#J!==null){var I=class J extends Error{constructor(U=\"The operation was aborted\",V=void 0){if(V!==void 0&&typeof V!==\"object\")throw new Error(`Invalid AbortError options:\\n\\n${JSON.stringify(V,null,2)}`);super(U,V);this.code=\"ABORT_ERR\",this.name=\"AbortError\"}};Y=new I}if(this.#J===null)j(Y);else if(this.#J=j,this.#j)P(this.#j,Y)}setRawMode(Y){}on(Y,j){if(Y===\"readable\")this.ref(),this.#G=!0;return super.on(Y,j)}pause(){return this.unref(),super.pause()}resume(){return this.ref(),super.resume()}ref(){this.#Y\?\?=H.stdin.stream().getReader(),this.#$\?\?=setInterval(()=>{},1<<30)}unref(){if(this.#$)clearInterval(this.#$),this.#$=null}async#M(){try{var Y,j;const I=this.#Y.readMany();if(!I\?.then)({done:Y,value:j}=I);else({done:Y,value:j}=await I);if(!Y){this.push(j[0]);const J=j.length;for(let U=1;U{if(this.#I){const I=this.#I;this.#I=null,I()}}),j.on(\"drain\",()=>{if(this.#K){const I=this.#K;this.#K=null,I()}}),N(j,(I)=>{if(this.#H=!1,I)P(j,I);this.#L(I)}),j}_write(Y,j,I){var J=this.#j;if(!J)J=this.#N();if(J.write(Y,j))I();else this.#K=I}_final(Y){this.#j.end(),this.#I=(...j)=>Y(...j)}};return new Q})\n"; +const char* const s_processObjectInternalsGetStdinStreamCode = "(function (Y,j,z){\"use strict\";var G={path:\"node:process\",require:j},H=(M)=>G.require(M),{Duplex:I,eos:J,destroy:K}=H(\"node:stream\"),L=class M extends I{#Y;#$;#j;#z=!0;#G=!1;#H=!0;#I;#J;#K;get isTTY(){return H(\"tty\").isatty(Y)}get fd(){return Y}constructor(){super({readable:!0,writable:!0})}#L(N){const P=this.#J;if(this.#J=null,P)P(N);else if(N)this.destroy(N);else if(!this.#z&&!this.#H)this.destroy()}_destroy(N,P){if(!N&&this.#J!==null){var Q=class T extends Error{constructor(U=\"The operation was aborted\",V=void 0){if(V!==void 0&&typeof V!==\"object\")throw new Error(`Invalid AbortError options:\\n\\n${JSON.stringify(V,null,2)}`);super(U,V);this.code=\"ABORT_ERR\",this.name=\"AbortError\"}};N=new Q}if(this.#J===null)P(N);else if(this.#J=P,this.#j)K(this.#j,N)}setRawMode(N){}on(N,P){if(N===\"readable\")this.ref(),this.#G=!0;return super.on(N,P)}pause(){return this.unref(),super.pause()}resume(){return this.ref(),super.resume()}ref(){this.#Y\?\?=z.stdin.stream().getReader(),this.#$\?\?=setInterval(()=>{},1<<30)}unref(){if(this.#$)clearInterval(this.#$),this.#$=null}async#M(){try{var N,P;const Q=this.#Y.readMany();if(!Q\?.then)({done:N,value:P}=Q);else({done:N,value:P}=await Q);if(!N){this.push(P[0]);const T=P.length;for(let U=1;U{if(this.#I){const Q=this.#I;this.#I=null,Q()}}),P.on(\"drain\",()=>{if(this.#K){const Q=this.#K;this.#K=null,Q()}}),J(P,(Q)=>{if(this.#H=!1,Q)K(P,Q);this.#L(Q)}),P}_write(N,P,Q){var T=this.#j;if(!T)T=this.#N();if(T.write(N,P))Q();else this.#K=Q}_final(N){this.#j.end(),this.#I=(...P)=>N(...P)}};return new L})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -674,7 +674,7 @@ const JSC::ConstructorKind s_transformStreamInitializeTransformStreamCodeConstru const JSC::ImplementationVisibility s_transformStreamInitializeTransformStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_transformStreamInitializeTransformStreamCodeLength = 1334; static const JSC::Intrinsic s_transformStreamInitializeTransformStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInitializeTransformStreamCode = "(function (){\"use strict\";let _=arguments[0];if(@isObject(_)&&@getByIdDirectPrivate(_,\"TransformStream\"))return this;let B=arguments[1],u=arguments[2];if(_===@undefined)_=null;if(u===@undefined)u={};if(B===@undefined)B={};let E={};if(_!==null){if(\"start\"in _){if(E[\"start\"]=_[\"start\"],typeof E[\"start\"]!==\"function\")@throwTypeError(\"transformer.start should be a function\")}if(\"transform\"in _){if(E[\"transform\"]=_[\"transform\"],typeof E[\"transform\"]!==\"function\")@throwTypeError(\"transformer.transform should be a function\")}if(\"flush\"in _){if(E[\"flush\"]=_[\"flush\"],typeof E[\"flush\"]!==\"function\")@throwTypeError(\"transformer.flush should be a function\")}if(\"readableType\"in _)@throwRangeError(\"TransformStream transformer has a readableType\");if(\"writableType\"in _)@throwRangeError(\"TransformStream transformer has a writableType\")}const j=@extractHighWaterMark(u,0),F=@extractSizeAlgorithm(u),q=@extractHighWaterMark(B,1),G=@extractSizeAlgorithm(B),v=@newPromiseCapability(@Promise);if(@initializeTransformStream(this,v.@promise,q,G,j,F),@setUpTransformStreamDefaultControllerFromTransformer(this,_,E),(\"start\"in E)){const I=@getByIdDirectPrivate(this,\"controller\");(()=>@promiseInvokeOrNoopMethodNoCatch(_,E[\"start\"],[I]))().@then(()=>{v.@resolve.@call()},(J)=>{v.@reject.@call(@undefined,J)})}else v.@resolve.@call();return this})\n"; +const char* const s_transformStreamInitializeTransformStreamCode = "(function (){\"use strict\";let _=arguments[0];if(@isObject(_)&&@getByIdDirectPrivate(_,\"TransformStream\"))return this;let B=arguments[1],u=arguments[2];if(_===@undefined)_=null;if(u===@undefined)u={};if(B===@undefined)B={};let j={};if(_!==null){if(\"start\"in _){if(j[\"start\"]=_[\"start\"],typeof j[\"start\"]!==\"function\")@throwTypeError(\"transformer.start should be a function\")}if(\"transform\"in _){if(j[\"transform\"]=_[\"transform\"],typeof j[\"transform\"]!==\"function\")@throwTypeError(\"transformer.transform should be a function\")}if(\"flush\"in _){if(j[\"flush\"]=_[\"flush\"],typeof j[\"flush\"]!==\"function\")@throwTypeError(\"transformer.flush should be a function\")}if(\"readableType\"in _)@throwRangeError(\"TransformStream transformer has a readableType\");if(\"writableType\"in _)@throwRangeError(\"TransformStream transformer has a writableType\")}const v=@extractHighWaterMark(u,0),x=@extractSizeAlgorithm(u),E=@extractHighWaterMark(B,1),F=@extractSizeAlgorithm(B),G=@newPromiseCapability(@Promise);if(@initializeTransformStream(this,G.@promise,E,F,v,x),@setUpTransformStreamDefaultControllerFromTransformer(this,_,j),(\"start\"in j)){const q=@getByIdDirectPrivate(this,\"controller\");(()=>@promiseInvokeOrNoopMethodNoCatch(_,j[\"start\"],[q]))().@then(()=>{G.@resolve.@call()},(J)=>{G.@reject.@call(@undefined,J)})}else G.@resolve.@call();return this})\n"; // readable const JSC::ConstructAbility s_transformStreamReadableCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -716,7 +716,7 @@ const JSC::ConstructorKind s_moduleRequireCodeConstructorKind = JSC::Constructor const JSC::ImplementationVisibility s_moduleRequireCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_moduleRequireCodeLength = 1035; static const JSC::Intrinsic s_moduleRequireCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_moduleRequireCode = "(function (M){\"use strict\";const S=@requireMap.@get(M)||@requireMap.@get(M=@resolveSync(M,this.path,!1));if(S)return @evaluateCommonJSModule(S),S.exports;if(M.endsWith(\".json\")||M.endsWith(\".toml\")||M.endsWith(\".node\"))return @internalRequire(M);let f=@Loader.registry.@get(M);if(f\?.evaluated&&(f.state\?\?0)>=@ModuleReady){const _=f.module,b=@Loader.getModuleNamespaceObject(_),r=b\?.[@commonJSSymbol]===0||b\?.default\?.[@commonJSSymbol]===0\?b.default:b.__esModule\?b:Object.create(b,{__esModule:{value:!0}});return @requireMap.@set(M,@createCommonJSModule(M,r,!0)),r}const L=@createCommonJSModule(M,{},!1);@requireMap.@set(M,L);var h=this.@require(M,L);if(h===-1){try{h=@requireESM(M)}catch(_){throw @requireMap.@delete(M),_}if(f=@Loader.registry.@get(M),f\?.evaluated&&(f.state\?\?0)>=@ModuleReady){const _=@Loader.getModuleNamespaceObject(f.module);return L.exports=_\?.[@commonJSSymbol]===0||_\?.default\?.[@commonJSSymbol]===0\?_.default:_.__esModule\?_:Object.create(_,{__esModule:{value:!0}})}}return @evaluateCommonJSModule(L),L.exports})\n"; +const char* const s_moduleRequireCode = "(function (_){\"use strict\";const S=@requireMap.@get(_)||@requireMap.@get(_=@resolveSync(_,this.path,!1));if(S)return @evaluateCommonJSModule(S),S.exports;if(_.endsWith(\".json\")||_.endsWith(\".toml\")||_.endsWith(\".node\"))return @internalRequire(_);let f=@Loader.registry.@get(_);if(f\?.evaluated&&(f.state\?\?0)>=@ModuleReady){const h=f.module,r=@Loader.getModuleNamespaceObject(h),b=r\?.[@commonJSSymbol]===0||r\?.default\?.[@commonJSSymbol]===0\?r.default:r.__esModule\?r:Object.create(r,{__esModule:{value:!0}});return @requireMap.@set(_,@createCommonJSModule(_,b,!0)),b}const L=@createCommonJSModule(_,{},!1);@requireMap.@set(_,L);var M=this.@require(_,L);if(M===-1){try{M=@requireESM(_)}catch(h){throw @requireMap.@delete(_),h}if(f=@Loader.registry.@get(_),f\?.evaluated&&(f.state\?\?0)>=@ModuleReady){const h=@Loader.getModuleNamespaceObject(f.module);return L.exports=h\?.[@commonJSSymbol]===0||h\?.default\?.[@commonJSSymbol]===0\?h.default:h.__esModule\?h:Object.create(h,{__esModule:{value:!0}})}}return @evaluateCommonJSModule(L),L.exports})\n"; // requireResolve const JSC::ConstructAbility s_moduleRequireResolveCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -830,7 +830,7 @@ const JSC::ConstructorKind s_jsBufferPrototypeReadIntLECodeConstructorKind = JSC const JSC::ImplementationVisibility s_jsBufferPrototypeReadIntLECodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_jsBufferPrototypeReadIntLECodeLength = 528; static const JSC::Intrinsic s_jsBufferPrototypeReadIntLECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadIntLECode = "(function (d,r){\"use strict\";const _=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(r){case 1:return _.getInt8(d);case 2:return _.getInt16(d,!0);case 3:{const u=_.getUint16(d,!0)+_.getUint8(d+2)*65536;return u|(u&8388608)*510}case 4:return _.getInt32(d,!0);case 5:{const u=_.getUint8(d+4);return(u|(u&128)*33554430)*4294967296+_.getUint32(d,!0)}case 6:{const u=_.getUint16(d+4,!0);return(u|(u&32768)*131070)*4294967296+_.getUint32(d,!0)}}@throwRangeError(\"byteLength must be >= 1 and <= 6\")})\n"; +const char* const s_jsBufferPrototypeReadIntLECode = "(function (d,_){\"use strict\";const u=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(_){case 1:return u.getInt8(d);case 2:return u.getInt16(d,!0);case 3:{const r=u.getUint16(d,!0)+u.getUint8(d+2)*65536;return r|(r&8388608)*510}case 4:return u.getInt32(d,!0);case 5:{const r=u.getUint8(d+4);return(r|(r&128)*33554430)*4294967296+u.getUint32(d,!0)}case 6:{const r=u.getUint16(d+4,!0);return(r|(r&32768)*131070)*4294967296+u.getUint32(d,!0)}}@throwRangeError(\"byteLength must be >= 1 and <= 6\")})\n"; // readIntBE const JSC::ConstructAbility s_jsBufferPrototypeReadIntBECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1038,7 +1038,7 @@ const JSC::ConstructorKind s_jsBufferPrototypeWriteFloatLECodeConstructorKind = const JSC::ImplementationVisibility s_jsBufferPrototypeWriteFloatLECodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_jsBufferPrototypeWriteFloatLECodeLength = 137; static const JSC::Intrinsic s_jsBufferPrototypeWriteFloatLECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteFloatLECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setFloat32(c,d,!0),c+4})\n"; +const char* const s_jsBufferPrototypeWriteFloatLECode = "(function (c,d){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setFloat32(d,c,!0),d+4})\n"; // writeFloatBE const JSC::ConstructAbility s_jsBufferPrototypeWriteFloatBECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1046,7 +1046,7 @@ const JSC::ConstructorKind s_jsBufferPrototypeWriteFloatBECodeConstructorKind = const JSC::ImplementationVisibility s_jsBufferPrototypeWriteFloatBECodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_jsBufferPrototypeWriteFloatBECodeLength = 137; static const JSC::Intrinsic s_jsBufferPrototypeWriteFloatBECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteFloatBECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setFloat32(c,d,!1),c+4})\n"; +const char* const s_jsBufferPrototypeWriteFloatBECode = "(function (c,d){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setFloat32(d,c,!1),d+4})\n"; // writeDoubleLE const JSC::ConstructAbility s_jsBufferPrototypeWriteDoubleLECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1142,7 +1142,7 @@ const JSC::ConstructorKind s_jsBufferPrototypeBase64WriteCodeConstructorKind = J const JSC::ImplementationVisibility s_jsBufferPrototypeBase64WriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_jsBufferPrototypeBase64WriteCodeLength = 67; static const JSC::Intrinsic s_jsBufferPrototypeBase64WriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeBase64WriteCode = "(function (a,d,r){\"use strict\";return this.write(a,d,r,\"base64\")})\n"; +const char* const s_jsBufferPrototypeBase64WriteCode = "(function (a,r,d){\"use strict\";return this.write(a,r,d,\"base64\")})\n"; // base64urlWrite const JSC::ConstructAbility s_jsBufferPrototypeBase64urlWriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1150,7 +1150,7 @@ const JSC::ConstructorKind s_jsBufferPrototypeBase64urlWriteCodeConstructorKind const JSC::ImplementationVisibility s_jsBufferPrototypeBase64urlWriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_jsBufferPrototypeBase64urlWriteCodeLength = 70; static const JSC::Intrinsic s_jsBufferPrototypeBase64urlWriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeBase64urlWriteCode = "(function (a,d,r){\"use strict\";return this.write(a,d,r,\"base64url\")})\n"; +const char* const s_jsBufferPrototypeBase64urlWriteCode = "(function (d,a,r){\"use strict\";return this.write(d,a,r,\"base64url\")})\n"; // hexWrite const JSC::ConstructAbility s_jsBufferPrototypeHexWriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1238,7 +1238,7 @@ const JSC::ConstructorKind s_jsBufferPrototypeSliceCodeConstructorKind = JSC::Co const JSC::ImplementationVisibility s_jsBufferPrototypeSliceCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_jsBufferPrototypeSliceCodeLength = 260; static const JSC::Intrinsic s_jsBufferPrototypeSliceCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeSliceCode = "(function (p,m){\"use strict\";var{buffer:c,byteOffset:k,byteLength:v}=this;function q(z,i){if(z=@trunc(z),z===0||@isNaN(z))return 0;else if(z<0)return z+=i,z>0\?z:0;else return zw\?x-w:0)})\n"; +const char* const s_jsBufferPrototypeSliceCode = "(function (p,q){\"use strict\";var{buffer:m,byteOffset:v,byteLength:c}=this;function w(z,k){if(z=@trunc(z),z===0||@isNaN(z))return 0;else if(z<0)return z+=k,z>0\?z:0;else return zi\?x-i:0)})\n"; // parent const JSC::ConstructAbility s_jsBufferPrototypeParentCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1312,7 +1312,7 @@ const JSC::ConstructorKind s_readableByteStreamControllerByobRequestCodeConstruc const JSC::ImplementationVisibility s_readableByteStreamControllerByobRequestCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableByteStreamControllerByobRequestCodeLength = 523; static const JSC::Intrinsic s_readableByteStreamControllerByobRequestCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamControllerByobRequestCode = "(function (){\"use strict\";if(!@isReadableByteStreamController(this))throw @makeGetterTypeError(\"ReadableByteStreamController\",\"byobRequest\");var _=@getByIdDirectPrivate(this,\"byobRequest\");if(_===@undefined){var a=@getByIdDirectPrivate(this,\"pendingPullIntos\");const l=a.peek();if(l){const m=new @Uint8Array(l.buffer,l.byteOffset+l.bytesFilled,l.byteLength-l.bytesFilled);@putByIdDirectPrivate(this,\"byobRequest\",new @ReadableStreamBYOBRequest(this,m,@isReadableStream))}}return @getByIdDirectPrivate(this,\"byobRequest\")})\n"; +const char* const s_readableByteStreamControllerByobRequestCode = "(function (){\"use strict\";if(!@isReadableByteStreamController(this))throw @makeGetterTypeError(\"ReadableByteStreamController\",\"byobRequest\");var _=@getByIdDirectPrivate(this,\"byobRequest\");if(_===@undefined){var l=@getByIdDirectPrivate(this,\"pendingPullIntos\");const m=l.peek();if(m){const a=new @Uint8Array(m.buffer,m.byteOffset+m.bytesFilled,m.byteLength-m.bytesFilled);@putByIdDirectPrivate(this,\"byobRequest\",new @ReadableStreamBYOBRequest(this,a,@isReadableStream))}}return @getByIdDirectPrivate(this,\"byobRequest\")})\n"; // desiredSize const JSC::ConstructAbility s_readableByteStreamControllerDesiredSizeCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1338,7 +1338,7 @@ const JSC::ConstructorKind s_consoleObjectAsyncIteratorCodeConstructorKind = JSC const JSC::ImplementationVisibility s_consoleObjectAsyncIteratorCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_consoleObjectAsyncIteratorCodeLength = 577; static const JSC::Intrinsic s_consoleObjectAsyncIteratorCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_consoleObjectAsyncIteratorCode = "(function (){\"use strict\";const j=async function*w(){var _=@Bun.stdin.stream().getReader(),B=new globalThis.TextDecoder(\"utf-8\",{fatal:!1}),m,D=@Bun.indexOfLine;try{while(!0){var F,q,G;const L=_.readMany();if(@isPromise(L))({done:F,value:q}=await L);else({done:F,value:q}=L);if(F){if(G)yield B.decode(G);return}var H;for(let M of q){if(H=M,G)H=@Buffer.concat([G,M]),G=null;var J=0,K=D(H,J);while(K!==-1)yield B.decode(H.subarray(J,K)),J=K+1,K=D(H,J);G=H.subarray(J)}}}catch(L){m=L}finally{if(_.releaseLock(),m)throw m}},z=globalThis.Symbol.asyncIterator;return this[z]=j,j()})\n"; +const char* const s_consoleObjectAsyncIteratorCode = "(function (){\"use strict\";const j=async function*z(){var D=@Bun.stdin.stream().getReader(),F=new globalThis.TextDecoder(\"utf-8\",{fatal:!1}),G,H=@Bun.indexOfLine;try{while(!0){var J,K,w;const L=D.readMany();if(@isPromise(L))({done:J,value:K}=await L);else({done:J,value:K}=L);if(J){if(w)yield F.decode(w);return}var _;for(let M of K){if(_=M,w)_=@Buffer.concat([w,M]),w=null;var q=0,A=H(_,q);while(A!==-1)yield F.decode(_.subarray(q,A)),q=A+1,A=H(_,q);w=_.subarray(q)}}}catch(L){G=L}finally{if(D.releaseLock(),G)throw G}},m=globalThis.Symbol.asyncIterator;return this[m]=j,j()})\n"; // write const JSC::ConstructAbility s_consoleObjectWriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1346,7 +1346,7 @@ const JSC::ConstructorKind s_consoleObjectWriteCodeConstructorKind = JSC::Constr const JSC::ImplementationVisibility s_consoleObjectWriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_consoleObjectWriteCodeLength = 310; static const JSC::Intrinsic s_consoleObjectWriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_consoleObjectWriteCode = "(function (d){\"use strict\";var _=@getByIdDirectPrivate(this,\"writer\");if(!_){var b=@toLength(d\?.length\?\?0);_=@Bun.stdout.writer({highWaterMark:b>65536\?b:65536}),@putByIdDirectPrivate(this,\"writer\",_)}var c=_.write(d);const f=@argumentCount();for(var a=1;a65536\?_:65536}),@putByIdDirectPrivate(this,\"writer\",d)}var b=d.write(a);const c=@argumentCount();for(var f=1;f@promiseInvokeOrNoopMethod(f,w,[C]),D=(x)=>@promiseInvokeOrNoopMethod(f,B,[x]);@putByIdDirectPrivate(C,\"pullAlgorithm\",q),@putByIdDirectPrivate(C,\"cancelAlgorithm\",D),@putByIdDirectPrivate(C,\"pull\",@readableStreamDefaultControllerPull),@putByIdDirectPrivate(C,\"cancel\",@readableStreamDefaultControllerCancel),@putByIdDirectPrivate(_,\"readableStreamController\",C),@readableStreamDefaultControllerStart(C)})\n"; +const char* const s_readableStreamInternalsSetupReadableStreamDefaultControllerCode = "(function (_,w,f,b,q,v,x){\"use strict\";const B=new @ReadableStreamDefaultController(_,w,f,b,@isReadableStream),C=()=>@promiseInvokeOrNoopMethod(w,v,[B]),j=(D)=>@promiseInvokeOrNoopMethod(w,x,[D]);@putByIdDirectPrivate(B,\"pullAlgorithm\",C),@putByIdDirectPrivate(B,\"cancelAlgorithm\",j),@putByIdDirectPrivate(B,\"pull\",@readableStreamDefaultControllerPull),@putByIdDirectPrivate(B,\"cancel\",@readableStreamDefaultControllerCancel),@putByIdDirectPrivate(_,\"readableStreamController\",B),@readableStreamDefaultControllerStart(B)})\n"; // createReadableStreamController const JSC::ConstructAbility s_readableStreamInternalsCreateReadableStreamControllerCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1412,7 +1412,7 @@ const JSC::ConstructorKind s_readableStreamInternalsCreateReadableStreamControll const JSC::ImplementationVisibility s_readableStreamInternalsCreateReadableStreamControllerCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsCreateReadableStreamControllerCodeLength = 671; static const JSC::Intrinsic s_readableStreamInternalsCreateReadableStreamControllerCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsCreateReadableStreamControllerCode = "(function (w,C,A){\"use strict\";const b=C.type,f=@toString(b);if(f===\"bytes\"){if(A.highWaterMark===@undefined)A.highWaterMark=0;if(A.size!==@undefined)@throwRangeError(\"Strategy for a ReadableByteStreamController cannot have a size\");@putByIdDirectPrivate(w,\"readableStreamController\",new @ReadableByteStreamController(w,C,A.highWaterMark,@isReadableStream))}else if(f===\"direct\"){var v=A\?.highWaterMark;@initializeArrayBufferStream.@call(w,C,v)}else if(b===@undefined){if(A.highWaterMark===@undefined)A.highWaterMark=1;@setupReadableStreamDefaultController(w,C,A.size,A.highWaterMark,C.start,C.pull,C.cancel)}else @throwRangeError(\"Invalid type for underlying source\")})\n"; +const char* const s_readableStreamInternalsCreateReadableStreamControllerCode = "(function (f,v,w){\"use strict\";const A=v.type,C=@toString(A);if(C===\"bytes\"){if(w.highWaterMark===@undefined)w.highWaterMark=0;if(w.size!==@undefined)@throwRangeError(\"Strategy for a ReadableByteStreamController cannot have a size\");@putByIdDirectPrivate(f,\"readableStreamController\",new @ReadableByteStreamController(f,v,w.highWaterMark,@isReadableStream))}else if(C===\"direct\"){var b=w\?.highWaterMark;@initializeArrayBufferStream.@call(f,v,b)}else if(A===@undefined){if(w.highWaterMark===@undefined)w.highWaterMark=1;@setupReadableStreamDefaultController(f,v,w.size,w.highWaterMark,v.start,v.pull,v.cancel)}else @throwRangeError(\"Invalid type for underlying source\")})\n"; // readableStreamDefaultControllerStart const JSC::ConstructAbility s_readableStreamInternalsReadableStreamDefaultControllerStartCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1420,7 +1420,7 @@ const JSC::ConstructorKind s_readableStreamInternalsReadableStreamDefaultControl const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamDefaultControllerStartCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsReadableStreamDefaultControllerStartCodeLength = 465; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamDefaultControllerStartCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamDefaultControllerStartCode = "(function (B){\"use strict\";if(@getByIdDirectPrivate(B,\"started\")!==-1)return;const a=@getByIdDirectPrivate(B,\"underlyingSource\"),p=a.start;@putByIdDirectPrivate(B,\"started\",0),@promiseInvokeOrNoopMethodNoCatch(a,p,[B]).@then(()=>{@putByIdDirectPrivate(B,\"started\",1),@assert(!@getByIdDirectPrivate(B,\"pulling\")),@assert(!@getByIdDirectPrivate(B,\"pullAgain\")),@readableStreamDefaultControllerCallPullIfNeeded(B)},(m)=>{@readableStreamDefaultControllerError(B,m)})})\n"; +const char* const s_readableStreamInternalsReadableStreamDefaultControllerStartCode = "(function (m){\"use strict\";if(@getByIdDirectPrivate(m,\"started\")!==-1)return;const B=@getByIdDirectPrivate(m,\"underlyingSource\"),a=B.start;@putByIdDirectPrivate(m,\"started\",0),@promiseInvokeOrNoopMethodNoCatch(B,a,[m]).@then(()=>{@putByIdDirectPrivate(m,\"started\",1),@assert(!@getByIdDirectPrivate(m,\"pulling\")),@assert(!@getByIdDirectPrivate(m,\"pullAgain\")),@readableStreamDefaultControllerCallPullIfNeeded(m)},(p)=>{@readableStreamDefaultControllerError(m,p)})})\n"; // readableStreamPipeToWritableStream const JSC::ConstructAbility s_readableStreamInternalsReadableStreamPipeToWritableStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1428,7 +1428,7 @@ const JSC::ConstructorKind s_readableStreamInternalsReadableStreamPipeToWritable const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamPipeToWritableStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsReadableStreamPipeToWritableStreamCodeLength = 1631; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamPipeToWritableStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamPipeToWritableStreamCode = "(function (D,w,_,x,f,z){\"use strict\";if(@assert(@isReadableStream(D)),@assert(@isWritableStream(w)),@assert(!@isReadableStreamLocked(D)),@assert(!@isWritableStreamLocked(w)),@assert(z===@undefined||@isAbortSignal(z)),@getByIdDirectPrivate(D,\"underlyingByteSource\")!==@undefined)return @Promise.@reject(\"Piping to a readable bytestream is not supported\");let E={source:D,destination:w,preventAbort:x,preventCancel:f,preventClose:_,signal:z};if(E.reader=@acquireReadableStreamDefaultReader(D),E.writer=@acquireWritableStreamDefaultWriter(w),@putByIdDirectPrivate(D,\"disturbed\",!0),E.finalized=!1,E.shuttingDown=!1,E.promiseCapability=@newPromiseCapability(@Promise),E.pendingReadPromiseCapability=@newPromiseCapability(@Promise),E.pendingReadPromiseCapability.@resolve.@call(),E.pendingWritePromise=@Promise.@resolve(),z!==@undefined){const B=(F)=>{if(E.finalized)return;@pipeToShutdownWithAction(E,()=>{const G=!E.preventAbort&&@getByIdDirectPrivate(E.destination,\"state\")===\"writable\"\?@writableStreamAbort(E.destination,F):@Promise.@resolve(),I=!E.preventCancel&&@getByIdDirectPrivate(E.source,\"state\")===@streamReadable\?@readableStreamCancel(E.source,F):@Promise.@resolve();let J=@newPromiseCapability(@Promise),K=!0,L=()=>{if(K){K=!1;return}J.@resolve.@call()},k=(q)=>{J.@reject.@call(@undefined,q)};return G.@then(L,k),I.@then(L,k),J.@promise},F)};if(@whenSignalAborted(z,B))return E.promiseCapability.@promise}return @pipeToErrorsMustBePropagatedForward(E),@pipeToErrorsMustBePropagatedBackward(E),@pipeToClosingMustBePropagatedForward(E),@pipeToClosingMustBePropagatedBackward(E),@pipeToLoop(E),E.promiseCapability.@promise})\n"; +const char* const s_readableStreamInternalsReadableStreamPipeToWritableStreamCode = "(function (f,q,w,x,F,G){\"use strict\";if(@assert(@isReadableStream(f)),@assert(@isWritableStream(q)),@assert(!@isReadableStreamLocked(f)),@assert(!@isWritableStreamLocked(q)),@assert(G===@undefined||@isAbortSignal(G)),@getByIdDirectPrivate(f,\"underlyingByteSource\")!==@undefined)return @Promise.@reject(\"Piping to a readable bytestream is not supported\");let _={source:f,destination:q,preventAbort:x,preventCancel:F,preventClose:w,signal:G};if(_.reader=@acquireReadableStreamDefaultReader(f),_.writer=@acquireWritableStreamDefaultWriter(q),@putByIdDirectPrivate(f,\"disturbed\",!0),_.finalized=!1,_.shuttingDown=!1,_.promiseCapability=@newPromiseCapability(@Promise),_.pendingReadPromiseCapability=@newPromiseCapability(@Promise),_.pendingReadPromiseCapability.@resolve.@call(),_.pendingWritePromise=@Promise.@resolve(),G!==@undefined){const H=(I)=>{if(_.finalized)return;@pipeToShutdownWithAction(_,()=>{const E=!_.preventAbort&&@getByIdDirectPrivate(_.destination,\"state\")===\"writable\"\?@writableStreamAbort(_.destination,I):@Promise.@resolve(),z=!_.preventCancel&&@getByIdDirectPrivate(_.source,\"state\")===@streamReadable\?@readableStreamCancel(_.source,I):@Promise.@resolve();let B=@newPromiseCapability(@Promise),K=!0,T=()=>{if(K){K=!1;return}B.@resolve.@call()},L=(k)=>{B.@reject.@call(@undefined,k)};return E.@then(T,L),z.@then(T,L),B.@promise},I)};if(@whenSignalAborted(G,H))return _.promiseCapability.@promise}return @pipeToErrorsMustBePropagatedForward(_),@pipeToErrorsMustBePropagatedBackward(_),@pipeToClosingMustBePropagatedForward(_),@pipeToClosingMustBePropagatedBackward(_),@pipeToLoop(_),_.promiseCapability.@promise})\n"; // pipeToLoop const JSC::ConstructAbility s_readableStreamInternalsPipeToLoopCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1484,7 +1484,7 @@ const JSC::ConstructorKind s_readableStreamInternalsPipeToShutdownWithActionCode const JSC::ImplementationVisibility s_readableStreamInternalsPipeToShutdownWithActionCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsPipeToShutdownWithActionCodeLength = 458; static const JSC::Intrinsic s_readableStreamInternalsPipeToShutdownWithActionCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsPipeToShutdownWithActionCode = "(function (_,m){\"use strict\";if(_.shuttingDown)return;_.shuttingDown=!0;const g=arguments.length>2,h=arguments[2],b=()=>{m().@then(()=>{if(g)@pipeToFinalize(_,h);else @pipeToFinalize(_)},(d)=>{@pipeToFinalize(_,d)})};if(@getByIdDirectPrivate(_.destination,\"state\")===\"writable\"&&!@writableStreamCloseQueuedOrInFlight(_.destination)){_.pendingReadPromiseCapability.@promise.@then(()=>{_.pendingWritePromise.@then(b,b)},(j)=>@pipeToFinalize(_,j));return}b()})\n"; +const char* const s_readableStreamInternalsPipeToShutdownWithActionCode = "(function (m,b){\"use strict\";if(m.shuttingDown)return;m.shuttingDown=!0;const d=arguments.length>2,g=arguments[2],j=()=>{b().@then(()=>{if(d)@pipeToFinalize(m,g);else @pipeToFinalize(m)},(h)=>{@pipeToFinalize(m,h)})};if(@getByIdDirectPrivate(m.destination,\"state\")===\"writable\"&&!@writableStreamCloseQueuedOrInFlight(m.destination)){m.pendingReadPromiseCapability.@promise.@then(()=>{m.pendingWritePromise.@then(j,j)},(_)=>@pipeToFinalize(m,_));return}j()})\n"; // pipeToShutdown const JSC::ConstructAbility s_readableStreamInternalsPipeToShutdownCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1492,7 +1492,7 @@ const JSC::ConstructorKind s_readableStreamInternalsPipeToShutdownCodeConstructo const JSC::ImplementationVisibility s_readableStreamInternalsPipeToShutdownCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsPipeToShutdownCodeLength = 411; static const JSC::Intrinsic s_readableStreamInternalsPipeToShutdownCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsPipeToShutdownCode = "(function (_){\"use strict\";if(_.shuttingDown)return;_.shuttingDown=!0;const m=arguments.length>1,u=arguments[1],d=()=>{if(m)@pipeToFinalize(_,u);else @pipeToFinalize(_)};if(@getByIdDirectPrivate(_.destination,\"state\")===\"writable\"&&!@writableStreamCloseQueuedOrInFlight(_.destination)){_.pendingReadPromiseCapability.@promise.@then(()=>{_.pendingWritePromise.@then(d,d)},(I)=>@pipeToFinalize(_,I));return}d()})\n"; +const char* const s_readableStreamInternalsPipeToShutdownCode = "(function (_){\"use strict\";if(_.shuttingDown)return;_.shuttingDown=!0;const d=arguments.length>1,m=arguments[1],u=()=>{if(d)@pipeToFinalize(_,m);else @pipeToFinalize(_)};if(@getByIdDirectPrivate(_.destination,\"state\")===\"writable\"&&!@writableStreamCloseQueuedOrInFlight(_.destination)){_.pendingReadPromiseCapability.@promise.@then(()=>{_.pendingWritePromise.@then(u,u)},(I)=>@pipeToFinalize(_,I));return}u()})\n"; // pipeToFinalize const JSC::ConstructAbility s_readableStreamInternalsPipeToFinalizeCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1516,7 +1516,7 @@ const JSC::ConstructorKind s_readableStreamInternalsReadableStreamTeePullFunctio const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamTeePullFunctionCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsReadableStreamTeePullFunctionCodeLength = 764; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamTeePullFunctionCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamTeePullFunctionCode = "(function (i,m,_){\"use strict\";return function(){@Promise.prototype.@then.@call(@readableStreamDefaultReaderRead(m),function(f){if(@assert(@isObject(f)),@assert(typeof f.done===\"boolean\"),f.done&&!i.closedOrErrored){if(!i.canceled1)@readableStreamDefaultControllerClose(i.branch1.@readableStreamController);if(!i.canceled2)@readableStreamDefaultControllerClose(i.branch2.@readableStreamController);if(i.closedOrErrored=!0,!i.canceled1||!i.canceled2)i.cancelPromiseCapability.@resolve.@call()}if(i.closedOrErrored)return;if(!i.canceled1)@readableStreamDefaultControllerEnqueue(i.branch1.@readableStreamController,f.value);if(!i.canceled2)@readableStreamDefaultControllerEnqueue(i.branch2.@readableStreamController,_\?@structuredCloneForStream(f.value):f.value)})}})\n"; +const char* const s_readableStreamInternalsReadableStreamTeePullFunctionCode = "(function (i,_,f){\"use strict\";return function(){@Promise.prototype.@then.@call(@readableStreamDefaultReaderRead(_),function(m){if(@assert(@isObject(m)),@assert(typeof m.done===\"boolean\"),m.done&&!i.closedOrErrored){if(!i.canceled1)@readableStreamDefaultControllerClose(i.branch1.@readableStreamController);if(!i.canceled2)@readableStreamDefaultControllerClose(i.branch2.@readableStreamController);if(i.closedOrErrored=!0,!i.canceled1||!i.canceled2)i.cancelPromiseCapability.@resolve.@call()}if(i.closedOrErrored)return;if(!i.canceled1)@readableStreamDefaultControllerEnqueue(i.branch1.@readableStreamController,m.value);if(!i.canceled2)@readableStreamDefaultControllerEnqueue(i.branch2.@readableStreamController,f\?@structuredCloneForStream(m.value):m.value)})}})\n"; // readableStreamTeeBranch1CancelFunction const JSC::ConstructAbility s_readableStreamInternalsReadableStreamTeeBranch1CancelFunctionCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1524,7 +1524,7 @@ const JSC::ConstructorKind s_readableStreamInternalsReadableStreamTeeBranch1Canc const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamTeeBranch1CancelFunctionCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsReadableStreamTeeBranch1CancelFunctionCodeLength = 258; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamTeeBranch1CancelFunctionCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamTeeBranch1CancelFunctionCode = "(function (c,i){\"use strict\";return function(d){if(c.canceled1=!0,c.reason1=d,c.canceled2)@readableStreamCancel(i,[c.reason1,c.reason2]).@then(c.cancelPromiseCapability.@resolve,c.cancelPromiseCapability.@reject);return c.cancelPromiseCapability.@promise}})\n"; +const char* const s_readableStreamInternalsReadableStreamTeeBranch1CancelFunctionCode = "(function (c,d){\"use strict\";return function(i){if(c.canceled1=!0,c.reason1=i,c.canceled2)@readableStreamCancel(d,[c.reason1,c.reason2]).@then(c.cancelPromiseCapability.@resolve,c.cancelPromiseCapability.@reject);return c.cancelPromiseCapability.@promise}})\n"; // readableStreamTeeBranch2CancelFunction const JSC::ConstructAbility s_readableStreamInternalsReadableStreamTeeBranch2CancelFunctionCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1564,7 +1564,7 @@ const JSC::ConstructorKind s_readableStreamInternalsReadDirectStreamCodeConstruc const JSC::ImplementationVisibility s_readableStreamInternalsReadDirectStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsReadDirectStreamCodeLength = 900; static const JSC::Intrinsic s_readableStreamInternalsReadDirectStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadDirectStreamCode = "(function (j,w,_){\"use strict\";@putByIdDirectPrivate(j,\"underlyingSource\",@undefined),@putByIdDirectPrivate(j,\"start\",@undefined);function x(q,A){if(A&&_\?.cancel){try{var B=_.cancel(A);@markPromiseAsHandled(B)}catch(v){}_=@undefined}if(q){if(@putByIdDirectPrivate(q,\"readableStreamController\",@undefined),@putByIdDirectPrivate(q,\"reader\",@undefined),A)@putByIdDirectPrivate(q,\"state\",@streamErrored),@putByIdDirectPrivate(q,\"storedError\",A);else @putByIdDirectPrivate(q,\"state\",@streamClosed);q=@undefined}}if(!_.pull){x();return}if(!@isCallable(_.pull)){x(),@throwTypeError(\"pull is not a function\");return}@putByIdDirectPrivate(j,\"readableStreamController\",w);const f=@getByIdDirectPrivate(j,\"highWaterMark\");w.start({highWaterMark:!f||f<64\?64:f}),@startDirectStream.@call(w,j,_.pull,x),@putByIdDirectPrivate(j,\"reader\",{});var z=_.pull(w);if(w=@undefined,z&&@isPromise(z))return z.@then(()=>{})})\n"; +const char* const s_readableStreamInternalsReadDirectStreamCode = "(function (_,f,j){\"use strict\";@putByIdDirectPrivate(_,\"underlyingSource\",@undefined),@putByIdDirectPrivate(_,\"start\",@undefined);function q(x,z){if(z&&j\?.cancel){try{var A=j.cancel(z);@markPromiseAsHandled(A)}catch(B){}j=@undefined}if(x){if(@putByIdDirectPrivate(x,\"readableStreamController\",@undefined),@putByIdDirectPrivate(x,\"reader\",@undefined),z)@putByIdDirectPrivate(x,\"state\",@streamErrored),@putByIdDirectPrivate(x,\"storedError\",z);else @putByIdDirectPrivate(x,\"state\",@streamClosed);x=@undefined}}if(!j.pull){q();return}if(!@isCallable(j.pull)){q(),@throwTypeError(\"pull is not a function\");return}@putByIdDirectPrivate(_,\"readableStreamController\",f);const v=@getByIdDirectPrivate(_,\"highWaterMark\");f.start({highWaterMark:!v||v<64\?64:v}),@startDirectStream.@call(f,_,j.pull,q),@putByIdDirectPrivate(_,\"reader\",{});var w=j.pull(f);if(f=@undefined,w&&@isPromise(w))return w.@then(()=>{})})\n"; // assignToStream const JSC::ConstructAbility s_readableStreamInternalsAssignToStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1572,7 +1572,7 @@ const JSC::ConstructorKind s_readableStreamInternalsAssignToStreamCodeConstructo const JSC::ImplementationVisibility s_readableStreamInternalsAssignToStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Private; const int s_readableStreamInternalsAssignToStreamCodeLength = 221; static const JSC::Intrinsic s_readableStreamInternalsAssignToStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsAssignToStreamCode = "(function (h,_){\"use strict\";var b=@getByIdDirectPrivate(h,\"underlyingSource\");if(b)try{return @readDirectStream(h,_,b)}catch(f){throw f}finally{b=@undefined,h=@undefined,_=@undefined}return @readStreamIntoSink(h,_,!0)})\n"; +const char* const s_readableStreamInternalsAssignToStreamCode = "(function (_,b){\"use strict\";var f=@getByIdDirectPrivate(_,\"underlyingSource\");if(f)try{return @readDirectStream(_,b,f)}catch(h){throw h}finally{f=@undefined,_=@undefined,b=@undefined}return @readStreamIntoSink(_,b,!0)})\n"; // readStreamIntoSink const JSC::ConstructAbility s_readableStreamInternalsReadStreamIntoSinkCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1580,7 +1580,7 @@ const JSC::ConstructorKind s_readableStreamInternalsReadStreamIntoSinkCodeConstr const JSC::ImplementationVisibility s_readableStreamInternalsReadStreamIntoSinkCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsReadStreamIntoSinkCodeLength = 1395; static const JSC::Intrinsic s_readableStreamInternalsReadStreamIntoSinkCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadStreamIntoSinkCode = "(async function (f,I,q){\"use strict\";var z=!1,A=!1;try{var B=f.getReader(),D=B.readMany();if(D&&@isPromise(D))D=await D;if(D.done)return z=!0,I.end();var E=D.value.length;const J=@getByIdDirectPrivate(f,\"highWaterMark\");if(q)@startDirectStream.@call(I,f,@undefined,()=>!A&&@markPromiseAsHandled(f.cancel()));I.start({highWaterMark:J||0});for(var F=0,G=D.value,_=D.value.length;F<_;F++)I.write(G[F]);var c=@getByIdDirectPrivate(f,\"state\");if(c===@streamClosed)return z=!0,I.end();while(!0){var{value:P,done:x}=await B.read();if(x)return z=!0,I.end();I.write(P)}}catch(J){A=!0;try{B=@undefined;const K=f.cancel(J);@markPromiseAsHandled(K)}catch(K){}if(I&&!z){z=!0;try{I.close(J)}catch(K){throw new globalThis.AggregateError([J,K])}}throw J}finally{if(B){try{B.releaseLock()}catch(K){}B=@undefined}I=@undefined;var c=@getByIdDirectPrivate(f,\"state\");if(f){var H=@getByIdDirectPrivate(f,\"readableStreamController\");if(H){if(@getByIdDirectPrivate(H,\"underlyingSource\"))@putByIdDirectPrivate(H,\"underlyingSource\",@undefined);if(@getByIdDirectPrivate(H,\"controlledReadableStream\"))@putByIdDirectPrivate(H,\"controlledReadableStream\",@undefined);if(@putByIdDirectPrivate(f,\"readableStreamController\",null),@getByIdDirectPrivate(f,\"underlyingSource\"))@putByIdDirectPrivate(f,\"underlyingSource\",@undefined);H=@undefined}if(!A&&c!==@streamClosed&&c!==@streamErrored)@readableStreamClose(f);f=@undefined}}})\n"; +const char* const s_readableStreamInternalsReadStreamIntoSinkCode = "(async function (_,E,c){\"use strict\";var f=!1,B=!1;try{var D=_.getReader(),F=D.readMany();if(F&&@isPromise(F))F=await F;if(F.done)return f=!0,E.end();var G=F.value.length;const q=@getByIdDirectPrivate(_,\"highWaterMark\");if(c)@startDirectStream.@call(E,_,@undefined,()=>!B&&@markPromiseAsHandled(_.cancel()));E.start({highWaterMark:q||0});for(var H=0,I=F.value,J=F.value.length;H{var j=@createFulfilledPromise({value:b,done:!1});return b=@undefined,@readableStreamClose(v),v=@undefined,j}}else if(this._pendingRead){var y=this._pendingRead;this._pendingRead=@undefined,@putByIdDirectPrivate(this,\"pull\",@noopDoneFunction),@fulfillPromise(y,{value:@undefined,done:!0})}@readableStreamClose(v)})\n"; +const char* const s_readableStreamInternalsOnCloseDirectStreamCode = "(function (c){\"use strict\";var v=this.@controlledReadableStream;if(!v||@getByIdDirectPrivate(v,\"state\")!==@streamReadable)return;if(this._deferClose!==0){this._deferClose=1,this._deferCloseReason=c;return}if(@putByIdDirectPrivate(v,\"state\",@streamClosing),typeof this.@underlyingSource.close===\"function\")try{this.@underlyingSource.close.@call(this.@underlyingSource,c)}catch(j){}var b;try{b=this.@sink.end(),@putByIdDirectPrivate(this,\"sink\",@undefined)}catch(j){if(this._pendingRead){var y=this._pendingRead;this._pendingRead=@undefined,@rejectPromise(y,j)}@readableStreamError(v,j);return}this.error=this.flush=this.write=this.close=this.end=@onReadableStreamDirectControllerClosed;var S=@getByIdDirectPrivate(v,\"reader\");if(S&&@isReadableStreamDefaultReader(S)){var C=this._pendingRead;if(C&&@isPromise(C)&&b\?.byteLength){this._pendingRead=@undefined,@fulfillPromise(C,{value:b,done:!1}),@readableStreamClose(v);return}}if(b\?.byteLength){var B=@getByIdDirectPrivate(S,\"readRequests\");if(B\?.isNotEmpty()){@readableStreamFulfillReadRequest(v,b,!1),@readableStreamClose(v);return}@putByIdDirectPrivate(v,\"state\",@streamReadable),this.@pull=()=>{var j=@createFulfilledPromise({value:b,done:!1});return b=@undefined,@readableStreamClose(v),v=@undefined,j}}else if(this._pendingRead){var y=this._pendingRead;this._pendingRead=@undefined,@putByIdDirectPrivate(this,\"pull\",@noopDoneFunction),@fulfillPromise(y,{value:@undefined,done:!0})}@readableStreamClose(v)})\n"; // onFlushDirectStream const JSC::ConstructAbility s_readableStreamInternalsOnFlushDirectStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1636,7 +1636,7 @@ const JSC::ConstructorKind s_readableStreamInternalsOnFlushDirectStreamCodeConst const JSC::ImplementationVisibility s_readableStreamInternalsOnFlushDirectStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsOnFlushDirectStreamCodeLength = 591; static const JSC::Intrinsic s_readableStreamInternalsOnFlushDirectStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsOnFlushDirectStreamCode = "(function (){\"use strict\";var c=this.@controlledReadableStream,B=@getByIdDirectPrivate(c,\"reader\");if(!B||!@isReadableStreamDefaultReader(B))return;var b=this._pendingRead;if(this._pendingRead=@undefined,b&&@isPromise(b)){var i=this.@sink.flush();if(i\?.byteLength)this._pendingRead=@getByIdDirectPrivate(c,\"readRequests\")\?.shift(),@fulfillPromise(b,{value:i,done:!1});else this._pendingRead=b}else if(@getByIdDirectPrivate(c,\"readRequests\")\?.isNotEmpty()){var i=this.@sink.flush();if(i\?.byteLength)@readableStreamFulfillReadRequest(c,i,!1)}else if(this._deferFlush===-1)this._deferFlush=1})\n"; +const char* const s_readableStreamInternalsOnFlushDirectStreamCode = "(function (){\"use strict\";var c=this.@controlledReadableStream,b=@getByIdDirectPrivate(c,\"reader\");if(!b||!@isReadableStreamDefaultReader(b))return;var i=this._pendingRead;if(this._pendingRead=@undefined,i&&@isPromise(i)){var B=this.@sink.flush();if(B\?.byteLength)this._pendingRead=@getByIdDirectPrivate(c,\"readRequests\")\?.shift(),@fulfillPromise(i,{value:B,done:!1});else this._pendingRead=i}else if(@getByIdDirectPrivate(c,\"readRequests\")\?.isNotEmpty()){var B=this.@sink.flush();if(B\?.byteLength)@readableStreamFulfillReadRequest(c,B,!1)}else if(this._deferFlush===-1)this._deferFlush=1})\n"; // createTextStream const JSC::ConstructAbility s_readableStreamInternalsCreateTextStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1644,7 +1644,7 @@ const JSC::ConstructorKind s_readableStreamInternalsCreateTextStreamCodeConstruc const JSC::ImplementationVisibility s_readableStreamInternalsCreateTextStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsCreateTextStreamCodeLength = 984; static const JSC::Intrinsic s_readableStreamInternalsCreateTextStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsCreateTextStreamCode = "(function (j){\"use strict\";var x,w=[],z=!1,_=!1,A=\"\",q=@toLength(0),C=@newPromiseCapability(@Promise),E=!1;return x={start(){},write(v){if(typeof v===\"string\"){var F=@toLength(v.length);if(F>0)A+=v,z=!0,q+=F;return F}if(!v||!(@ArrayBuffer.@isView(v)||v instanceof @ArrayBuffer))@throwTypeError(\"Expected text, ArrayBuffer or ArrayBufferView\");const G=@toLength(v.byteLength);if(G>0)if(_=!0,A.length>0)@arrayPush(w,A,v),A=\"\";else @arrayPush(w,v);return q+=G,G},flush(){return 0},end(){if(E)return\"\";return x.fulfill()},fulfill(){E=!0;const v=x.finishInternal();return @fulfillPromise(C.@promise,v),v},finishInternal(){if(!z&&!_)return\"\";if(z&&!_)return A;if(_&&!z)return new globalThis.TextDecoder().decode(@Bun.concatArrayBuffers(w));var v=new @Bun.ArrayBufferSink;v.start({highWaterMark:q,asUint8Array:!0});for(let F of w)v.write(F);if(w.length=0,A.length>0)v.write(A),A=\"\";return new globalThis.TextDecoder().decode(v.end())},close(){try{if(!E)E=!0,x.fulfill()}catch(v){}}},[x,C]})\n"; +const char* const s_readableStreamInternalsCreateTextStreamCode = "(function (_){\"use strict\";var j,q=[],x=!1,v=!1,z=\"\",C=@toLength(0),E=@newPromiseCapability(@Promise),F=!1;return j={start(){},write(G){if(typeof G===\"string\"){var A=@toLength(G.length);if(A>0)z+=G,x=!0,C+=A;return A}if(!G||!(@ArrayBuffer.@isView(G)||G instanceof @ArrayBuffer))@throwTypeError(\"Expected text, ArrayBuffer or ArrayBufferView\");const w=@toLength(G.byteLength);if(w>0)if(v=!0,z.length>0)@arrayPush(q,z,G),z=\"\";else @arrayPush(q,G);return C+=w,w},flush(){return 0},end(){if(F)return\"\";return j.fulfill()},fulfill(){F=!0;const G=j.finishInternal();return @fulfillPromise(E.@promise,G),G},finishInternal(){if(!x&&!v)return\"\";if(x&&!v)return z;if(v&&!x)return new globalThis.TextDecoder().decode(@Bun.concatArrayBuffers(q));var G=new @Bun.ArrayBufferSink;G.start({highWaterMark:C,asUint8Array:!0});for(let A of q)G.write(A);if(q.length=0,z.length>0)G.write(z),z=\"\";return new globalThis.TextDecoder().decode(G.end())},close(){try{if(!F)F=!0,j.fulfill()}catch(G){}}},[j,E]})\n"; // initializeTextStream const JSC::ConstructAbility s_readableStreamInternalsInitializeTextStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1652,7 +1652,7 @@ const JSC::ConstructorKind s_readableStreamInternalsInitializeTextStreamCodeCons const JSC::ImplementationVisibility s_readableStreamInternalsInitializeTextStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsInitializeTextStreamCodeLength = 578; static const JSC::Intrinsic s_readableStreamInternalsInitializeTextStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsInitializeTextStreamCode = "(function (_,m){\"use strict\";var[p,b]=@createTextStream(m),f={@underlyingSource:_,@pull:@onPullDirectStream,@controlledReadableStream:this,@sink:p,close:@onCloseDirectStream,write:p.write,error:@handleDirectStreamError,end:@onCloseDirectStream,@close:@onCloseDirectStream,flush:@onFlushDirectStream,_pendingRead:@undefined,_deferClose:0,_deferFlush:0,_deferCloseReason:@undefined,_handleError:@undefined};return @putByIdDirectPrivate(this,\"readableStreamController\",f),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"start\",@undefined),b})\n"; +const char* const s_readableStreamInternalsInitializeTextStreamCode = "(function (_,m){\"use strict\";var[b,f]=@createTextStream(m),p={@underlyingSource:_,@pull:@onPullDirectStream,@controlledReadableStream:this,@sink:b,close:@onCloseDirectStream,write:b.write,error:@handleDirectStreamError,end:@onCloseDirectStream,@close:@onCloseDirectStream,flush:@onFlushDirectStream,_pendingRead:@undefined,_deferClose:0,_deferFlush:0,_deferCloseReason:@undefined,_handleError:@undefined};return @putByIdDirectPrivate(this,\"readableStreamController\",p),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"start\",@undefined),f})\n"; // initializeArrayStream const JSC::ConstructAbility s_readableStreamInternalsInitializeArrayStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1660,7 +1660,7 @@ const JSC::ConstructorKind s_readableStreamInternalsInitializeArrayStreamCodeCon const JSC::ImplementationVisibility s_readableStreamInternalsInitializeArrayStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsInitializeArrayStreamCodeLength = 797; static const JSC::Intrinsic s_readableStreamInternalsInitializeArrayStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsInitializeArrayStreamCode = "(function (_,b){\"use strict\";var j=[],t=@newPromiseCapability(@Promise),p=!1;function d(){return p=!0,t.@resolve.@call(@undefined,j),j}var m={start(){},write(v){return @arrayPush(j,v),v.byteLength||v.length},flush(){return 0},end(){if(p)return[];return d()},close(){if(!p)d()}},q={@underlyingSource:_,@pull:@onPullDirectStream,@controlledReadableStream:this,@sink:m,close:@onCloseDirectStream,write:m.write,error:@handleDirectStreamError,end:@onCloseDirectStream,@close:@onCloseDirectStream,flush:@onFlushDirectStream,_pendingRead:@undefined,_deferClose:0,_deferFlush:0,_deferCloseReason:@undefined,_handleError:@undefined};return @putByIdDirectPrivate(this,\"readableStreamController\",q),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"start\",@undefined),t})\n"; +const char* const s_readableStreamInternalsInitializeArrayStreamCode = "(function (p,b){\"use strict\";var d=[],j=@newPromiseCapability(@Promise),_=!1;function m(){return _=!0,j.@resolve.@call(@undefined,d),d}var t={start(){},write(v){return @arrayPush(d,v),v.byteLength||v.length},flush(){return 0},end(){if(_)return[];return m()},close(){if(!_)m()}},q={@underlyingSource:p,@pull:@onPullDirectStream,@controlledReadableStream:this,@sink:t,close:@onCloseDirectStream,write:t.write,error:@handleDirectStreamError,end:@onCloseDirectStream,@close:@onCloseDirectStream,flush:@onFlushDirectStream,_pendingRead:@undefined,_deferClose:0,_deferFlush:0,_deferCloseReason:@undefined,_handleError:@undefined};return @putByIdDirectPrivate(this,\"readableStreamController\",q),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"start\",@undefined),j})\n"; // initializeArrayBufferStream const JSC::ConstructAbility s_readableStreamInternalsInitializeArrayBufferStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1756,7 +1756,7 @@ const JSC::ConstructorKind s_readableStreamInternalsReadableStreamCloseCodeConst const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamCloseCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsReadableStreamCloseCodeLength = 617; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamCloseCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamCloseCode = "(function (_){\"use strict\";if(@assert(@getByIdDirectPrivate(_,\"state\")===@streamReadable),@putByIdDirectPrivate(_,\"state\",@streamClosed),!@getByIdDirectPrivate(_,\"reader\"))return;if(@isReadableStreamDefaultReader(@getByIdDirectPrivate(_,\"reader\"))){const i=@getByIdDirectPrivate(@getByIdDirectPrivate(_,\"reader\"),\"readRequests\");if(i.isNotEmpty()){@putByIdDirectPrivate(@getByIdDirectPrivate(_,\"reader\"),\"readRequests\",@createFIFO());for(var d=i.shift();d;d=i.shift())@fulfillPromise(d,{value:@undefined,done:!0})}}@getByIdDirectPrivate(@getByIdDirectPrivate(_,\"reader\"),\"closedPromiseCapability\").@resolve.@call()})\n"; +const char* const s_readableStreamInternalsReadableStreamCloseCode = "(function (_){\"use strict\";if(@assert(@getByIdDirectPrivate(_,\"state\")===@streamReadable),@putByIdDirectPrivate(_,\"state\",@streamClosed),!@getByIdDirectPrivate(_,\"reader\"))return;if(@isReadableStreamDefaultReader(@getByIdDirectPrivate(_,\"reader\"))){const d=@getByIdDirectPrivate(@getByIdDirectPrivate(_,\"reader\"),\"readRequests\");if(d.isNotEmpty()){@putByIdDirectPrivate(@getByIdDirectPrivate(_,\"reader\"),\"readRequests\",@createFIFO());for(var i=d.shift();i;i=d.shift())@fulfillPromise(i,{value:@undefined,done:!0})}}@getByIdDirectPrivate(@getByIdDirectPrivate(_,\"reader\"),\"closedPromiseCapability\").@resolve.@call()})\n"; // readableStreamFulfillReadRequest const JSC::ConstructAbility s_readableStreamInternalsReadableStreamFulfillReadRequestCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1772,7 +1772,7 @@ const JSC::ConstructorKind s_readableStreamInternalsReadableStreamDefaultControl const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamDefaultControllerEnqueueCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsReadableStreamDefaultControllerEnqueueCodeLength = 659; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamDefaultControllerEnqueueCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamDefaultControllerEnqueueCode = "(function (_,d){\"use strict\";const E=@getByIdDirectPrivate(_,\"controlledReadableStream\");if(@assert(@readableStreamDefaultControllerCanCloseOrEnqueue(_)),@isReadableStreamLocked(E)&&@getByIdDirectPrivate(@getByIdDirectPrivate(E,\"reader\"),\"readRequests\")\?.isNotEmpty()){@readableStreamFulfillReadRequest(E,d,!1),@readableStreamDefaultControllerCallPullIfNeeded(_);return}try{let D=1;if(@getByIdDirectPrivate(_,\"strategy\").size!==@undefined)D=@getByIdDirectPrivate(_,\"strategy\").size(d);@enqueueValueWithSize(@getByIdDirectPrivate(_,\"queue\"),d,D)}catch(D){throw @readableStreamDefaultControllerError(_,D),D}@readableStreamDefaultControllerCallPullIfNeeded(_)})\n"; +const char* const s_readableStreamInternalsReadableStreamDefaultControllerEnqueueCode = "(function (_,d){\"use strict\";const D=@getByIdDirectPrivate(_,\"controlledReadableStream\");if(@assert(@readableStreamDefaultControllerCanCloseOrEnqueue(_)),@isReadableStreamLocked(D)&&@getByIdDirectPrivate(@getByIdDirectPrivate(D,\"reader\"),\"readRequests\")\?.isNotEmpty()){@readableStreamFulfillReadRequest(D,d,!1),@readableStreamDefaultControllerCallPullIfNeeded(_);return}try{let E=1;if(@getByIdDirectPrivate(_,\"strategy\").size!==@undefined)E=@getByIdDirectPrivate(_,\"strategy\").size(d);@enqueueValueWithSize(@getByIdDirectPrivate(_,\"queue\"),d,E)}catch(E){throw @readableStreamDefaultControllerError(_,E),E}@readableStreamDefaultControllerCallPullIfNeeded(_)})\n"; // readableStreamDefaultReaderRead const JSC::ConstructAbility s_readableStreamInternalsReadableStreamDefaultReaderReadCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1780,7 +1780,7 @@ const JSC::ConstructorKind s_readableStreamInternalsReadableStreamDefaultReaderR const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamDefaultReaderReadCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsReadableStreamDefaultReaderReadCodeLength = 491; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamDefaultReaderReadCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamDefaultReaderReadCode = "(function (i){\"use strict\";const n=@getByIdDirectPrivate(i,\"ownerReadableStream\");@assert(!!n);const y=@getByIdDirectPrivate(n,\"state\");if(@putByIdDirectPrivate(n,\"disturbed\",!0),y===@streamClosed)return @createFulfilledPromise({value:@undefined,done:!0});if(y===@streamErrored)return @Promise.@reject(@getByIdDirectPrivate(n,\"storedError\"));return @assert(y===@streamReadable),@getByIdDirectPrivate(n,\"readableStreamController\").@pull(@getByIdDirectPrivate(n,\"readableStreamController\"))})\n"; +const char* const s_readableStreamInternalsReadableStreamDefaultReaderReadCode = "(function (i){\"use strict\";const y=@getByIdDirectPrivate(i,\"ownerReadableStream\");@assert(!!y);const n=@getByIdDirectPrivate(y,\"state\");if(@putByIdDirectPrivate(y,\"disturbed\",!0),n===@streamClosed)return @createFulfilledPromise({value:@undefined,done:!0});if(n===@streamErrored)return @Promise.@reject(@getByIdDirectPrivate(y,\"storedError\"));return @assert(n===@streamReadable),@getByIdDirectPrivate(y,\"readableStreamController\").@pull(@getByIdDirectPrivate(y,\"readableStreamController\"))})\n"; // readableStreamAddReadRequest const JSC::ConstructAbility s_readableStreamInternalsReadableStreamAddReadRequestCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1820,7 +1820,7 @@ const JSC::ConstructorKind s_readableStreamInternalsLazyLoadStreamCodeConstructo const JSC::ImplementationVisibility s_readableStreamInternalsLazyLoadStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsLazyLoadStreamCodeLength = 1589; static const JSC::Intrinsic s_readableStreamInternalsLazyLoadStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsLazyLoadStreamCode = "(function (Q,G){\"use strict\";var N=@getByIdDirectPrivate(Q,\"bunNativeType\"),H=@getByIdDirectPrivate(Q,\"bunNativePtr\"),I=@lazyStreamPrototypeMap.@get(N);if(I===@undefined){let m=function(D){var{c:p,v:z}=this;this.c=@undefined,this.v=@undefined,X(D,p,z)},M=function(D){try{D.close()}catch(p){globalThis.reportError(p)}},_=function(D,p,z,A){A[0]=!1;var E;try{E=f(D,z,A)}catch(F){return p.error(F)}return X(E,p,z)};var j=m,P=M,q=_,[f,b,J,x,K,O,U]=@lazyLoad(N),W=[!1],X;X=function D(p,z,A){if(p&&@isPromise(p))return p.then(m.bind({c:z,v:A}),(E)=>z.error(E));else if(typeof p===\"number\")if(A&&A.byteLength===p&&A.buffer===z.byobRequest\?.view\?.buffer)z.byobRequest.respondWithNewView(A);else z.byobRequest.respond(p);else if(p.constructor===@Uint8Array)z.enqueue(p);if(W[0]||p===!1)@enqueueJob(M,z),W[0]=!1};const B=K\?new FinalizationRegistry(K):null;I=class D{constructor(p,z,A){if(this.#f=p,this.#b={},this.pull=this.#j.bind(this),this.cancel=this.#m.bind(this),this.autoAllocateChunkSize=z,A!==@undefined)this.start=(E)=>{E.enqueue(A)};if(B)B.register(this,p,this.#b)}#b;pull;cancel;start;#f;type=\"bytes\";autoAllocateChunkSize=0;static startSync=b;#j(p){var z=this.#f;if(!z){p.close();return}_(z,p,p.byobRequest.view,W)}#m(p){var z=this.#f;B&&B.unregister(this.#b),O&&O(z,!1),J(z,p)}static deinit=K;static drain=U},@lazyStreamPrototypeMap.@set(N,I)}const Y=I.startSync(H,G);var Z;const{drain:y,deinit:L}=I;if(y)Z=y(H);if(Y===0){if(K&&H&&@enqueueJob(K,H),(Z\?.byteLength\?\?0)>0)return{start(m){m.enqueue(Z),m.close()},type:\"bytes\"};return{start(m){m.close()},type:\"bytes\"}}return new I(H,Y,Z)})\n"; +const char* const s_readableStreamInternalsLazyLoadStreamCode = "(function (N,J){\"use strict\";var M=@getByIdDirectPrivate(N,\"bunNativeType\"),K=@getByIdDirectPrivate(N,\"bunNativePtr\"),L=@lazyStreamPrototypeMap.@get(M);if(L===@undefined){let q=function(x){var{c:H,v:z}=this;this.c=@undefined,this.v=@undefined,j(x,H,z)},G=function(x){try{x.close()}catch(H){globalThis.reportError(H)}},_=function(x,H,z,A){A[0]=!1;var y;try{y=b(x,z,A)}catch(I){return H.error(I)}return j(y,H,z)};var Y=q,Z=G,F=_,[b,B,O,P,f,D,Q]=@lazyLoad(M),U=[!1],j;j=function x(H,z,A){if(H&&@isPromise(H))return H.then(q.bind({c:z,v:A}),(y)=>z.error(y));else if(typeof H===\"number\")if(A&&A.byteLength===H&&A.buffer===z.byobRequest\?.view\?.buffer)z.byobRequest.respondWithNewView(A);else z.byobRequest.respond(H);else if(H.constructor===@Uint8Array)z.enqueue(H);if(U[0]||H===!1)@enqueueJob(G,z),U[0]=!1};const p=f\?new FinalizationRegistry(f):null;L=class x{constructor(H,z,A){if(this.#f=H,this.#b={},this.pull=this.#j.bind(this),this.cancel=this.#m.bind(this),this.autoAllocateChunkSize=z,A!==@undefined)this.start=(y)=>{y.enqueue(A)};if(p)p.register(this,H,this.#b)}#b;pull;cancel;start;#f;type=\"bytes\";autoAllocateChunkSize=0;static startSync=B;#j(H){var z=this.#f;if(!z){H.close();return}_(z,H,H.byobRequest.view,U)}#m(H){var z=this.#f;p&&p.unregister(this.#b),D&&D(z,!1),O(z,H)}static deinit=f;static drain=Q},@lazyStreamPrototypeMap.@set(M,L)}const E=L.startSync(K,J);var W;const{drain:X,deinit:m}=L;if(X)W=X(K);if(E===0){if(f&&K&&@enqueueJob(f,K),(W\?.byteLength\?\?0)>0)return{start(q){q.enqueue(W),q.close()},type:\"bytes\"};return{start(q){q.close()},type:\"bytes\"}}return new L(K,E,W)})\n"; // readableStreamIntoArray const JSC::ConstructAbility s_readableStreamInternalsReadableStreamIntoArrayCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1828,7 +1828,7 @@ const JSC::ConstructorKind s_readableStreamInternalsReadableStreamIntoArrayCodeC const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamIntoArrayCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsReadableStreamIntoArrayCodeLength = 247; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamIntoArrayCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamIntoArrayCode = "(function (f){\"use strict\";var p=f.getReader(),g=p.readMany();async function b(_){if(_.done)return[];var j=_.value||[];while(!0){var q=await p.read();if(q.done)break;j=j.concat(q.value)}return j}if(g&&@isPromise(g))return g.@then(b);return b(g)})\n"; +const char* const s_readableStreamInternalsReadableStreamIntoArrayCode = "(function (_){\"use strict\";var b=_.getReader(),g=b.readMany();async function j(q){if(q.done)return[];var f=q.value||[];while(!0){var p=await b.read();if(p.done)break;f=f.concat(p.value)}return f}if(g&&@isPromise(g))return g.@then(j);return j(g)})\n"; // readableStreamIntoText const JSC::ConstructAbility s_readableStreamInternalsReadableStreamIntoTextCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1844,7 +1844,7 @@ const JSC::ConstructorKind s_readableStreamInternalsReadableStreamToArrayBufferD const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamToArrayBufferDirectCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsReadableStreamToArrayBufferDirectCodeLength = 727; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamToArrayBufferDirectCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamToArrayBufferDirectCode = "(function (j,w){\"use strict\";var _=new @Bun.ArrayBufferSink;@putByIdDirectPrivate(j,\"underlyingSource\",@undefined);var x=@getByIdDirectPrivate(j,\"highWaterMark\");_.start(x\?{highWaterMark:x}:{});var O=@newPromiseCapability(@Promise),z=!1,q=w.pull,A=w.close,B={start(){},close(C){if(!z){if(z=!0,A)A();@fulfillPromise(O.@promise,_.end())}},end(){if(!z){if(z=!0,A)A();@fulfillPromise(O.@promise,_.end())}},flush(){return 0},write:_.write.bind(_)},v=!1;try{const C=q(B);if(C&&@isObject(C)&&@isPromise(C))return async function(D,F,G){while(!z)await G(D);return await F}(B,promise,q);return O.@promise}catch(C){return v=!0,@readableStreamError(j,C),@Promise.@reject(C)}finally{if(!v&&j)@readableStreamClose(j);B=A=_=q=j=@undefined}})\n"; +const char* const s_readableStreamInternalsReadableStreamToArrayBufferDirectCode = "(function (O,_){\"use strict\";var q=new @Bun.ArrayBufferSink;@putByIdDirectPrivate(O,\"underlyingSource\",@undefined);var x=@getByIdDirectPrivate(O,\"highWaterMark\");q.start(x\?{highWaterMark:x}:{});var v=@newPromiseCapability(@Promise),A=!1,z=_.pull,B=_.close,C={start(){},close(F){if(!A){if(A=!0,B)B();@fulfillPromise(v.@promise,q.end())}},end(){if(!A){if(A=!0,B)B();@fulfillPromise(v.@promise,q.end())}},flush(){return 0},write:q.write.bind(q)},D=!1;try{const F=z(C);if(F&&@isObject(F)&&@isPromise(F))return async function(G,j,w){while(!A)await w(G);return await j}(C,promise,z);return v.@promise}catch(F){return D=!0,@readableStreamError(O,F),@Promise.@reject(F)}finally{if(!D&&O)@readableStreamClose(O);C=B=q=z=O=@undefined}})\n"; // readableStreamToTextDirect const JSC::ConstructAbility s_readableStreamInternalsReadableStreamToTextDirectCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1852,7 +1852,7 @@ const JSC::ConstructorKind s_readableStreamInternalsReadableStreamToTextDirectCo const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamToTextDirectCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsReadableStreamToTextDirectCodeLength = 278; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamToTextDirectCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamToTextDirectCode = "(async function (_,f){\"use strict\";const h=@initializeTextStream.@call(_,f,@undefined);var j=_.getReader();while(@getByIdDirectPrivate(_,\"state\")===@streamReadable){var k=await j.read();if(k.done)break}try{j.releaseLock()}catch(p){}return j=@undefined,_=@undefined,h.@promise})\n"; +const char* const s_readableStreamInternalsReadableStreamToTextDirectCode = "(async function (f,h){\"use strict\";const j=@initializeTextStream.@call(f,h,@undefined);var k=f.getReader();while(@getByIdDirectPrivate(f,\"state\")===@streamReadable){var p=await k.read();if(p.done)break}try{k.releaseLock()}catch(_){}return k=@undefined,f=@undefined,j.@promise})\n"; // readableStreamToArrayDirect const JSC::ConstructAbility s_readableStreamInternalsReadableStreamToArrayDirectCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1860,7 +1860,7 @@ const JSC::ConstructorKind s_readableStreamInternalsReadableStreamToArrayDirectC const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamToArrayDirectCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsReadableStreamToArrayDirectCodeLength = 354; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamToArrayDirectCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamToArrayDirectCode = "(async function (_,j){\"use strict\";const k=@initializeArrayStream.@call(_,j,@undefined);j=@undefined;var p=_.getReader();try{while(@getByIdDirectPrivate(_,\"state\")===@streamReadable){var q=await p.read();if(q.done)break}try{p.releaseLock()}catch(f){}return p=@undefined,@Promise.@resolve(k.@promise)}catch(f){throw f}finally{_=@undefined,p=@undefined}})\n"; +const char* const s_readableStreamInternalsReadableStreamToArrayDirectCode = "(async function (_,p){\"use strict\";const j=@initializeArrayStream.@call(_,p,@undefined);p=@undefined;var q=_.getReader();try{while(@getByIdDirectPrivate(_,\"state\")===@streamReadable){var k=await q.read();if(k.done)break}try{q.releaseLock()}catch(f){}return q=@undefined,@Promise.@resolve(j.@promise)}catch(f){throw f}finally{_=@undefined,q=@undefined}})\n"; // readableStreamDefineLazyIterators const JSC::ConstructAbility s_readableStreamInternalsReadableStreamDefineLazyIteratorsCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1868,7 +1868,7 @@ const JSC::ConstructorKind s_readableStreamInternalsReadableStreamDefineLazyIter const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamDefineLazyIteratorsCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInternalsReadableStreamDefineLazyIteratorsCodeLength = 516; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamDefineLazyIteratorsCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamDefineLazyIteratorsCode = "(function (k){\"use strict\";var z=globalThis.Symbol.asyncIterator,D=async function*B(G,x){var i=G.getReader(),w;try{while(!0){var q,h;const j=i.readMany();if(@isPromise(j))({done:q,value:h}=await j);else({done:q,value:h}=j);if(q)return;yield*h}}catch(j){w=j}finally{if(i.releaseLock(),!x)G.cancel(w);if(w)throw w}},F=function B(){return D(this,!1)},g=function B({preventCancel:G=!1}={preventCancel:!1}){return D(this,G)};return @Object.@defineProperty(k,z,{value:F}),@Object.@defineProperty(k,\"values\",{value:g}),k})\n"; +const char* const s_readableStreamInternalsReadableStreamDefineLazyIteratorsCode = "(function (k){\"use strict\";var g=globalThis.Symbol.asyncIterator,i=async function*D(q,F){var w=q.getReader(),G;try{while(!0){var x,h;const z=w.readMany();if(@isPromise(z))({done:x,value:h}=await z);else({done:x,value:h}=z);if(x)return;yield*h}}catch(z){G=z}finally{if(w.releaseLock(),!F)q.cancel(G);if(G)throw G}},B=function D(){return i(this,!1)},j=function D({preventCancel:q=!1}={preventCancel:!1}){return i(this,q)};return @Object.@defineProperty(k,g,{value:B}),@Object.@defineProperty(k,\"values\",{value:j}),k})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -1894,7 +1894,7 @@ const JSC::ConstructorKind s_transformStreamDefaultControllerDesiredSizeCodeCons const JSC::ImplementationVisibility s_transformStreamDefaultControllerDesiredSizeCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_transformStreamDefaultControllerDesiredSizeCodeLength = 339; static const JSC::Intrinsic s_transformStreamDefaultControllerDesiredSizeCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamDefaultControllerDesiredSizeCode = "(function (){\"use strict\";if(!@isTransformStreamDefaultController(this))throw @makeThisTypeError(\"TransformStreamDefaultController\",\"enqueue\");const _=@getByIdDirectPrivate(this,\"stream\"),i=@getByIdDirectPrivate(_,\"readable\"),u=@getByIdDirectPrivate(i,\"readableStreamController\");return @readableStreamDefaultControllerGetDesiredSize(u)})\n"; +const char* const s_transformStreamDefaultControllerDesiredSizeCode = "(function (){\"use strict\";if(!@isTransformStreamDefaultController(this))throw @makeThisTypeError(\"TransformStreamDefaultController\",\"enqueue\");const _=@getByIdDirectPrivate(this,\"stream\"),u=@getByIdDirectPrivate(_,\"readable\"),i=@getByIdDirectPrivate(u,\"readableStreamController\");return @readableStreamDefaultControllerGetDesiredSize(i)})\n"; // enqueue const JSC::ConstructAbility s_transformStreamDefaultControllerEnqueueCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1986,7 +1986,7 @@ const JSC::ConstructorKind s_jsBufferConstructorFromCodeConstructorKind = JSC::C const JSC::ImplementationVisibility s_jsBufferConstructorFromCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_jsBufferConstructorFromCodeLength = 1107; static const JSC::Intrinsic s_jsBufferConstructorFromCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferConstructorFromCode = "(function (n){\"use strict\";if(@isUndefinedOrNull(n))@throwTypeError(\"The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object.\");if(typeof n===\"string\"||typeof n===\"object\"&&(@isTypedArrayView(n)||n instanceof @ArrayBuffer||n instanceof SharedArrayBuffer||n instanceof String))switch(@argumentCount()){case 1:return new @Buffer(n);case 2:return new @Buffer(n,@argument(1));default:return new @Buffer(n,@argument(1),@argument(2))}var f=@toObject(n,\"The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.\");if(!@isJSArray(f)){const d=@tryGetByIdWithWellKnownSymbol(n,\"toPrimitive\");if(d){const u=d.@call(n,\"string\");if(typeof u===\"string\")switch(@argumentCount()){case 1:return new @Buffer(u);case 2:return new @Buffer(u,@argument(1));default:return new @Buffer(u,@argument(1),@argument(2))}}if(!(\"length\"in f)||@isCallable(f))@throwTypeError(\"The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.\")}return new @Buffer(@Uint8Array.from(f).buffer)})\n"; +const char* const s_jsBufferConstructorFromCode = "(function (n){\"use strict\";if(@isUndefinedOrNull(n))@throwTypeError(\"The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object.\");if(typeof n===\"string\"||typeof n===\"object\"&&(@isTypedArrayView(n)||n instanceof @ArrayBuffer||n instanceof SharedArrayBuffer||n instanceof String))switch(@argumentCount()){case 1:return new @Buffer(n);case 2:return new @Buffer(n,@argument(1));default:return new @Buffer(n,@argument(1),@argument(2))}var d=@toObject(n,\"The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.\");if(!@isJSArray(d)){const f=@tryGetByIdWithWellKnownSymbol(n,\"toPrimitive\");if(f){const u=f.@call(n,\"string\");if(typeof u===\"string\")switch(@argumentCount()){case 1:return new @Buffer(u);case 2:return new @Buffer(u,@argument(1));default:return new @Buffer(u,@argument(1),@argument(2))}}if(!(\"length\"in d)||@isCallable(d))@throwTypeError(\"The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.\")}return new @Buffer(@Uint8Array.from(d).buffer)})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -2020,7 +2020,7 @@ const JSC::ConstructorKind s_readableStreamDefaultReaderReadManyCodeConstructorK const JSC::ImplementationVisibility s_readableStreamDefaultReaderReadManyCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamDefaultReaderReadManyCodeLength = 2598; static const JSC::Intrinsic s_readableStreamDefaultReaderReadManyCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamDefaultReaderReadManyCode = "(function (){\"use strict\";if(!@isReadableStreamDefaultReader(this))@throwTypeError(\"ReadableStreamDefaultReader.readMany() should not be called directly\");const T=@getByIdDirectPrivate(this,\"ownerReadableStream\");if(!T)@throwTypeError(\"readMany() called on a reader owned by no readable stream\");const C=@getByIdDirectPrivate(T,\"state\");if(@putByIdDirectPrivate(T,\"disturbed\",!0),C===@streamClosed)return{value:[],size:0,done:!0};else if(C===@streamErrored)throw @getByIdDirectPrivate(T,\"storedError\");var H=@getByIdDirectPrivate(T,\"readableStreamController\"),E=@getByIdDirectPrivate(H,\"queue\");if(!E)return H.@pull(H).@then(function({done:Q,value:w}){return Q\?{done:!0,value:[],size:0}:{value:[w],size:1,done:!1}});const F=E.content;var B=E.size,_=F.toArray(!1),I=_.length;if(I>0){var k=@newArrayWithSize(I);if(@isReadableByteStreamController(H)){{const Q=_[0];if(!(@ArrayBuffer.@isView(Q)||Q instanceof @ArrayBuffer))@putByValDirect(k,0,new @Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength));else @putByValDirect(k,0,Q)}for(var N=1;N{if(Q.done)return{value:[],size:0,done:!0};var w=@getByIdDirectPrivate(T,\"readableStreamController\"),d=@getByIdDirectPrivate(w,\"queue\"),J=[Q.value].concat(d.content.toArray(!1)),x=J.length;if(@isReadableByteStreamController(w))for(var K=0;K0){var j=@newArrayWithSize(S);if(@isReadableByteStreamController(J)){{const k=I[0];if(!(@ArrayBuffer.@isView(k)||k instanceof @ArrayBuffer))@putByValDirect(j,0,new @Uint8Array(k.buffer,k.byteOffset,k.byteLength));else @putByValDirect(j,0,k)}for(var _=1;_{if(k.done)return{value:[],size:0,done:!0};var K=@getByIdDirectPrivate(Q,\"readableStreamController\"),N=@getByIdDirectPrivate(K,\"queue\"),O=[k.value].concat(N.content.toArray(!1)),x=O.length;if(@isReadableByteStreamController(K))for(var d=0;d0}shift(){var{_head:w,_tail:x,_list:z,_capacityMask:k}=this;if(w===x)return @undefined;var A=z[w];if(@putByValDirect(z,w,@undefined),w=this._head=w+1&k,w<2&&x>1e4&&x<=z.length>>>2)this._shrinkArray();return A}peek(){if(this._head===this._tail)return @undefined;return this._list[this._head]}push(w){var x=this._tail;if(@putByValDirect(this._list,x,w),this._tail=x+1&this._capacityMask,this._tail===this._head)this._growArray()}toArray(w){var x=this._list,z=@toLength(x.length);if(w||this._head>this._tail){var k=@toLength(this._head),A=@toLength(this._tail),B=@toLength(z-k+A),E=@newArrayWithSize(B),v=0;for(var F=k;F>>=1,this._capacityMask>>>=1}}return new g})\n"; +const char* const s_streamInternalsCreateFIFOCode = "(function (){\"use strict\";var b=@Array.prototype.slice;class z{constructor(){this._head=0,this._tail=0,this._capacityMask=3,this._list=@newArrayWithSize(4)}_head;_tail;_capacityMask;_list;size(){if(this._head===this._tail)return 0;if(this._head0}shift(){var{_head:v,_tail:x,_list:k,_capacityMask:w}=this;if(v===x)return @undefined;var A=k[v];if(@putByValDirect(k,v,@undefined),v=this._head=v+1&w,v<2&&x>1e4&&x<=k.length>>>2)this._shrinkArray();return A}peek(){if(this._head===this._tail)return @undefined;return this._list[this._head]}push(v){var x=this._tail;if(@putByValDirect(this._list,x,v),this._tail=x+1&this._capacityMask,this._tail===this._head)this._growArray()}toArray(v){var x=this._list,k=@toLength(x.length);if(v||this._head>this._tail){var w=@toLength(this._head),A=@toLength(this._tail),B=@toLength(k-w+A),E=@newArrayWithSize(B),g=0;for(var F=w;F>>=1,this._capacityMask>>>=1}}return new z})\n"; // newQueue const JSC::ConstructAbility s_streamInternalsNewQueueCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2232,7 +2232,7 @@ const JSC::ConstructorKind s_importMetaObjectRequireESMCodeConstructorKind = JSC const JSC::ImplementationVisibility s_importMetaObjectRequireESMCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_importMetaObjectRequireESMCodeLength = 325; static const JSC::Intrinsic s_importMetaObjectRequireESMCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_importMetaObjectRequireESMCode = "(function (a){\"use strict\";var c=@Loader.registry.@get(a);if(!c||!c.evaluated)c=@loadCJS2ESM(a);if(!c||!c.evaluated||!c.module)@throwTypeError(`require() failed to evaluate module \"${a}\". This is an internal consistentency error.`);var _=@Loader.getModuleNamespaceObject(c.module);if(_[@commonJSSymbol]===0)return;return _})\n"; +const char* const s_importMetaObjectRequireESMCode = "(function (a){\"use strict\";var _=@Loader.registry.@get(a);if(!_||!_.evaluated)_=@loadCJS2ESM(a);if(!_||!_.evaluated||!_.module)@throwTypeError(`require() failed to evaluate module \"${a}\". This is an internal consistentency error.`);var c=@Loader.getModuleNamespaceObject(_.module);if(c[@commonJSSymbol]===0)return;return c})\n"; // internalRequire const JSC::ConstructAbility s_importMetaObjectInternalRequireCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2248,7 +2248,7 @@ const JSC::ConstructorKind s_importMetaObjectCreateRequireCacheCodeConstructorKi const JSC::ImplementationVisibility s_importMetaObjectCreateRequireCacheCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_importMetaObjectCreateRequireCacheCodeLength = 854; static const JSC::Intrinsic s_importMetaObjectCreateRequireCacheCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_importMetaObjectCreateRequireCacheCode = "(function (){\"use strict\";var f=new Map,u={};return new Proxy(u,{get(c,L){const h=@requireMap.@get(L);if(h)return h;const g=@Loader.registry.@get(L);if(g\?.evaluated){const _=@Loader.getModuleNamespaceObject(g.module),b=_[@commonJSSymbol]===0||_.default\?.[@commonJSSymbol]\?_.default:_,t=@createCommonJSModule(L,b,!0);return @requireMap.@set(L,t),t}return u[L]},set(c,L,h){return @requireMap.@set(L,h),!0},has(c,L){return @requireMap.@has(L)||@Loader.registry.@has(L)},deleteProperty(c,L){return f.@delete(L),@requireMap.@delete(L),@Loader.registry.@delete(L),!0},ownKeys(c){var L=[...@requireMap.@keys()];const h=[...@Loader.registry.@keys()];for(let g of h)if(!L.includes(g))@arrayPush(L,g);return L},getPrototypeOf(c){return null},getOwnPropertyDescriptor(c,L){if(@requireMap.@has(L)||@Loader.registry.@has(L))return{configurable:!0,enumerable:!0}}})})\n"; +const char* const s_importMetaObjectCreateRequireCacheCode = "(function (){\"use strict\";var _=new Map,f={};return new Proxy(f,{get(h,t){const u=@requireMap.@get(t);if(u)return u;const L=@Loader.registry.@get(t);if(L\?.evaluated){const b=@Loader.getModuleNamespaceObject(L.module),c=b[@commonJSSymbol]===0||b.default\?.[@commonJSSymbol]\?b.default:b,g=@createCommonJSModule(t,c,!0);return @requireMap.@set(t,g),g}return f[t]},set(h,t,u){return @requireMap.@set(t,u),!0},has(h,t){return @requireMap.@has(t)||@Loader.registry.@has(t)},deleteProperty(h,t){return _.@delete(t),@requireMap.@delete(t),@Loader.registry.@delete(t),!0},ownKeys(h){var t=[...@requireMap.@keys()];const u=[...@Loader.registry.@keys()];for(let L of u)if(!t.includes(L))@arrayPush(t,L);return t},getPrototypeOf(h){return null},getOwnPropertyDescriptor(h,t){if(@requireMap.@has(t)||@Loader.registry.@has(t))return{configurable:!0,enumerable:!0}}})})\n"; // require const JSC::ConstructAbility s_importMetaObjectRequireCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2432,7 +2432,7 @@ const JSC::ConstructorKind s_readableStreamInitializeReadableStreamCodeConstruct const JSC::ImplementationVisibility s_readableStreamInitializeReadableStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableStreamInitializeReadableStreamCodeLength = 2065; static const JSC::Intrinsic s_readableStreamInitializeReadableStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInitializeReadableStreamCode = "(function (f,B){\"use strict\";if(f===@undefined)f={@bunNativeType:0,@bunNativePtr:0,@lazy:!1};if(B===@undefined)B={};if(!@isObject(f))@throwTypeError(\"ReadableStream constructor takes an object as first argument\");if(B!==@undefined&&!@isObject(B))@throwTypeError(\"ReadableStream constructor takes an object as second argument, if any\");@putByIdDirectPrivate(this,\"state\",@streamReadable),@putByIdDirectPrivate(this,\"reader\",@undefined),@putByIdDirectPrivate(this,\"storedError\",@undefined),@putByIdDirectPrivate(this,\"disturbed\",!1),@putByIdDirectPrivate(this,\"readableStreamController\",null),@putByIdDirectPrivate(this,\"bunNativeType\",@getByIdDirectPrivate(f,\"bunNativeType\")\?\?0),@putByIdDirectPrivate(this,\"bunNativePtr\",@getByIdDirectPrivate(f,\"bunNativePtr\")\?\?0);const b=f.type===\"direct\",m=!!f.@lazy,v=b||m;if(@getByIdDirectPrivate(f,\"pull\")!==@undefined&&!v){const I=@getByIdDirectPrivate(B,\"size\"),_=@getByIdDirectPrivate(B,\"highWaterMark\");return @putByIdDirectPrivate(this,\"highWaterMark\",_),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@setupReadableStreamDefaultController(this,f,I,_!==@undefined\?_:1,@getByIdDirectPrivate(f,\"start\"),@getByIdDirectPrivate(f,\"pull\"),@getByIdDirectPrivate(f,\"cancel\")),this}if(b)@putByIdDirectPrivate(this,\"underlyingSource\",f),@putByIdDirectPrivate(this,\"highWaterMark\",@getByIdDirectPrivate(B,\"highWaterMark\")),@putByIdDirectPrivate(this,\"start\",()=>@createReadableStreamController(this,f,B));else if(v){const I=f.autoAllocateChunkSize;@putByIdDirectPrivate(this,\"highWaterMark\",@undefined),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"highWaterMark\",I||@getByIdDirectPrivate(B,\"highWaterMark\")),@putByIdDirectPrivate(this,\"start\",()=>{const _=@lazyLoadStream(this,I);if(_)@createReadableStreamController(this,_,B)})}else @putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"highWaterMark\",@getByIdDirectPrivate(B,\"highWaterMark\")),@putByIdDirectPrivate(this,\"start\",@undefined),@createReadableStreamController(this,f,B);return this})\n"; +const char* const s_readableStreamInitializeReadableStreamCode = "(function (f,m){\"use strict\";if(f===@undefined)f={@bunNativeType:0,@bunNativePtr:0,@lazy:!1};if(m===@undefined)m={};if(!@isObject(f))@throwTypeError(\"ReadableStream constructor takes an object as first argument\");if(m!==@undefined&&!@isObject(m))@throwTypeError(\"ReadableStream constructor takes an object as second argument, if any\");@putByIdDirectPrivate(this,\"state\",@streamReadable),@putByIdDirectPrivate(this,\"reader\",@undefined),@putByIdDirectPrivate(this,\"storedError\",@undefined),@putByIdDirectPrivate(this,\"disturbed\",!1),@putByIdDirectPrivate(this,\"readableStreamController\",null),@putByIdDirectPrivate(this,\"bunNativeType\",@getByIdDirectPrivate(f,\"bunNativeType\")\?\?0),@putByIdDirectPrivate(this,\"bunNativePtr\",@getByIdDirectPrivate(f,\"bunNativePtr\")\?\?0);const v=f.type===\"direct\",B=!!f.@lazy,b=v||B;if(@getByIdDirectPrivate(f,\"pull\")!==@undefined&&!b){const _=@getByIdDirectPrivate(m,\"size\"),I=@getByIdDirectPrivate(m,\"highWaterMark\");return @putByIdDirectPrivate(this,\"highWaterMark\",I),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@setupReadableStreamDefaultController(this,f,_,I!==@undefined\?I:1,@getByIdDirectPrivate(f,\"start\"),@getByIdDirectPrivate(f,\"pull\"),@getByIdDirectPrivate(f,\"cancel\")),this}if(v)@putByIdDirectPrivate(this,\"underlyingSource\",f),@putByIdDirectPrivate(this,\"highWaterMark\",@getByIdDirectPrivate(m,\"highWaterMark\")),@putByIdDirectPrivate(this,\"start\",()=>@createReadableStreamController(this,f,m));else if(b){const _=f.autoAllocateChunkSize;@putByIdDirectPrivate(this,\"highWaterMark\",@undefined),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"highWaterMark\",_||@getByIdDirectPrivate(m,\"highWaterMark\")),@putByIdDirectPrivate(this,\"start\",()=>{const I=@lazyLoadStream(this,_);if(I)@createReadableStreamController(this,I,m)})}else @putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"highWaterMark\",@getByIdDirectPrivate(m,\"highWaterMark\")),@putByIdDirectPrivate(this,\"start\",@undefined),@createReadableStreamController(this,f,m);return this})\n"; // readableStreamToArray const JSC::ConstructAbility s_readableStreamReadableStreamToArrayCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2448,7 +2448,7 @@ const JSC::ConstructorKind s_readableStreamReadableStreamToTextCodeConstructorKi const JSC::ImplementationVisibility s_readableStreamReadableStreamToTextCodeImplementationVisibility = JSC::ImplementationVisibility::Private; const int s_readableStreamReadableStreamToTextCodeLength = 171; static const JSC::Intrinsic s_readableStreamReadableStreamToTextCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamReadableStreamToTextCode = "(function (_){\"use strict\";var p=@getByIdDirectPrivate(_,\"underlyingSource\");if(p!==@undefined)return @readableStreamToTextDirect(_,p);return @readableStreamIntoText(_)})\n"; +const char* const s_readableStreamReadableStreamToTextCode = "(function (p){\"use strict\";var _=@getByIdDirectPrivate(p,\"underlyingSource\");if(_!==@undefined)return @readableStreamToTextDirect(p,_);return @readableStreamIntoText(p)})\n"; // readableStreamToArrayBuffer const JSC::ConstructAbility s_readableStreamReadableStreamToArrayBufferCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2456,7 +2456,7 @@ const JSC::ConstructorKind s_readableStreamReadableStreamToArrayBufferCodeConstr const JSC::ImplementationVisibility s_readableStreamReadableStreamToArrayBufferCodeImplementationVisibility = JSC::ImplementationVisibility::Private; const int s_readableStreamReadableStreamToArrayBufferCodeLength = 270; static const JSC::Intrinsic s_readableStreamReadableStreamToArrayBufferCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamReadableStreamToArrayBufferCode = "(function (_){\"use strict\";var p=@getByIdDirectPrivate(_,\"underlyingSource\");if(p!==@undefined)return @readableStreamToArrayBufferDirect(_,p);var b=@Bun.readableStreamToArray(_);if(@isPromise(b))return b.then(@Bun.concatArrayBuffers);return @Bun.concatArrayBuffers(b)})\n"; +const char* const s_readableStreamReadableStreamToArrayBufferCode = "(function (_){\"use strict\";var b=@getByIdDirectPrivate(_,\"underlyingSource\");if(b!==@undefined)return @readableStreamToArrayBufferDirect(_,b);var p=@Bun.readableStreamToArray(_);if(@isPromise(p))return p.then(@Bun.concatArrayBuffers);return @Bun.concatArrayBuffers(p)})\n"; // readableStreamToJSON const JSC::ConstructAbility s_readableStreamReadableStreamToJSONCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2480,7 +2480,7 @@ const JSC::ConstructorKind s_readableStreamConsumeReadableStreamCodeConstructorK const JSC::ImplementationVisibility s_readableStreamConsumeReadableStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Private; const int s_readableStreamConsumeReadableStreamCodeLength = 1603; static const JSC::Intrinsic s_readableStreamConsumeReadableStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamConsumeReadableStreamCode = "(function (q,w,x){\"use strict\";const A=globalThis.Symbol.for(\"Bun.consumeReadableStreamPrototype\");var F=globalThis[A];if(!F)F=globalThis[A]=[];var I=F[w];if(I===@undefined){var[j,J,K,L,G,_]=globalThis[globalThis.Symbol.for(\"Bun.lazy\")](w);I=class H{handleError;handleClosed;processResult;constructor(D,N){this.#_=N,this.#F=D,this.#$=!1,this.handleError=this._handleError.bind(this),this.handleClosed=this._handleClosed.bind(this),this.processResult=this._processResult.bind(this),D.closed.then(this.handleClosed,this.handleError)}_handleClosed(){if(this.#$)return;this.#$=!0;var D=this.#_;this.#_=0,L(D),_(D)}_handleError(D){if(this.#$)return;this.#$=!0;var N=this.#_;this.#_=0,J(N,D),_(N)}#_;#$=!1;#F;_handleReadMany({value:D,done:N,size:k}){if(N){this.handleClosed();return}if(this.#$)return;K(this.#_,D,N,k)}read(){if(!this.#_)return @throwTypeError(\"ReadableStreamSink is already closed\");return this.processResult(this.#F.read())}_processResult(D){if(D&&@isPromise(D)){if(@getPromiseInternalField(D,@promiseFieldFlags)&@promiseStateFulfilled){const k=@getPromiseInternalField(D,@promiseFieldReactionsOrResult);if(k)D=k}}if(D&&@isPromise(D))return D.then(this.processResult,this.handleError),null;if(D.done)return this.handleClosed(),0;else if(D.value)return D.value;else return-1}readMany(){if(!this.#_)return @throwTypeError(\"ReadableStreamSink is already closed\");return this.processResult(this.#F.readMany())}};const B=w+1;if(F.length{@putByIdDirectPrivate(R,\"started\",1),@assert(!@getByIdDirectPrivate(R,\"pulling\")),@assert(!@getByIdDirectPrivate(R,\"pullAgain\")),@readableByteStreamControllerCallPullIfNeeded(R)},(d)=>{if(@getByIdDirectPrivate(_,\"state\")===@streamReadable)@readableByteStreamControllerError(R,d)}),@putByIdDirectPrivate(this,\"cancel\",@readableByteStreamControllerCancel),@putByIdDirectPrivate(this,\"pull\",@readableByteStreamControllerPull),this})\n"; +const char* const s_readableByteStreamInternalsPrivateInitializeReadableByteStreamControllerCode = "(function (v,b,f){\"use strict\";if(!@isReadableStream(v))@throwTypeError(\"ReadableByteStreamController needs a ReadableStream\");if(@getByIdDirectPrivate(v,\"readableStreamController\")!==null)@throwTypeError(\"ReadableStream already has a controller\");@putByIdDirectPrivate(this,\"controlledReadableStream\",v),@putByIdDirectPrivate(this,\"underlyingByteSource\",b),@putByIdDirectPrivate(this,\"pullAgain\",!1),@putByIdDirectPrivate(this,\"pulling\",!1),@readableByteStreamControllerClearPendingPullIntos(this),@putByIdDirectPrivate(this,\"queue\",@newQueue()),@putByIdDirectPrivate(this,\"started\",0),@putByIdDirectPrivate(this,\"closeRequested\",!1);let p=@toNumber(f);if(@isNaN(p)||p<0)@throwRangeError(\"highWaterMark value is negative or not a number\");@putByIdDirectPrivate(this,\"strategyHWM\",p);let d=b.autoAllocateChunkSize;if(d!==@undefined){if(d=@toNumber(d),d<=0||d===@Infinity||d===-@Infinity)@throwRangeError(\"autoAllocateChunkSize value is negative or equal to positive or negative infinity\")}@putByIdDirectPrivate(this,\"autoAllocateChunkSize\",d),@putByIdDirectPrivate(this,\"pendingPullIntos\",@createFIFO());const _=this;return @promiseInvokeOrNoopNoCatch(@getByIdDirectPrivate(_,\"underlyingByteSource\"),\"start\",[_]).@then(()=>{@putByIdDirectPrivate(_,\"started\",1),@assert(!@getByIdDirectPrivate(_,\"pulling\")),@assert(!@getByIdDirectPrivate(_,\"pullAgain\")),@readableByteStreamControllerCallPullIfNeeded(_)},(R)=>{if(@getByIdDirectPrivate(v,\"state\")===@streamReadable)@readableByteStreamControllerError(_,R)}),@putByIdDirectPrivate(this,\"cancel\",@readableByteStreamControllerCancel),@putByIdDirectPrivate(this,\"pull\",@readableByteStreamControllerPull),this})\n"; // readableStreamByteStreamControllerStart const JSC::ConstructAbility s_readableByteStreamInternalsReadableStreamByteStreamControllerStartCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2676,7 +2676,7 @@ const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamContro const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerCancelCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableByteStreamInternalsReadableByteStreamControllerCancelCodeLength = 248; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerCancelCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerCancelCode = "(function (a,p){\"use strict\";var u=@getByIdDirectPrivate(a,\"pendingPullIntos\"),_=u.peek();if(_)_.bytesFilled=0;return @putByIdDirectPrivate(a,\"queue\",@newQueue()),@promiseInvokeOrNoop(@getByIdDirectPrivate(a,\"underlyingByteSource\"),\"cancel\",[p])})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerCancelCode = "(function (a,u){\"use strict\";var p=@getByIdDirectPrivate(a,\"pendingPullIntos\"),_=p.peek();if(_)_.bytesFilled=0;return @putByIdDirectPrivate(a,\"queue\",@newQueue()),@promiseInvokeOrNoop(@getByIdDirectPrivate(a,\"underlyingByteSource\"),\"cancel\",[u])})\n"; // readableByteStreamControllerError const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerErrorCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2740,7 +2740,7 @@ const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamContro const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerPullCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableByteStreamInternalsReadableByteStreamControllerPullCodeLength = 1005; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerPullCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerPullCode = "(function (_){\"use strict\";const P=@getByIdDirectPrivate(_,\"controlledReadableStream\");if(@assert(@readableStreamHasDefaultReader(P)),@getByIdDirectPrivate(_,\"queue\").content\?.isNotEmpty()){const R=@getByIdDirectPrivate(_,\"queue\").content.shift();@getByIdDirectPrivate(_,\"queue\").size-=R.byteLength,@readableByteStreamControllerHandleQueueDrain(_);let h;try{h=new @Uint8Array(R.buffer,R.byteOffset,R.byteLength)}catch(F){return @Promise.@reject(F)}return @createFulfilledPromise({value:h,done:!1})}if(@getByIdDirectPrivate(_,\"autoAllocateChunkSize\")!==@undefined){let R;try{R=@createUninitializedArrayBuffer(@getByIdDirectPrivate(_,\"autoAllocateChunkSize\"))}catch(F){return @Promise.@reject(F)}const h={buffer:R,byteOffset:0,byteLength:@getByIdDirectPrivate(_,\"autoAllocateChunkSize\"),bytesFilled:0,elementSize:1,ctor:@Uint8Array,readerType:\"default\"};@getByIdDirectPrivate(_,\"pendingPullIntos\").push(h)}const d=@readableStreamAddReadRequest(P);return @readableByteStreamControllerCallPullIfNeeded(_),d})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerPullCode = "(function (_){\"use strict\";const d=@getByIdDirectPrivate(_,\"controlledReadableStream\");if(@assert(@readableStreamHasDefaultReader(d)),@getByIdDirectPrivate(_,\"queue\").content\?.isNotEmpty()){const R=@getByIdDirectPrivate(_,\"queue\").content.shift();@getByIdDirectPrivate(_,\"queue\").size-=R.byteLength,@readableByteStreamControllerHandleQueueDrain(_);let F;try{F=new @Uint8Array(R.buffer,R.byteOffset,R.byteLength)}catch(P){return @Promise.@reject(P)}return @createFulfilledPromise({value:F,done:!1})}if(@getByIdDirectPrivate(_,\"autoAllocateChunkSize\")!==@undefined){let R;try{R=@createUninitializedArrayBuffer(@getByIdDirectPrivate(_,\"autoAllocateChunkSize\"))}catch(P){return @Promise.@reject(P)}const F={buffer:R,byteOffset:0,byteLength:@getByIdDirectPrivate(_,\"autoAllocateChunkSize\"),bytesFilled:0,elementSize:1,ctor:@Uint8Array,readerType:\"default\"};@getByIdDirectPrivate(_,\"pendingPullIntos\").push(F)}const h=@readableStreamAddReadRequest(d);return @readableByteStreamControllerCallPullIfNeeded(_),h})\n"; // readableByteStreamControllerShouldCallPull const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerShouldCallPullCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2780,7 +2780,7 @@ const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamContro const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCodeLength = 1076; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCode = "(function (i,d){\"use strict\";const f=@getByIdDirectPrivate(i,\"controlledReadableStream\");switch(@assert(!@getByIdDirectPrivate(i,\"closeRequested\")),@assert(@getByIdDirectPrivate(f,\"state\")===@streamReadable),@getByIdDirectPrivate(f,\"reader\")\?@readableStreamReaderKind(@getByIdDirectPrivate(f,\"reader\")):0){case 1:{if(!@getByIdDirectPrivate(@getByIdDirectPrivate(f,\"reader\"),\"readRequests\")\?.isNotEmpty())@readableByteStreamControllerEnqueueChunk(i,@transferBufferToCurrentRealm(d.buffer),d.byteOffset,d.byteLength);else{@assert(!@getByIdDirectPrivate(i,\"queue\").content.size());const _=d.constructor===@Uint8Array\?d:new @Uint8Array(d.buffer,d.byteOffset,d.byteLength);@readableStreamFulfillReadRequest(f,_,!1)}break}case 2:{@readableByteStreamControllerEnqueueChunk(i,@transferBufferToCurrentRealm(d.buffer),d.byteOffset,d.byteLength),@readableByteStreamControllerProcessPullDescriptors(i);break}case 3:break;default:{@assert(!@isReadableStreamLocked(f)),@readableByteStreamControllerEnqueueChunk(i,@transferBufferToCurrentRealm(d.buffer),d.byteOffset,d.byteLength);break}}})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCode = "(function (i,f){\"use strict\";const d=@getByIdDirectPrivate(i,\"controlledReadableStream\");switch(@assert(!@getByIdDirectPrivate(i,\"closeRequested\")),@assert(@getByIdDirectPrivate(d,\"state\")===@streamReadable),@getByIdDirectPrivate(d,\"reader\")\?@readableStreamReaderKind(@getByIdDirectPrivate(d,\"reader\")):0){case 1:{if(!@getByIdDirectPrivate(@getByIdDirectPrivate(d,\"reader\"),\"readRequests\")\?.isNotEmpty())@readableByteStreamControllerEnqueueChunk(i,@transferBufferToCurrentRealm(f.buffer),f.byteOffset,f.byteLength);else{@assert(!@getByIdDirectPrivate(i,\"queue\").content.size());const _=f.constructor===@Uint8Array\?f:new @Uint8Array(f.buffer,f.byteOffset,f.byteLength);@readableStreamFulfillReadRequest(d,_,!1)}break}case 2:{@readableByteStreamControllerEnqueueChunk(i,@transferBufferToCurrentRealm(f.buffer),f.byteOffset,f.byteLength),@readableByteStreamControllerProcessPullDescriptors(i);break}case 3:break;default:{@assert(!@isReadableStreamLocked(d)),@readableByteStreamControllerEnqueueChunk(i,@transferBufferToCurrentRealm(f.buffer),f.byteOffset,f.byteLength);break}}})\n"; // readableByteStreamControllerEnqueueChunk const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerEnqueueChunkCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2796,7 +2796,7 @@ const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamContro const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCodeLength = 417; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCode = "(function (u,a){\"use strict\";@assert(@getByIdDirectPrivate(u,\"pendingPullIntos\").isNotEmpty());let d=@getByIdDirectPrivate(u,\"pendingPullIntos\").peek();if(d.byteOffset+d.bytesFilled!==a.byteOffset)@throwRangeError(\"Invalid value for view.byteOffset\");if(d.byteLength!==a.byteLength)@throwRangeError(\"Invalid value for view.byteLength\");d.buffer=a.buffer,@readableByteStreamControllerRespondInternal(u,a.byteLength)})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCode = "(function (u,d){\"use strict\";@assert(@getByIdDirectPrivate(u,\"pendingPullIntos\").isNotEmpty());let a=@getByIdDirectPrivate(u,\"pendingPullIntos\").peek();if(a.byteOffset+a.bytesFilled!==d.byteOffset)@throwRangeError(\"Invalid value for view.byteOffset\");if(a.byteLength!==d.byteLength)@throwRangeError(\"Invalid value for view.byteLength\");a.buffer=d.buffer,@readableByteStreamControllerRespondInternal(u,d.byteLength)})\n"; // readableByteStreamControllerRespond const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerRespondCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2812,7 +2812,7 @@ const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamContro const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCodeLength = 464; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCode = "(function (d,u){\"use strict\";let k=@getByIdDirectPrivate(d,\"pendingPullIntos\").peek(),_=@getByIdDirectPrivate(d,\"controlledReadableStream\");if(@getByIdDirectPrivate(_,\"state\")===@streamClosed){if(u!==0)@throwTypeError(\"bytesWritten is different from 0 even though stream is closed\");@readableByteStreamControllerRespondInClosedState(d,k)}else @assert(@getByIdDirectPrivate(_,\"state\")===@streamReadable),@readableByteStreamControllerRespondInReadableState(d,u,k)})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCode = "(function (d,u){\"use strict\";let _=@getByIdDirectPrivate(d,\"pendingPullIntos\").peek(),k=@getByIdDirectPrivate(d,\"controlledReadableStream\");if(@getByIdDirectPrivate(k,\"state\")===@streamClosed){if(u!==0)@throwTypeError(\"bytesWritten is different from 0 even though stream is closed\");@readableByteStreamControllerRespondInClosedState(d,_)}else @assert(@getByIdDirectPrivate(k,\"state\")===@streamReadable),@readableByteStreamControllerRespondInReadableState(d,u,_)})\n"; // readableByteStreamControllerRespondInReadableState const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2820,7 +2820,7 @@ const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamContro const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCodeLength = 799; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCode = "(function (w,R,_){\"use strict\";if(_.bytesFilled+R>_.byteLength)@throwRangeError(\"bytesWritten value is too great\");if(@assert(@getByIdDirectPrivate(w,\"pendingPullIntos\").isEmpty()||@getByIdDirectPrivate(w,\"pendingPullIntos\").peek()===_),@readableByteStreamControllerInvalidateBYOBRequest(w),_.bytesFilled+=R,_.bytesFilled<_.elementSize)return;@readableByteStreamControllerShiftPendingDescriptor(w);const g=_.bytesFilled%_.elementSize;if(g>0){const h=_.byteOffset+_.bytesFilled,f=@cloneArrayBuffer(_.buffer,h-g,g);@readableByteStreamControllerEnqueueChunk(w,f,0,f.byteLength)}_.buffer=@transferBufferToCurrentRealm(_.buffer),_.bytesFilled-=g,@readableByteStreamControllerCommitDescriptor(@getByIdDirectPrivate(w,\"controlledReadableStream\"),_),@readableByteStreamControllerProcessPullDescriptors(w)})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCode = "(function (w,h,g){\"use strict\";if(g.bytesFilled+h>g.byteLength)@throwRangeError(\"bytesWritten value is too great\");if(@assert(@getByIdDirectPrivate(w,\"pendingPullIntos\").isEmpty()||@getByIdDirectPrivate(w,\"pendingPullIntos\").peek()===g),@readableByteStreamControllerInvalidateBYOBRequest(w),g.bytesFilled+=h,g.bytesFilled0){const _=g.byteOffset+g.bytesFilled,f=@cloneArrayBuffer(g.buffer,_-R,R);@readableByteStreamControllerEnqueueChunk(w,f,0,f.byteLength)}g.buffer=@transferBufferToCurrentRealm(g.buffer),g.bytesFilled-=R,@readableByteStreamControllerCommitDescriptor(@getByIdDirectPrivate(w,\"controlledReadableStream\"),g),@readableByteStreamControllerProcessPullDescriptors(w)})\n"; // readableByteStreamControllerRespondInClosedState const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2828,7 +2828,7 @@ const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamContro const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCodeLength = 502; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCode = "(function (a,_){\"use strict\";if(_.buffer=@transferBufferToCurrentRealm(_.buffer),@assert(_.bytesFilled===0),@readableStreamHasBYOBReader(@getByIdDirectPrivate(a,\"controlledReadableStream\")))while(@getByIdDirectPrivate(@getByIdDirectPrivate(@getByIdDirectPrivate(a,\"controlledReadableStream\"),\"reader\"),\"readIntoRequests\")\?.isNotEmpty()){let d=@readableByteStreamControllerShiftPendingDescriptor(a);@readableByteStreamControllerCommitDescriptor(@getByIdDirectPrivate(a,\"controlledReadableStream\"),d)}})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCode = "(function (a,d){\"use strict\";if(d.buffer=@transferBufferToCurrentRealm(d.buffer),@assert(d.bytesFilled===0),@readableStreamHasBYOBReader(@getByIdDirectPrivate(a,\"controlledReadableStream\")))while(@getByIdDirectPrivate(@getByIdDirectPrivate(@getByIdDirectPrivate(a,\"controlledReadableStream\"),\"reader\"),\"readIntoRequests\")\?.isNotEmpty()){let _=@readableByteStreamControllerShiftPendingDescriptor(a);@readableByteStreamControllerCommitDescriptor(@getByIdDirectPrivate(a,\"controlledReadableStream\"),_)}})\n"; // readableByteStreamControllerProcessPullDescriptors const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerProcessPullDescriptorsCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2844,7 +2844,7 @@ const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamContro const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCodeLength = 970; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCode = "(function (q,j){\"use strict\";const k=j.bytesFilled-j.bytesFilled%j.elementSize,v=@getByIdDirectPrivate(q,\"queue\").sizek)E=z-j.bytesFilled,G=!0;while(E>0){let H=@getByIdDirectPrivate(q,\"queue\").content.peek();const J=E0),@assert(j.bytesFilledj)z=w-_.bytesFilled,E=!0;while(z>0){let G=@getByIdDirectPrivate(q,\"queue\").content.peek();const H=z0),@assert(_.bytesFilled<_.elementSize);return E})\n"; // readableByteStreamControllerShiftPendingDescriptor const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerShiftPendingDescriptorCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2852,7 +2852,7 @@ const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamContro const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerShiftPendingDescriptorCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableByteStreamInternalsReadableByteStreamControllerShiftPendingDescriptorCodeLength = 150; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerShiftPendingDescriptorCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerShiftPendingDescriptorCode = "(function (u){\"use strict\";let _=@getByIdDirectPrivate(u,\"pendingPullIntos\").shift();return @readableByteStreamControllerInvalidateBYOBRequest(u),_})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerShiftPendingDescriptorCode = "(function (_){\"use strict\";let u=@getByIdDirectPrivate(_,\"pendingPullIntos\").shift();return @readableByteStreamControllerInvalidateBYOBRequest(_),u})\n"; // readableByteStreamControllerInvalidateBYOBRequest const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerInvalidateBYOBRequestCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2900,7 +2900,7 @@ const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamContro const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerPullIntoCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_readableByteStreamInternalsReadableByteStreamControllerPullIntoCodeLength = 1255; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerPullIntoCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerPullIntoCode = "(function (_,A){\"use strict\";const b=@getByIdDirectPrivate(_,\"controlledReadableStream\");let d=1;if(A.BYTES_PER_ELEMENT!==@undefined)d=A.BYTES_PER_ELEMENT;const k=A.constructor,E={buffer:A.buffer,byteOffset:A.byteOffset,byteLength:A.byteLength,bytesFilled:0,elementSize:d,ctor:k,readerType:\"byob\"};var L=@getByIdDirectPrivate(_,\"pendingPullIntos\");if(L\?.isNotEmpty())return E.buffer=@transferBufferToCurrentRealm(E.buffer),L.push(E),@readableStreamAddReadIntoRequest(b);if(@getByIdDirectPrivate(b,\"state\")===@streamClosed){const R=new k(E.buffer,E.byteOffset,0);return @createFulfilledPromise({value:R,done:!0})}if(@getByIdDirectPrivate(_,\"queue\").size>0){if(@readableByteStreamControllerFillDescriptorFromQueue(_,E)){const R=@readableByteStreamControllerConvertDescriptor(E);return @readableByteStreamControllerHandleQueueDrain(_),@createFulfilledPromise({value:R,done:!1})}if(@getByIdDirectPrivate(_,\"closeRequested\")){const R=@makeTypeError(\"Closing stream has been requested\");return @readableByteStreamControllerError(_,R),@Promise.@reject(R)}}E.buffer=@transferBufferToCurrentRealm(E.buffer),@getByIdDirectPrivate(_,\"pendingPullIntos\").push(E);const N=@readableStreamAddReadIntoRequest(b);return @readableByteStreamControllerCallPullIfNeeded(_),N})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerPullIntoCode = "(function (b,A){\"use strict\";const E=@getByIdDirectPrivate(b,\"controlledReadableStream\");let L=1;if(A.BYTES_PER_ELEMENT!==@undefined)L=A.BYTES_PER_ELEMENT;const d=A.constructor,N={buffer:A.buffer,byteOffset:A.byteOffset,byteLength:A.byteLength,bytesFilled:0,elementSize:L,ctor:d,readerType:\"byob\"};var _=@getByIdDirectPrivate(b,\"pendingPullIntos\");if(_\?.isNotEmpty())return N.buffer=@transferBufferToCurrentRealm(N.buffer),_.push(N),@readableStreamAddReadIntoRequest(E);if(@getByIdDirectPrivate(E,\"state\")===@streamClosed){const k=new d(N.buffer,N.byteOffset,0);return @createFulfilledPromise({value:k,done:!0})}if(@getByIdDirectPrivate(b,\"queue\").size>0){if(@readableByteStreamControllerFillDescriptorFromQueue(b,N)){const k=@readableByteStreamControllerConvertDescriptor(N);return @readableByteStreamControllerHandleQueueDrain(b),@createFulfilledPromise({value:k,done:!1})}if(@getByIdDirectPrivate(b,\"closeRequested\")){const k=@makeTypeError(\"Closing stream has been requested\");return @readableByteStreamControllerError(b,k),@Promise.@reject(k)}}N.buffer=@transferBufferToCurrentRealm(N.buffer),@getByIdDirectPrivate(b,\"pendingPullIntos\").push(N);const R=@readableStreamAddReadIntoRequest(E);return @readableByteStreamControllerCallPullIfNeeded(b),R})\n"; // readableStreamAddReadIntoRequest const JSC::ConstructAbility s_readableByteStreamInternalsReadableStreamAddReadIntoRequestCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2952,7 +2952,7 @@ const JSC::ConstructorKind s_eventSourceGetEventSourceCodeConstructorKind = JSC: const JSC::ImplementationVisibility s_eventSourceGetEventSourceCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_eventSourceGetEventSourceCodeLength = 5477; static const JSC::Intrinsic s_eventSourceGetEventSourceCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_eventSourceGetEventSourceCode = "(function (){\"use strict\";class B extends EventTarget{#$;#j;#w;#A;#B;#F=!1;#G=null;#J=\"\";#K=\"\";#L=\"\";#M=!0;#O=0;#Q=0;#U=0;#V=null;static#W(W){W.#H()}static#X(W,Q){const F=W.data,G=F.#L\?`Last-Event-ID: ${F.#L}\\r\\n`:\"\",j=`GET ${Q.pathname}${Q.search} HTTP/1.1\\r\\nHost: bun\\r\\nContent-type: text/event-stream\\r\\nContent-length: 0\\r\\n${G}\\r\\n`,X=W.write(j);if(X!==j.length)F.#K=j.substring(X)}static#Y(W,Q,F){for(;;){if(F>=Q.length)return;let G=-1,j=Q.indexOf(\"\\r\\n\",F);const X=j+2;if(j>0)if(W.#O===0){const z=parseInt(Q.substring(F,j),16);if(z===0){W.#j=2,W.#G\?.end();return}G=X+z}else G=Q.length;else{if(W.#J.length===0){W.#J+=Q.substring(F);return}G=Q.length}let Y=Q.substring(X,G);F=G+2;let J=0,Z=Y.indexOf(\"\\n\\n\");if(Z==-1){W.#J+=Q.substring(X);return}if(W.#J.length)W.#J+=Y,Y=W.#J,W.#J=\"\";let K=!0;while(K){const z=Y.substring(J,Z);let L,w=\"\",A,H=0,M=-1;for(;;){let U=z.indexOf(\"\\n\",H);if(U===-1){if(H>=z.length)break;U=z.length}const V=z.substring(H,U);if(V.startsWith(\"data:\"))if(w.length)w+=`\\n${V.substring(5).trim()}`;else w=V.substring(5).trim();else if(V.startsWith(\"event:\"))L=V.substring(6).trim();else if(V.startsWith(\"id:\"))A=V.substring(3).trim();else if(V.startsWith(\"retry:\")){if(M=parseInt(V.substring(6).trim(),10),@isNaN(M))M=-1}H=U+1}if(W.#L=A||\"\",M>=0)W.#U=M;if(w||A||L)W.dispatchEvent(new MessageEvent(L||\"message\",{data:w||\"\",origin:W.#$.origin,source:W,lastEventId:A}));if(Y.length===Z+2){K=!1;break}const O=Y.indexOf(\"\\n\\n\",Z+1);if(O===-1)break;J=Z,Z=O}}}static#Z={open(W){const Q=W.data;if(Q.#G=W,!Q.#F)B.#X(W,Q.#$)},handshake(W,Q,F){const G=W.data;if(Q)B.#X(W,G.#$);else G.#j=2,G.dispatchEvent(new ErrorEvent(\"error\",{error:F})),W.end()},data(W,Q){const F=W.data;switch(F.#j){case 0:{let G=Q.toString();const j=G.indexOf(\"\\r\\n\\r\\n\");if(j===-1){F.#J+=G;return}if(F.#J.length)F.#J+=G,G=F.#J,F.#J=\"\";const X=G.substring(0,j),Y=X.indexOf(\"\\r\\n\");if(Y===-1){F.#j=2,F.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(\"Invalid HTTP request\")})),W.end();return}const J=X.substring(0,Y);if(J!==\"HTTP/1.1 200 OK\"){F.#j=2,F.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(J)})),W.end();return}let Z=Y+1,K=!1,z=-1;for(;;){let w=X.indexOf(\"\\r\\n\",Z);if(w===-1){if(Z>=X.length){if(!K)F.#j=2,F.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(`EventSource's response has no MIME type and \"text/event-stream\" is required. Aborting the connection.`)})),W.end();return}w=X.length}const A=X.substring(Z+1,w),H=A.indexOf(\":\"),M=A.substring(0,H),O=M.localeCompare(\"content-type\",@undefined,{sensitivity:\"accent\"})===0;if(Z=w+1,O)if(A.endsWith(\" text/event-stream\"))K=!0;else{F.#j=2,F.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(`EventSource's response has a MIME type that is not \"text/event-stream\". Aborting the connection.`)})),W.end();return}else if(M.localeCompare(\"content-length\",@undefined,{sensitivity:\"accent\"})===0){if(z=parseInt(A.substring(H+1).trim(),10),@isNaN(z)||z<=0){F.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(`EventSource's Content-Length is invalid. Aborting the connection.`)})),W.end();return}if(K)break}else if(M.localeCompare(\"transfer-encoding\",@undefined,{sensitivity:\"accent\"})===0){if(A.substring(H+1).trim()!==\"chunked\"){F.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(`EventSource's Transfer-Encoding is invalid. Aborting the connection.`)})),W.end();return}if(z=0,K)break}}F.#O=z,F.#j=1,F.dispatchEvent(new Event(\"open\"));const L=G.substring(j+4);if(B.#Y(F,L,0),F.#O>0){if(F.#Q+=L.length,F.#Q>=F.#O)F.#j=2,W.end()}return}case 1:if(B.#Y(F,Q.toString(),2),F.#O>0){if(F.#Q+=Q.byteLength,F.#Q>=F.#O)F.#j=2,W.end()}return;default:break}},drain(W){const Q=W.data;if(Q.#j===0){const F=Q.#J;if(F.length){const G=W.write(F);if(G!==F.length)W.data.#K=F.substring(G);else W.data.#K=\"\"}}},close:B.#z,end(W){B.#z(W).dispatchEvent(new ErrorEvent(\"error\",{error:new Error(\"Connection closed by server\")}))},timeout(W){B.#z(W).dispatchEvent(new ErrorEvent(\"error\",{error:new Error(\"Timeout\")}))},binaryType:\"buffer\"};static#z(W){const Q=W.data;if(Q.#G=null,Q.#Q=0,Q.#j=2,Q.#M){if(Q.#V)clearTimeout(Q.#V);Q.#V=setTimeout(B.#W,Q.#U,Q)}return Q}constructor(W,Q=@undefined){super();const F=new URL(W);this.#F=F.protocol===\"https:\",this.#$=F,this.#j=2,process.nextTick(B.#W,this)}ref(){this.#V\?.ref(),this.#G\?.ref()}unref(){this.#V\?.unref(),this.#G\?.unref()}#H(){if(this.#j!==2)return;const W=this.#$,Q=this.#F;this.#j=0,@Bun.connect({data:this,socket:B.#Z,hostname:W.hostname,port:parseInt(W.port||(Q\?\"443\":\"80\"),10),tls:Q\?{requestCert:!0,rejectUnauthorized:!1}:!1}).catch((F)=>{if(super.dispatchEvent(new ErrorEvent(\"error\",{error:F})),this.#M){if(this.#V)this.#V.unref\?.();this.#V=setTimeout(B.#W,1000,this)}})}get url(){return this.#$.href}get readyState(){return this.#j}close(){this.#M=!1,this.#j=2,this.#G\?.unref(),this.#G\?.end()}get onopen(){return this.#B}get onerror(){return this.#w}get onmessage(){return this.#A}set onopen(W){if(this.#B)super.removeEventListener(\"close\",this.#B);super.addEventListener(\"open\",W),this.#B=W}set onerror(W){if(this.#w)super.removeEventListener(\"error\",this.#w);super.addEventListener(\"error\",W),this.#w=W}set onmessage(W){if(this.#A)super.removeEventListener(\"message\",this.#A);super.addEventListener(\"message\",W),this.#A=W}}return Object.defineProperty(B.prototype,\"CONNECTING\",{enumerable:!0,value:0}),Object.defineProperty(B.prototype,\"OPEN\",{enumerable:!0,value:1}),Object.defineProperty(B.prototype,\"CLOSED\",{enumerable:!0,value:2}),B[Symbol.for(\"CommonJS\")]=0,B})\n"; +const char* const s_eventSourceGetEventSourceCode = "(function (){\"use strict\";class A extends EventTarget{#$;#j;#w;#A;#B;#F=!1;#G=null;#J=\"\";#K=\"\";#L=\"\";#M=!0;#O=0;#Q=0;#U=0;#V=null;static#W(Q){Q.#H()}static#X(Q,U){const V=Q.data,B=V.#L\?`Last-Event-ID: ${V.#L}\\r\\n`:\"\",W=`GET ${U.pathname}${U.search} HTTP/1.1\\r\\nHost: bun\\r\\nContent-type: text/event-stream\\r\\nContent-length: 0\\r\\n${B}\\r\\n`,X=Q.write(W);if(X!==W.length)V.#K=W.substring(X)}static#Y(Q,U,V){for(;;){if(V>=U.length)return;let B=-1,W=U.indexOf(\"\\r\\n\",V);const X=W+2;if(W>0)if(Q.#O===0){const j=parseInt(U.substring(V,W),16);if(j===0){Q.#j=2,Q.#G\?.end();return}B=X+j}else B=U.length;else{if(Q.#J.length===0){Q.#J+=U.substring(V);return}B=U.length}let M=U.substring(X,B);V=B+2;let F=0,Y=M.indexOf(\"\\n\\n\");if(Y==-1){Q.#J+=U.substring(X);return}if(Q.#J.length)Q.#J+=M,M=Q.#J,Q.#J=\"\";let G=!0;while(G){const j=M.substring(F,Y);let J,Z=\"\",O,w=0,K=-1;for(;;){let L=j.indexOf(\"\\n\",w);if(L===-1){if(w>=j.length)break;L=j.length}const H=j.substring(w,L);if(H.startsWith(\"data:\"))if(Z.length)Z+=`\\n${H.substring(5).trim()}`;else Z=H.substring(5).trim();else if(H.startsWith(\"event:\"))J=H.substring(6).trim();else if(H.startsWith(\"id:\"))O=H.substring(3).trim();else if(H.startsWith(\"retry:\")){if(K=parseInt(H.substring(6).trim(),10),@isNaN(K))K=-1}w=L+1}if(Q.#L=O||\"\",K>=0)Q.#U=K;if(Z||O||J)Q.dispatchEvent(new MessageEvent(J||\"message\",{data:Z||\"\",origin:Q.#$.origin,source:Q,lastEventId:O}));if(M.length===Y+2){G=!1;break}const z=M.indexOf(\"\\n\\n\",Y+1);if(z===-1)break;F=Y,Y=z}}}static#Z={open(Q){const U=Q.data;if(U.#G=Q,!U.#F)A.#X(Q,U.#$)},handshake(Q,U,V){const B=Q.data;if(U)A.#X(Q,B.#$);else B.#j=2,B.dispatchEvent(new ErrorEvent(\"error\",{error:V})),Q.end()},data(Q,U){const V=Q.data;switch(V.#j){case 0:{let B=U.toString();const W=B.indexOf(\"\\r\\n\\r\\n\");if(W===-1){V.#J+=B;return}if(V.#J.length)V.#J+=B,B=V.#J,V.#J=\"\";const X=B.substring(0,W),M=X.indexOf(\"\\r\\n\");if(M===-1){V.#j=2,V.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(\"Invalid HTTP request\")})),Q.end();return}const F=X.substring(0,M);if(F!==\"HTTP/1.1 200 OK\"){V.#j=2,V.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(F)})),Q.end();return}let Y=M+1,G=!1,j=-1;for(;;){let Z=X.indexOf(\"\\r\\n\",Y);if(Z===-1){if(Y>=X.length){if(!G)V.#j=2,V.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(`EventSource's response has no MIME type and \"text/event-stream\" is required. Aborting the connection.`)})),Q.end();return}Z=X.length}const O=X.substring(Y+1,Z),w=O.indexOf(\":\"),K=O.substring(0,w),z=K.localeCompare(\"content-type\",@undefined,{sensitivity:\"accent\"})===0;if(Y=Z+1,z)if(O.endsWith(\" text/event-stream\"))G=!0;else{V.#j=2,V.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(`EventSource's response has a MIME type that is not \"text/event-stream\". Aborting the connection.`)})),Q.end();return}else if(K.localeCompare(\"content-length\",@undefined,{sensitivity:\"accent\"})===0){if(j=parseInt(O.substring(w+1).trim(),10),@isNaN(j)||j<=0){V.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(`EventSource's Content-Length is invalid. Aborting the connection.`)})),Q.end();return}if(G)break}else if(K.localeCompare(\"transfer-encoding\",@undefined,{sensitivity:\"accent\"})===0){if(O.substring(w+1).trim()!==\"chunked\"){V.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(`EventSource's Transfer-Encoding is invalid. Aborting the connection.`)})),Q.end();return}if(j=0,G)break}}V.#O=j,V.#j=1,V.dispatchEvent(new Event(\"open\"));const J=B.substring(W+4);if(A.#Y(V,J,0),V.#O>0){if(V.#Q+=J.length,V.#Q>=V.#O)V.#j=2,Q.end()}return}case 1:if(A.#Y(V,U.toString(),2),V.#O>0){if(V.#Q+=U.byteLength,V.#Q>=V.#O)V.#j=2,Q.end()}return;default:break}},drain(Q){const U=Q.data;if(U.#j===0){const V=U.#J;if(V.length){const B=Q.write(V);if(B!==V.length)Q.data.#K=V.substring(B);else Q.data.#K=\"\"}}},close:A.#z,end(Q){A.#z(Q).dispatchEvent(new ErrorEvent(\"error\",{error:new Error(\"Connection closed by server\")}))},timeout(Q){A.#z(Q).dispatchEvent(new ErrorEvent(\"error\",{error:new Error(\"Timeout\")}))},binaryType:\"buffer\"};static#z(Q){const U=Q.data;if(U.#G=null,U.#Q=0,U.#j=2,U.#M){if(U.#V)clearTimeout(U.#V);U.#V=setTimeout(A.#W,U.#U,U)}return U}constructor(Q,U=@undefined){super();const V=new URL(Q);this.#F=V.protocol===\"https:\",this.#$=V,this.#j=2,process.nextTick(A.#W,this)}ref(){this.#V\?.ref(),this.#G\?.ref()}unref(){this.#V\?.unref(),this.#G\?.unref()}#H(){if(this.#j!==2)return;const Q=this.#$,U=this.#F;this.#j=0,@Bun.connect({data:this,socket:A.#Z,hostname:Q.hostname,port:parseInt(Q.port||(U\?\"443\":\"80\"),10),tls:U\?{requestCert:!0,rejectUnauthorized:!1}:!1}).catch((V)=>{if(super.dispatchEvent(new ErrorEvent(\"error\",{error:V})),this.#M){if(this.#V)this.#V.unref\?.();this.#V=setTimeout(A.#W,1000,this)}})}get url(){return this.#$.href}get readyState(){return this.#j}close(){this.#M=!1,this.#j=2,this.#G\?.unref(),this.#G\?.end()}get onopen(){return this.#B}get onerror(){return this.#w}get onmessage(){return this.#A}set onopen(Q){if(this.#B)super.removeEventListener(\"close\",this.#B);super.addEventListener(\"open\",Q),this.#B=Q}set onerror(Q){if(this.#w)super.removeEventListener(\"error\",this.#w);super.addEventListener(\"error\",Q),this.#w=Q}set onmessage(Q){if(this.#A)super.removeEventListener(\"message\",this.#A);super.addEventListener(\"message\",Q),this.#A=Q}}return Object.defineProperty(A.prototype,\"CONNECTING\",{enumerable:!0,value:0}),Object.defineProperty(A.prototype,\"OPEN\",{enumerable:!0,value:1}),Object.defineProperty(A.prototype,\"CLOSED\",{enumerable:!0,value:2}),A[Symbol.for(\"CommonJS\")]=0,A})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ diff --git a/src/js/out/modules/node/assert.js b/src/js/out/modules/node/assert.js index dbcaf0a02..4086ef8d5 100644 --- a/src/js/out/modules/node/assert.js +++ b/src/js/out/modules/node/assert.js @@ -1,53 +1,53 @@ -import J from"node:util";var f1=function(){throw new Error("CallTracker is not supported yet")},{Bun:j1}=globalThis[Symbol.for("Bun.lazy")]("primordials"),O=j1.deepEquals,N=(X,_)=>function(){return _||(0,X[Object.keys(X)[0]])((_={exports:{}}).exports,_),_.exports},z=N({"assert/build/internal/errors.js"(X,_){function u(H1){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?u=function(Q1){return typeof Q1}:u=function(Q1){return Q1&&typeof Symbol=="function"&&Q1.constructor===Symbol&&Q1!==Symbol.prototype?"symbol":typeof Q1},u(H1)}function n(H1,Q1){if(!(H1 instanceof Q1))throw new TypeError("Cannot call a class as a function")}function i(H1,Q1){return Q1&&(u(Q1)==="object"||typeof Q1=="function")?Q1:U(H1)}function U(H1){if(H1===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return H1}function p(H1){return p=Object.setPrototypeOf?Object.getPrototypeOf:function(Q1){return Q1.__proto__||Object.getPrototypeOf(Q1)},p(H1)}function l(H1,Q1){if(typeof Q1!="function"&&Q1!==null)throw new TypeError("Super expression must either be null or a function");H1.prototype=Object.create(Q1&&Q1.prototype,{constructor:{value:H1,writable:!0,configurable:!0}}),Q1&&c(H1,Q1)}function c(H1,Q1){return c=Object.setPrototypeOf||function(Z1,W){return Z1.__proto__=W,Z1},c(H1,Q1)}var o={},$,a;function t(H1,Q1,Z1){Z1||(Z1=Error);function W(z1,X1,U1){return typeof Q1=="string"?Q1:Q1(z1,X1,U1)}var J1=function(z1){l(X1,z1);function X1(U1,Y,$1){var K1;return n(this,X1),K1=i(this,p(X1).call(this,W(U1,Y,$1))),K1.code=H1,K1}return X1}(Z1);o[H1]=J1}function r(H1,Q1){if(Array.isArray(H1)){var Z1=H1.length;return H1=H1.map(function(W){return String(W)}),Z1>2?"one of ".concat(Q1," ").concat(H1.slice(0,Z1-1).join(", "),", or ")+H1[Z1-1]:Z1===2?"one of ".concat(Q1," ").concat(H1[0]," or ").concat(H1[1]):"of ".concat(Q1," ").concat(H1[0])}else return"of ".concat(Q1," ").concat(String(H1))}function s(H1,Q1,Z1){return H1.substr(!Z1||Z1<0?0:+Z1,Q1.length)===Q1}function K(H1,Q1,Z1){return(Z1===void 0||Z1>H1.length)&&(Z1=H1.length),H1.substring(Z1-Q1.length,Z1)===Q1}function e(H1,Q1,Z1){return typeof Z1!="number"&&(Z1=0),Z1+Q1.length>H1.length?!1:H1.indexOf(Q1,Z1)!==-1}t("ERR_AMBIGUOUS_ARGUMENT",'The "%s" argument is ambiguous. %s',TypeError),t("ERR_INVALID_ARG_TYPE",function(H1,Q1,Z1){$===void 0&&($=F()),$(typeof H1=="string","'name' must be a string");var W;typeof Q1=="string"&&s(Q1,"not ")?(W="must not be",Q1=Q1.replace(/^not /,"")):W="must be";var J1;if(K(H1," argument"))J1="The ".concat(H1," ").concat(W," ").concat(r(Q1,"type"));else{var z1=e(H1,".")?"property":"argument";J1='The "'.concat(H1,'" ').concat(z1," ").concat(W," ").concat(r(Q1,"type"))}return J1+=". Received type ".concat(u(Z1)),J1},TypeError),t("ERR_INVALID_ARG_VALUE",function(H1,Q1){var Z1=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"is invalid",W=a.inspect(Q1);return W.length>128&&(W="".concat(W.slice(0,128),"...")),"The argument '".concat(H1,"' ").concat(Z1,". Received ").concat(W)},TypeError,RangeError),t("ERR_INVALID_RETURN_VALUE",function(H1,Q1,Z1){var W;return Z1&&Z1.constructor&&Z1.constructor.name?W="instance of ".concat(Z1.constructor.name):W="type ".concat(u(Z1)),"Expected ".concat(H1,' to be returned from the "').concat(Q1,'"')+" function but got ".concat(W,".")},TypeError),t("ERR_MISSING_ARGS",function(){for(var H1=arguments.length,Q1=new Array(H1),Z1=0;Z10,"At least one arg needs to be specified");var W="The ",J1=Q1.length;switch(Q1=Q1.map(function(z1){return'"'.concat(z1,'"')}),J1){case 1:W+="".concat(Q1[0]," argument");break;case 2:W+="".concat(Q1[0]," and ").concat(Q1[1]," arguments");break;default:W+=Q1.slice(0,J1-1).join(", "),W+=", and ".concat(Q1[J1-1]," arguments");break}return"".concat(W," must be specified")},TypeError),_.exports.codes=o}}),I=N({"assert/build/internal/assert/assertion_error.js"(X,_){function u(V1){for(var D1=1;D1V1.length)&&(M1=V1.length),V1.substring(M1-D1.length,M1)===D1}function J1(V1,D1){if(D1=Math.floor(D1),V1.length==0||D1==0)return"";var M1=V1.length*D1;for(D1=Math.floor(Math.log(D1)/Math.log(2));D1;)V1+=V1,D1--;return V1+=V1.substring(0,M1-V1.length),V1}var z1="",X1="",U1="",Y="",$1={deepStrictEqual:"Expected values to be strictly deep-equal:",strictEqual:"Expected values to be strictly equal:",strictEqualObject:'Expected "actual" to be reference-equal to "expected":',deepEqual:"Expected values to be loosely deep-equal:",equal:"Expected values to be loosely equal:",notDeepStrictEqual:'Expected "actual" not to be strictly deep-equal to:',notStrictEqual:'Expected "actual" to be strictly unequal to:',notStrictEqualObject:'Expected "actual" not to be reference-equal to "expected":',notDeepEqual:'Expected "actual" not to be loosely deep-equal to:',notEqual:'Expected "actual" to be loosely unequal to:',notIdentical:"Values identical but not reference-equal:"},K1=10;function W1(V1){var D1=Object.keys(V1),M1=Object.create(Object.getPrototypeOf(V1));return D1.forEach(function(V){M1[V]=V1[V]}),Object.defineProperty(M1,"message",{value:V1.message}),M1}function Y1(V1){return H1(V1,{compact:!1,customInspect:!1,depth:1000,maxArrayLength:Infinity,showHidden:!1,breakLength:Infinity,showProxy:!1,sorted:!0,getters:!0})}function B(V1,D1,M1){var V="",q1="",v1=0,G1="",T1=!1,D=Y1(V1),w1=D.split(` -`),O1=Y1(D1).split(` -`),M=0,H="";if(M1==="strictEqual"&&e(V1)==="object"&&e(D1)==="object"&&V1!==null&&D1!==null&&(M1="strictEqualObject"),w1.length===1&&O1.length===1&&w1[0]!==O1[0]){var q=w1[0].length+O1[0].length;if(q<=K1){if((e(V1)!=="object"||V1===null)&&(e(D1)!=="object"||D1===null)&&(V1!==0||D1!==0))return"".concat($1[M1],` +import X1 from"node:util";var D1=function(){throw new Error("CallTracker is not supported yet")},{Bun:$1}=globalThis[Symbol.for("Bun.lazy")]("primordials"),z1=$1.deepEquals,W1=(H,Q)=>function(){return Q||(0,H[Object.keys(H)[0]])((Q={exports:{}}).exports,Q),Q.exports},Y1=W1({"assert/build/internal/errors.js"(H,Q){function Z(G){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Z=function(T){return typeof T}:Z=function(T){return T&&typeof Symbol=="function"&&T.constructor===Symbol&&T!==Symbol.prototype?"symbol":typeof T},Z(G)}function J(G,T){if(!(G instanceof T))throw new TypeError("Cannot call a class as a function")}function z(G,T){return T&&(Z(T)==="object"||typeof T=="function")?T:X(G)}function X(G){if(G===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return G}function U(G){return U=Object.setPrototypeOf?Object.getPrototypeOf:function(T){return T.__proto__||Object.getPrototypeOf(T)},U(G)}function $(G,T){if(typeof T!="function"&&T!==null)throw new TypeError("Super expression must either be null or a function");G.prototype=Object.create(T&&T.prototype,{constructor:{value:G,writable:!0,configurable:!0}}),T&&K(G,T)}function K(G,T){return K=Object.setPrototypeOf||function(w,O){return w.__proto__=O,w},K(G,T)}var W={},Y,B;function V(G,T,w){w||(w=Error);function O(N,I,P){return typeof T=="string"?T:T(N,I,P)}var F=function(N){$(I,N);function I(P,A,S){var j;return J(this,I),j=z(this,U(I).call(this,O(P,A,S))),j.code=G,j}return I}(w);W[G]=F}function D(G,T){if(Array.isArray(G)){var w=G.length;return G=G.map(function(O){return String(O)}),w>2?"one of ".concat(T," ").concat(G.slice(0,w-1).join(", "),", or ")+G[w-1]:w===2?"one of ".concat(T," ").concat(G[0]," or ").concat(G[1]):"of ".concat(T," ").concat(G[0])}else return"of ".concat(T," ").concat(String(G))}function M(G,T,w){return G.substr(!w||w<0?0:+w,T.length)===T}function q(G,T,w){return(w===void 0||w>G.length)&&(w=G.length),G.substring(w-T.length,w)===T}function v(G,T,w){return typeof w!="number"&&(w=0),w+T.length>G.length?!1:G.indexOf(T,w)!==-1}V("ERR_AMBIGUOUS_ARGUMENT",'The "%s" argument is ambiguous. %s',TypeError),V("ERR_INVALID_ARG_TYPE",function(G,T,w){Y===void 0&&(Y=U1()),Y(typeof G=="string","'name' must be a string");var O;typeof T=="string"&&M(T,"not ")?(O="must not be",T=T.replace(/^not /,"")):O="must be";var F;if(q(G," argument"))F="The ".concat(G," ").concat(O," ").concat(D(T,"type"));else{var N=v(G,".")?"property":"argument";F='The "'.concat(G,'" ').concat(N," ").concat(O," ").concat(D(T,"type"))}return F+=". Received type ".concat(Z(w)),F},TypeError),V("ERR_INVALID_ARG_VALUE",function(G,T){var w=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"is invalid",O=B.inspect(T);return O.length>128&&(O="".concat(O.slice(0,128),"...")),"The argument '".concat(G,"' ").concat(w,". Received ").concat(O)},TypeError,RangeError),V("ERR_INVALID_RETURN_VALUE",function(G,T,w){var O;return w&&w.constructor&&w.constructor.name?O="instance of ".concat(w.constructor.name):O="type ".concat(Z(w)),"Expected ".concat(G,' to be returned from the "').concat(T,'"')+" function but got ".concat(O,".")},TypeError),V("ERR_MISSING_ARGS",function(){for(var G=arguments.length,T=new Array(G),w=0;w0,"At least one arg needs to be specified");var O="The ",F=T.length;switch(T=T.map(function(N){return'"'.concat(N,'"')}),F){case 1:O+="".concat(T[0]," argument");break;case 2:O+="".concat(T[0]," and ").concat(T[1]," arguments");break;default:O+=T.slice(0,F-1).join(", "),O+=", and ".concat(T[F-1]," arguments");break}return"".concat(O," must be specified")},TypeError),Q.exports.codes=W}}),B1=W1({"assert/build/internal/assert/assertion_error.js"(H,Q){function Z(L){for(var b=1;bL.length)&&(h=L.length),L.substring(h-b.length,h)===b}function F(L,b){if(b=Math.floor(b),L.length==0||b==0)return"";var h=L.length*b;for(b=Math.floor(Math.log(b)/Math.log(2));b;)L+=L,b--;return L+=L.substring(0,h-L.length),L}var N="",I="",P="",A="",S={deepStrictEqual:"Expected values to be strictly deep-equal:",strictEqual:"Expected values to be strictly equal:",strictEqualObject:'Expected "actual" to be reference-equal to "expected":',deepEqual:"Expected values to be loosely deep-equal:",equal:"Expected values to be loosely equal:",notDeepStrictEqual:'Expected "actual" not to be strictly deep-equal to:',notStrictEqual:'Expected "actual" to be strictly unequal to:',notStrictEqualObject:'Expected "actual" not to be reference-equal to "expected":',notDeepEqual:'Expected "actual" not to be loosely deep-equal to:',notEqual:'Expected "actual" to be loosely unequal to:',notIdentical:"Values identical but not reference-equal:"},j=10;function R(L){var b=Object.keys(L),h=Object.create(Object.getPrototypeOf(L));return b.forEach(function(k){h[k]=L[k]}),Object.defineProperty(h,"message",{value:L.message}),h}function f(L){return G(L,{compact:!1,customInspect:!1,depth:1000,maxArrayLength:Infinity,showHidden:!1,breakLength:Infinity,showProxy:!1,sorted:!0,getters:!0})}function C(L,b,h){var k="",m="",x=0,y="",g=!1,d=f(L),_=d.split(` +`),u=f(b).split(` +`),n=0,i="";if(h==="strictEqual"&&v(L)==="object"&&v(b)==="object"&&L!==null&&b!==null&&(h="strictEqualObject"),_.length===1&&u.length===1&&_[0]!==u[0]){var p=_[0].length+u[0].length;if(p<=j){if((v(L)!=="object"||L===null)&&(v(b)!=="object"||b===null)&&(L!==0||b!==0))return"".concat(S[h],` -`)+"".concat(w1[0]," !== ").concat(O1[0],` -`)}else if(M1!=="strictEqualObject"){var F1=process.stderr&&process.stderr.isTTY?process.stderr.columns:80;if(q2&&(H=` - `.concat(J1(" ",M),"^"),M=0)}}}for(var N1=w1[w1.length-1],v=O1[O1.length-1];N1===v&&(M++<2?G1=` - `.concat(N1).concat(G1):V=N1,w1.pop(),O1.pop(),!(w1.length===0||O1.length===0));)N1=w1[w1.length-1],v=O1[O1.length-1];var Q=Math.max(w1.length,O1.length);if(Q===0){var G=D.split(` -`);if(G.length>30)for(G[26]="".concat(z1,"...").concat(Y);G.length>27;)G.pop();return"".concat($1.notIdentical,` +`)+"".concat(_[0]," !== ").concat(u[0],` +`)}else if(h!=="strictEqualObject"){var l=process.stderr&&process.stderr.isTTY?process.stderr.columns:80;if(p2&&(i=` + `.concat(F(" ",n),"^"),n=0)}}}for(var c=_[_.length-1],o=u[u.length-1];c===o&&(n++<2?y=` + `.concat(c).concat(y):k=c,_.pop(),u.pop(),!(_.length===0||u.length===0));)c=_[_.length-1],o=u[u.length-1];var a=Math.max(_.length,u.length);if(a===0){var t=d.split(` +`);if(t.length>30)for(t[26]="".concat(N,"...").concat(A);t.length>27;)t.pop();return"".concat(S.notIdentical,` -`).concat(G.join(` +`).concat(t.join(` `),` -`)}M>3&&(G1=` -`.concat(z1,"...").concat(Y).concat(G1),T1=!0),V!==""&&(G1=` - `.concat(V).concat(G1),V="");var I1=0,P1=$1[M1]+` -`.concat(X1,"+ actual").concat(Y," ").concat(U1,"- expected").concat(Y),T=" ".concat(z1,"...").concat(Y," Lines skipped");for(M=0;M1&&M>2&&(Z>4?(q1+=` -`.concat(z1,"...").concat(Y),T1=!0):Z>3&&(q1+=` - `.concat(O1[M-2]),I1++),q1+=` - `.concat(O1[M-1]),I1++),v1=M,V+=` -`.concat(U1,"-").concat(Y," ").concat(O1[M]),I1++;else if(O1.length1&&M>2&&(Z>4?(q1+=` -`.concat(z1,"...").concat(Y),T1=!0):Z>3&&(q1+=` - `.concat(w1[M-2]),I1++),q1+=` - `.concat(w1[M-1]),I1++),v1=M,q1+=` -`.concat(X1,"+").concat(Y," ").concat(w1[M]),I1++;else{var w=O1[M],A1=w1[M],S1=A1!==w&&(!W(A1,",")||A1.slice(0,-1)!==w);S1&&W(w,",")&&w.slice(0,-1)===A1&&(S1=!1,A1+=","),S1?(Z>1&&M>2&&(Z>4?(q1+=` -`.concat(z1,"...").concat(Y),T1=!0):Z>3&&(q1+=` - `.concat(w1[M-2]),I1++),q1+=` - `.concat(w1[M-1]),I1++),v1=M,q1+=` -`.concat(X1,"+").concat(Y," ").concat(A1),V+=` -`.concat(U1,"-").concat(Y," ").concat(w),I1+=2):(q1+=V,V="",(Z===1||M===0)&&(q1+=` - `.concat(A1),I1++))}if(I1>20&&M30)for(M[26]="".concat(z1,"...").concat(Y);M.length>27;)M.pop();M.length===1?V=l(this,K(D1).call(this,"".concat(O1," ").concat(M[0]))):V=l(this,K(D1).call(this,"".concat(O1,` +`)}n>3&&(y=` +`.concat(N,"...").concat(A).concat(y),g=!0),k!==""&&(y=` + `.concat(k).concat(y),k="");var r=0,s=S[h]+` +`.concat(I,"+ actual").concat(A," ").concat(P,"- expected").concat(A),e=" ".concat(N,"...").concat(A," Lines skipped");for(n=0;n1&&n>2&&(H1>4?(m+=` +`.concat(N,"...").concat(A),g=!0):H1>3&&(m+=` + `.concat(u[n-2]),r++),m+=` + `.concat(u[n-1]),r++),x=n,k+=` +`.concat(P,"-").concat(A," ").concat(u[n]),r++;else if(u.length1&&n>2&&(H1>4?(m+=` +`.concat(N,"...").concat(A),g=!0):H1>3&&(m+=` + `.concat(_[n-2]),r++),m+=` + `.concat(_[n-1]),r++),x=n,m+=` +`.concat(I,"+").concat(A," ").concat(_[n]),r++;else{var Q1=u[n],Z1=_[n],J1=Z1!==Q1&&(!O(Z1,",")||Z1.slice(0,-1)!==Q1);J1&&O(Q1,",")&&Q1.slice(0,-1)===Z1&&(J1=!1,Z1+=","),J1?(H1>1&&n>2&&(H1>4?(m+=` +`.concat(N,"...").concat(A),g=!0):H1>3&&(m+=` + `.concat(_[n-2]),r++),m+=` + `.concat(_[n-1]),r++),x=n,m+=` +`.concat(I,"+").concat(A," ").concat(Z1),k+=` +`.concat(P,"-").concat(A," ").concat(Q1),r+=2):(m+=k,k="",(H1===1||n===0)&&(m+=` + `.concat(Z1),r++))}if(r>20&&n30)for(n[26]="".concat(N,"...").concat(A);n.length>27;)n.pop();n.length===1?k=$(this,q(b).call(this,"".concat(u," ").concat(n[0]))):k=$(this,q(b).call(this,"".concat(u,` -`).concat(M.join(` +`).concat(n.join(` `),` -`)))}else{var H=Y1(T1),q="",F1=$1[v1];v1==="notDeepEqual"||v1==="notEqual"?(H="".concat($1[v1],` +`)))}else{var i=f(g),p="",l=S[x];x==="notDeepEqual"||x==="notEqual"?(i="".concat(S[x],` -`).concat(H),H.length>1024&&(H="".concat(H.slice(0,1021),"..."))):(q="".concat(Y1(D)),H.length>512&&(H="".concat(H.slice(0,509),"...")),q.length>512&&(q="".concat(q.slice(0,509),"...")),v1==="deepEqual"||v1==="equal"?H="".concat(F1,` +`).concat(i),i.length>1024&&(i="".concat(i.slice(0,1021),"..."))):(p="".concat(f(d)),i.length>512&&(i="".concat(i.slice(0,509),"...")),p.length>512&&(p="".concat(p.slice(0,509),"...")),x==="deepEqual"||x==="equal"?i="".concat(l,` -`).concat(H,` +`).concat(i,` should equal -`):q=" ".concat(v1," ").concat(q)),V=l(this,K(D1).call(this,"".concat(H).concat(q)))}return Error.stackTraceLimit=w1,V.generatedMessage=!q1,Object.defineProperty(c(V),"name",{value:"AssertionError [ERR_ASSERTION]",enumerable:!1,writable:!0,configurable:!0}),V.code="ERR_ASSERTION",V.actual=T1,V.expected=D,V.operator=v1,Error.captureStackTrace&&Error.captureStackTrace(c(V),G1),V.stack,V.name="AssertionError",l(V)}return p(D1,[{key:"toString",value:function(){return"".concat(this.name," [").concat(this.code,"]: ").concat(this.message)}},{key:H1.custom,value:function(M1,V){return H1(this,u({},V,{customInspect:!1,depth:0}))}}]),D1}($(Error));_.exports=B1}}),F=N({"assert/build/assert.js"(X,_){function u(v1){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?u=function(G1){return typeof G1}:u=function(G1){return G1&&typeof Symbol=="function"&&G1.constructor===Symbol&&G1!==Symbol.prototype?"symbol":typeof G1},u(v1)}function n(v1,G1){if(!(v1 instanceof G1))throw new TypeError("Cannot call a class as a function")}var i=z(),U=i.codes,p=U.ERR_AMBIGUOUS_ARGUMENT,l=U.ERR_INVALID_ARG_TYPE,c=U.ERR_INVALID_ARG_VALUE,o=U.ERR_INVALID_RETURN_VALUE,$=U.ERR_MISSING_ARGS,a=I(),t=J,r=t.inspect,s=J.types,K=s.isPromise,e=s.isRegExp,H1=Object.assign,Q1=Object.is,Z1=new Map,W=!1,J1=_.exports=$1,z1={};function X1(v1){throw v1.message instanceof Error?v1.message:new a(v1)}function U1(v1,G1,T1,D,w1){var O1=arguments.length,M;if(O1===0)M="Failed";else if(O1===1)T1=v1,v1=void 0;else{if(W===!1){W=!0;var H=process.emitWarning?process.emitWarning:console.warn.bind(console);H("assert.fail() with more than one argument is deprecated. Please use assert.strictEqual() instead or only pass a message.","DeprecationWarning","DEP0094")}O1===2&&(D="!=")}if(T1 instanceof Error)throw T1;var q={actual:v1,expected:G1,operator:D===void 0?"fail":D,stackStartFn:w1||U1};T1!==void 0&&(q.message=T1);var F1=new a(q);throw M&&(F1.message=M,F1.generatedMessage=!0),F1}J1.fail=U1,J1.AssertionError=a;function Y(v1,G1,T1,D){if(!T1){var w1=!1;if(G1===0)w1=!0,D="No value argument passed to `assert.ok()`";else if(D instanceof Error)throw D;var O1=new a({actual:T1,expected:!0,message:D,operator:"==",stackStartFn:v1});throw O1.generatedMessage=w1,O1}}function $1(){for(var v1=arguments.length,G1=new Array(v1),T1=0;T11?T1-1:0),w1=1;w11?T1-1:0),w1=1;w11?T1-1:0),w1=1;w11?T1-1:0),w1=1;w11?g-1:0),_=1;_1?g-1:0),_=1;_1?g-1:0),_=1;_1?g-1:0),_=1;_{if(L.push({eventType:r,filename:a}),n){const E=n;n=null,E()}}),{async*[Symbol.asyncIterator](){let r=!1;while(!r){while(L.length){let a=L.shift();if(a.eventType==="close"){r=!0;break}if(a.eventType==="error")throw r=!0,a.filename;yield a}await new Promise((a)=>n=a)}}}}var V=Bun.fs(),_="::bunternal::",q={[_]:(i)=>{var S={[_]:function(L,n,r){var a;try{a=i.apply(V,r),r=void 0}catch(E){r=void 0,n(E);return}L(a)}}[_];return async function(...L){return await new Promise((n,r)=>{process.nextTick(S,n,r,L)})}}}[_],k=q(V.accessSync),X=q(V.appendFileSync),l=q(V.closeSync),b=q(V.copyFileSync),R=q(V.existsSync),h=q(V.chownSync),j=q(V.chmodSync),N=q(V.fchmodSync),A=q(V.fchownSync),B=q(V.fstatSync),d=q(V.fsyncSync),P=q(V.ftruncateSync),p=q(V.futimesSync),O=q(V.lchmodSync),o=q(V.lchownSync),K=q(V.linkSync),Z=q(V.lstatSync),C=q(V.mkdirSync),D=q(V.mkdtempSync),y=q(V.openSync),c=q(V.readSync),G=q(V.writeSync),U=q(V.readdirSync),m=q(V.readFileSync),Q=q(V.writeFileSync),H=q(V.readlinkSync),v=q(V.realpathSync),x=q(V.renameSync),F=q(V.statSync),$=q(V.symlinkSync),W=q(V.truncateSync),w=q(V.unlinkSync),t=q(V.utimesSync),Y=q(V.lutimesSync),g=q(V.rmSync),T=q(V.rmdirSync),I=(i,S,L)=>{return new Promise((n,r)=>{try{var a=V.writevSync(i,S,L)}catch(E){r(E);return}n({bytesWritten:a,buffers:S})})},J=(i,S,L)=>{return new Promise((n,r)=>{try{var a=V.readvSync(i,S,L)}catch(E){r(E);return}n({bytesRead:a,buffers:S})})},M={access:k,appendFile:X,close:l,copyFile:b,exists:R,chown:h,chmod:j,fchmod:N,fchown:A,fstat:B,fsync:d,ftruncate:P,futimes:p,lchmod:O,lchown:o,link:K,lstat:Z,mkdir:C,mkdtemp:D,open:y,read:c,write:G,readdir:U,readFile:m,writeFile:Q,readlink:H,realpath:v,rename:x,stat:F,symlink:$,truncate:W,unlink:w,utimes:t,lutimes:Y,rm:g,rmdir:T,watch:z,writev:I,readv:J,constants,[Symbol.for("CommonJS")]:0};export{I as writev,Q as writeFile,G as write,z as watch,t as utimes,w as unlink,W as truncate,$ as symlink,F as stat,T as rmdir,g as rm,x as rename,v as realpath,J as readv,H as readlink,U as readdir,m as readFile,c as read,y as open,D as mkdtemp,C as mkdir,Y as lutimes,Z as lstat,K as link,o as lchown,O as lchmod,p as futimes,P as ftruncate,d as fsync,B as fstat,A as fchown,N as fchmod,R as exists,M as default,b as copyFile,l as close,h as chown,j as chmod,X as appendFile,k as access}; +function J(S,q={}){const z=[];if(S instanceof URL)throw new TypeError("Watch URLs are not supported yet");else if(Buffer.isBuffer(S))S=S.toString();else if(typeof S!=="string")throw new TypeError("Expected path to be a string or Buffer");let A=null;if(typeof q==="string")q={encoding:q};return H.watch(S,q||{},(B,C)=>{if(z.push({eventType:B,filename:C}),A){const D=A;A=null,D()}}),{async*[Symbol.asyncIterator](){let B=!1;while(!B){while(z.length){let C=z.shift();if(C.eventType==="close"){B=!0;break}if(C.eventType==="error")throw B=!0,C.filename;yield C}await new Promise((C)=>A=C)}}}}var H=Bun.fs(),G="::bunternal::",I={[G]:(S)=>{var q={[G]:function(z,A,B){var C;try{C=S.apply(H,B),B=void 0}catch(D){B=void 0,A(D);return}z(C)}}[G];return async function(...z){return await new Promise((A,B)=>{process.nextTick(q,A,B,z)})}}}[G],K=I(H.accessSync),L=I(H.appendFileSync),M=I(H.closeSync),N=I(H.copyFileSync),O=I(H.existsSync),P=I(H.chownSync),Q=I(H.chmodSync),U=I(H.fchmodSync),V=I(H.fchownSync),X=I(H.fstatSync),Y=I(H.fsyncSync),Z=I(H.ftruncateSync),_=I(H.futimesSync),$=I(H.lchmodSync),T=I(H.lchownSync),W=I(H.linkSync),k=I(H.lstatSync),E=I(H.mkdirSync),x=I(H.mkdtempSync),F=I(H.openSync),R=I(H.readSync),g=I(H.writeSync),h=I(H.readdirSync),j=I(H.readFileSync),w=I(H.writeFileSync),b=I(H.readlinkSync),u=I(H.realpathSync),d=I(H.renameSync),c=I(H.statSync),v=I(H.symlinkSync),a=I(H.truncateSync),y=I(H.unlinkSync),l=I(H.utimesSync),p=I(H.lutimesSync),m=I(H.rmSync),n=I(H.rmdirSync),t=(S,q,z)=>{return new Promise((A,B)=>{try{var C=H.writevSync(S,q,z)}catch(D){B(D);return}A({bytesWritten:C,buffers:q})})},o=(S,q,z)=>{return new Promise((A,B)=>{try{var C=H.readvSync(S,q,z)}catch(D){B(D);return}A({bytesRead:C,buffers:q})})},r={access:K,appendFile:L,close:M,copyFile:N,exists:O,chown:P,chmod:Q,fchmod:U,fchown:V,fstat:X,fsync:Y,ftruncate:Z,futimes:_,lchmod:$,lchown:T,link:W,lstat:k,mkdir:E,mkdtemp:x,open:F,read:R,write:g,readdir:h,readFile:j,writeFile:w,readlink:b,realpath:u,rename:d,stat:c,symlink:v,truncate:a,unlink:y,utimes:l,lutimes:p,rm:m,rmdir:n,watch:J,writev:t,readv:o,constants,[Symbol.for("CommonJS")]:0};export{t as writev,w as writeFile,g as write,J as watch,l as utimes,y as unlink,a as truncate,v as symlink,c as stat,n as rmdir,m as rm,d as rename,u as realpath,o as readv,b as readlink,h as readdir,j as readFile,R as read,F as open,x as mkdtemp,E as mkdir,p as lutimes,k as lstat,W as link,T as lchown,$ as lchmod,_ as futimes,Z as ftruncate,Y as fsync,X as fstat,V as fchown,U as fchmod,O as exists,r as default,N as copyFile,M as close,P as chown,Q as chmod,L as appendFile,K as access}; diff --git a/src/js/out/modules/node/http.js b/src/js/out/modules/node/http.js index 0a84f42b7..955c83642 100644 --- a/src/js/out/modules/node/http.js +++ b/src/js/out/modules/node/http.js @@ -1,7 +1,9 @@ import {EventEmitter} from "node:events"; import {Readable, Writable, Duplex} from "node:stream"; import {isTypedArray} from "node:util/types"; -var isIPv6 = function(input) { +var checkInvalidHeaderChar = function(val) { + return RegExpPrototypeExec.call(headerCharRegex, val) !== null; +}, isIPv6 = function(input) { return new RegExp("^((?:(?:[0-9a-fA-F]{1,4}):){7}(?:(?:[0-9a-fA-F]{1,4})|:)|(?:(?:[0-9a-fA-F]{1,4}):){6}(?:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|:(?:[0-9a-fA-F]{1,4})|:)|(?:(?:[0-9a-fA-F]{1,4}):){5}(?::((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(?:[0-9a-fA-F]{1,4})){1,2}|:)|(?:(?:[0-9a-fA-F]{1,4}):){4}(?:(:(?:[0-9a-fA-F]{1,4})){0,1}:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(?:[0-9a-fA-F]{1,4})){1,3}|:)|(?:(?:[0-9a-fA-F]{1,4}):){3}(?:(:(?:[0-9a-fA-F]{1,4})){0,2}:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(?:[0-9a-fA-F]{1,4})){1,4}|:)|(?:(?:[0-9a-fA-F]{1,4}):){2}(?:(:(?:[0-9a-fA-F]{1,4})){0,3}:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(?:[0-9a-fA-F]{1,4})){1,5}|:)|(?:(?:[0-9a-fA-F]{1,4}):){1}(?:(:(?:[0-9a-fA-F]{1,4})){0,4}:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(?:[0-9a-fA-F]{1,4})){1,6}|:)|(?::((?::(?:[0-9a-fA-F]{1,4})){0,5}:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(?::(?:[0-9a-fA-F]{1,4})){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})?$").test(input); }, isValidTLSArray = function(obj) { if (typeof obj === "string" || isTypedArray(obj) || obj instanceof ArrayBuffer || obj instanceof Blob) @@ -97,13 +99,20 @@ function get(url, options, cb) { const req = request(url, options, cb); return req.end(), req; } -var { URL } = globalThis, { newArrayWithSize, String, Object, Array } = globalThis[Symbol.for("Bun.lazy")]("primordials"), globalReportError = globalThis.reportError, setTimeout = globalThis.setTimeout, fetch = Bun.fetch, nop = () => { -}, __DEBUG__ = process.env.__DEBUG__, debug = __DEBUG__ ? (...args) => console.log("node:http", ...args) : nop, kEmptyObject = Object.freeze(Object.create(null)), kOutHeaders = Symbol.for("kOutHeaders"), kEndCalled = Symbol.for("kEndCalled"), kAbortController = Symbol.for("kAbortController"), kClearTimeout = Symbol("kClearTimeout"), kCorked = Symbol.for("kCorked"), searchParamsSymbol = Symbol.for("query"), StringPrototypeSlice = String.prototype.slice, StringPrototypeStartsWith = String.prototype.startsWith, StringPrototypeToUpperCase = String.prototype.toUpperCase, StringPrototypeIncludes = String.prototype.includes, StringPrototypeCharCodeAt = String.prototype.charCodeAt, StringPrototypeIndexOf = String.prototype.indexOf, ArrayIsArray = Array.isArray, RegExpPrototypeExec = RegExp.prototype.exec, ObjectAssign = Object.assign, ObjectPrototypeHasOwnProperty = Object.prototype.hasOwnProperty, INVALID_PATH_REGEX = /[^\u0021-\u00ff]/, NODE_HTTP_WARNING = "WARN: Agent is mostly unused in Bun's implementation of http. If you see strange behavior, this is probably the cause.", _globalAgent, _defaultHTTPSAgent, kInternalRequest = Symbol("kInternalRequest"), kInternalSocketData = Symbol.for("::bunternal::"), kEmptyBuffer = Buffer.alloc(0), FakeSocket = class Socket extends Duplex { +var headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/, validateHeaderName = (name, label) => { + if (typeof name !== "string" || !name || !checkIsHttpToken(name)) + throw new Error("ERR_INVALID_HTTP_TOKEN"); +}, validateHeaderValue = (name, value) => { + if (value === void 0) + throw new Error("ERR_HTTP_INVALID_HEADER_VALUE"); + if (checkInvalidHeaderChar(value)) + throw new Error("ERR_INVALID_CHAR"); +}, { URL } = globalThis, { newArrayWithSize, String, Object, Array } = globalThis[Symbol.for("Bun.lazy")]("primordials"), globalReportError = globalThis.reportError, setTimeout = globalThis.setTimeout, fetch = Bun.fetch, nop = () => { +}, __DEBUG__ = process.env.__DEBUG__, debug = __DEBUG__ ? (...args) => console.log("node:http", ...args) : nop, kEmptyObject = Object.freeze(Object.create(null)), kOutHeaders = Symbol.for("kOutHeaders"), kEndCalled = Symbol.for("kEndCalled"), kAbortController = Symbol.for("kAbortController"), kClearTimeout = Symbol("kClearTimeout"), kCorked = Symbol.for("kCorked"), searchParamsSymbol = Symbol.for("query"), StringPrototypeSlice = String.prototype.slice, StringPrototypeStartsWith = String.prototype.startsWith, StringPrototypeToUpperCase = String.prototype.toUpperCase, StringPrototypeIncludes = String.prototype.includes, StringPrototypeCharCodeAt = String.prototype.charCodeAt, StringPrototypeIndexOf = String.prototype.indexOf, ArrayIsArray = Array.isArray, RegExpPrototypeExec = RegExp.prototype.exec, ObjectAssign = Object.assign, ObjectPrototypeHasOwnProperty = Object.prototype.hasOwnProperty, INVALID_PATH_REGEX = /[^\u0021-\u00ff]/, NODE_HTTP_WARNING = "WARN: Agent is mostly unused in Bun's implementation of http. If you see strange behavior, this is probably the cause.", _defaultHTTPSAgent, kInternalRequest = Symbol("kInternalRequest"), kInternalSocketData = Symbol.for("::bunternal::"), kEmptyBuffer = Buffer.alloc(0), FakeSocket = class Socket extends Duplex { bytesRead = 0; bytesWritten = 0; connecting = !1; remoteAddress = null; - localAddress = "127.0.0.1"; remotePort; timeout = 0; isServer = !1; @@ -183,7 +192,7 @@ class Agent extends EventEmitter { totalSocketCount; #fakeSocket; static get globalAgent() { - return _globalAgent ??= new Agent; + return globalAgent; } static get defaultMaxSockets() { return Infinity; @@ -235,6 +244,7 @@ class Server extends EventEmitter { #tls; #is_tls = !1; listening = !1; + serverName; constructor(options, callback) { super(); if (typeof options === "function") @@ -386,12 +396,14 @@ class Server extends EventEmitter { } } class IncomingMessage extends Readable { + method; + complete; constructor(req, defaultIncomingOpts) { const method = req.method; super(); const url = new URL(req.url); var { type = "request", [kInternalRequest]: nodeReq } = defaultIncomingOpts || {}; - this.#noBody = type === "request" ? method === "GET" || method === "HEAD" || method === "TRACE" || method === "CONNECT" || method === "OPTIONS" || (parseInt(req.headers.get("Content-Length") || "") || 0) === 0 : !1, this.#req = req, this.method = method, this.#type = type, this.complete = !!this.#noBody, this.#bodyStream = null; + this.#noBody = type === "request" ? method === "GET" || method === "HEAD" || method === "TRACE" || method === "CONNECT" || method === "OPTIONS" || (parseInt(req.headers.get("Content-Length") || "") || 0) === 0 : !1, this.#req = req, this.method = method, this.#type = type, this.complete = !!this.#noBody, this.#bodyStream = void 0; const socket = new FakeSocket; socket.remoteAddress = url.hostname, socket.remotePort = url.port, this.#fakeSocket = socket, this.url = url.pathname + url.search, this.#nodeReq = nodeReq, assignHeaders(this, req); } @@ -399,8 +411,8 @@ class IncomingMessage extends Readable { rawHeaders; _consuming = !1; _dumped = !1; - #bodyStream = null; - #fakeSocket = void 0; + #bodyStream; + #fakeSocket; #noBody = !1; #aborted = !1; #req; @@ -422,42 +434,42 @@ class IncomingMessage extends Readable { } callback(); } - #closeBodyStream() { - debug("closeBodyStream()"); - var bodyStream = this.#bodyStream; - if (bodyStream == null) - return; - this.complete = !0, this.#bodyStream = void 0, this.push(null); + async#consumeStream(reader) { + while (!0) { + var { done, value } = await reader.readMany(); + if (this.#aborted) + return; + if (done) { + this.push(null), this.destroy(); + break; + } + for (var v of value) + this.push(v); + } } _read(size) { if (this.#noBody) this.push(null), this.complete = !0; else if (this.#bodyStream == null) { - const contentLength = this.#req.headers.get("content-length"); - let remaining = contentLength ? parseInt(contentLength, 10) : 0; - if (this.#bodyStream = Readable.fromWeb(this.#req.body, { - highWaterMark: Number.isFinite(remaining) ? Math.min(remaining, 16384) : 16384 - }), remaining > 0 && Number.isSafeInteger(remaining)) - this.#bodyStream.on("data", (chunk) => { - if (debug("body size known", remaining), this.push(chunk), remaining -= chunk?.byteLength ?? 0, remaining <= 0) - this.#closeBodyStream(); - }); - else - this.#bodyStream.on("data", (chunk) => { - this.push(chunk); - }); - this.#bodyStream && this.#bodyStream.on("end", () => { - this.#closeBodyStream(); - }); + const reader = this.#req.body?.getReader(); + if (!reader) { + this.push(null); + return; + } + this.#bodyStream = reader, this.#consumeStream(reader); } } get aborted() { return this.#aborted; } - abort() { + #abort() { if (this.#aborted) return; - this.#aborted = !0, this.#closeBodyStream(); + this.#aborted = !0; + var bodyStream = this.#bodyStream; + if (!bodyStream) + return; + bodyStream.cancel(), this.complete = !0, this.#bodyStream = void 0, this.push(null); } get connection() { return this.#fakeSocket; @@ -495,6 +507,9 @@ class IncomingMessage extends Readable { } class OutgoingMessage extends Writable { + constructor() { + super(...arguments); + } #headers; headersSent = !1; sendDate = !0; @@ -758,7 +773,7 @@ class ClientRequest extends OutgoingMessage { #useDefaultPort; #joinDuplicateHeaders; #maxHeaderSize; - #agent = _globalAgent; + #agent = globalAgent; #path; #socketPath; #body = null; @@ -862,14 +877,12 @@ class ClientRequest extends OutgoingMessage { options = ObjectAssign(input || {}, options); var defaultAgent = options._defaultAgent || Agent.globalAgent; let protocol = options.protocol; - if (!protocol) { + if (!protocol) if (options.port === 443) protocol = "https:"; else protocol = defaultAgent.protocol || "http:"; - this.#protocol = protocol; - } - switch (this.#agent?.protocol) { + switch (this.#protocol = protocol, this.#agent?.protocol) { case void 0: break; case "http:": @@ -1055,9 +1068,7 @@ var tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/, METHODS = [ 509: "Bandwidth Limit Exceeded", 510: "Not Extended", 511: "Network Authentication Required" -}; -_globalAgent ??= new Agent; -var defaultObject = { +}, globalAgent = new Agent, defaultObject = { Agent, Server, METHODS, @@ -1068,19 +1079,19 @@ var defaultObject = { request, get, maxHeaderSize: 16384, + validateHeaderName, + validateHeaderValue, setMaxIdleHTTPParsers(max) { debug(`${NODE_HTTP_WARNING}\n`, "setMaxIdleHTTPParsers() is a no-op"); }, - get globalAgent() { - return _globalAgent; - }, - set globalAgent(agent) { - }, + globalAgent, [Symbol.for("CommonJS")]: 0 }, http_default = defaultObject; export { + validateHeaderValue, + validateHeaderName, request, - _globalAgent as globalAgent, + globalAgent, get, http_default as default, createServer, diff --git a/src/js/out/modules/node/https.js b/src/js/out/modules/node/https.js index f6a4e25d0..4fbf284d5 100644 --- a/src/js/out/modules/node/https.js +++ b/src/js/out/modules/node/https.js @@ -1,5 +1,54 @@ -export * from "node:http"; -import {default as default2} from "node:http"; +import * as http from "node:http"; +var request2 = function(input, options, cb) { + if (input && typeof input === "object" && !(input instanceof URL)) + input.protocol ??= "https:"; + else if (typeof options === "object") + options.protocol ??= "https:"; + return http.request(input, options, cb); +}, get = function(input, options, cb) { + const req = request2(input, options, cb); + return req.end(), req; +}, { + Agent, + Server, + METHODS, + STATUS_CODES, + createServer, + ServerResponse, + IncomingMessage, + maxHeaderSize, + validateHeaderName, + validateHeaderValue, + globalAgent +} = http, defaultExport = { + Agent, + Server, + METHODS, + STATUS_CODES, + createServer, + ServerResponse, + IncomingMessage, + request: request2, + get, + maxHeaderSize, + validateHeaderName, + validateHeaderValue, + globalAgent +}; +var https_default = defaultExport; export { - default2 as default + validateHeaderValue, + validateHeaderName, + request2 as request, + maxHeaderSize, + globalAgent, + get, + https_default as default, + createServer, + ServerResponse, + Server, + STATUS_CODES, + METHODS, + IncomingMessage, + Agent }; diff --git a/src/js/private.d.ts b/src/js/private.d.ts index b689c208e..500048dd7 100644 --- a/src/js/private.d.ts +++ b/src/js/private.d.ts @@ -100,6 +100,7 @@ declare module "bun" { var main: string; var tty: Array<{ hasColors: boolean }>; var FFI: any; + var fetch: typeof globalThis.fetch; } declare var Loader: { diff --git a/test/js/node/http/node-http.test.ts b/test/js/node/http/node-http.test.ts index b1910a1f7..3e7da9d34 100644 --- a/test/js/node/http/node-http.test.ts +++ b/test/js/node/http/node-http.test.ts @@ -1,5 +1,14 @@ // @ts-nocheck -import { createServer, request, get, Agent, globalAgent, Server } from "node:http"; +import { + createServer, + request, + get, + Agent, + globalAgent, + Server, + validateHeaderName, + validateHeaderValue, +} from "node:http"; import { createTest } from "node-harness"; const { describe, expect, it, beforeAll, afterAll, createDoneDotAll } = createTest(import.meta.path); @@ -624,4 +633,16 @@ describe("node:http", () => { }); }); }); + + test("validateHeaderName", () => { + validateHeaderName("Foo"); + expect(() => validateHeaderName("foo:")).toThrow(); + expect(() => validateHeaderName("foo:bar")).toThrow(); + }); + + test("validateHeaderValue", () => { + validateHeaderValue("Foo", "Bar"); + expect(() => validateHeaderValue("Foo", undefined as any)).toThrow(); + expect(() => validateHeaderValue("Foo", "Bar\r")).toThrow(); + }); }); -- cgit v1.2.3