diff options
31 files changed, 1762 insertions, 569 deletions
diff --git a/bench/snippets/process-info.mjs b/bench/snippets/process-info.mjs new file mode 100644 index 000000000..0366472e5 --- /dev/null +++ b/bench/snippets/process-info.mjs @@ -0,0 +1,33 @@ +import { bench, run } from "./runner.mjs"; +import { performance } from "perf_hooks"; + +bench("process.memoryUsage()", () => { + process.memoryUsage(); +}); + +bench("process.memoryUsage.rss()", () => { + process.memoryUsage.rss(); +}); + +bench("process.cpuUsage()", () => { + process.cpuUsage(); +}); + +const init = process.cpuUsage(); +bench("process.cpuUsage(delta)", () => { + process.cpuUsage(init); +}); + +bench("performance.now()", () => { + performance.now(); +}); + +bench("process.hrtime()", () => { + process.hrtime(); +}); + +bench("process.hrtime.bigint()", () => { + process.hrtime.bigint(); +}); + +await run(); diff --git a/packages/bun-types/globals.d.ts b/packages/bun-types/globals.d.ts index da412b211..f3f941488 100644 --- a/packages/bun-types/globals.d.ts +++ b/packages/bun-types/globals.d.ts @@ -420,6 +420,32 @@ interface Process { emitWarning(warning: string | Error /*name?: string, ctor?: Function*/): void; readonly config: Object; + + memoryUsage: { + (delta?: MemoryUsageObject): MemoryUsageObject; + + rss(): number; + }; + + cpuUsage(previousValue?: CPUUsageObject): CPUUsageObject; + + /** + * Does nothing in Bun + */ + setSourceMapsEnabled(enabled: boolean): void; +} + +interface MemoryUsageObject { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + arrayBuffers: number; +} + +interface CPUUsageObject { + user: number; + system: number; } declare var process: Process; @@ -1437,8 +1463,8 @@ declare function queueMicrotask(callback: (...args: any[]) => void): void; declare function reportError(error: any): void; interface Timer { - ref(): void; - unref(): void; + ref(): Timer; + unref(): Timer; hasRef(): boolean; [Symbol.toPrimitive](): number; diff --git a/src/bun.js/bindings/BunString.cpp b/src/bun.js/bindings/BunString.cpp index 4c8ff384e..21541d711 100644 --- a/src/bun.js/bindings/BunString.cpp +++ b/src/bun.js/bindings/BunString.cpp @@ -169,6 +169,29 @@ extern "C" JSC::EncodedJSValue BunString__toJS(JSC::JSGlobalObject* globalObject return JSValue::encode(Bun::toJS(globalObject, *bunString)); } +extern "C" BunString BunString__fromUTF16Unitialized(size_t length) +{ + unsigned utf16Length = length; + UChar* ptr; + auto impl = WTF::StringImpl::createUninitialized(utf16Length, ptr); + if (UNLIKELY(!ptr)) + return { BunStringTag::Dead }; + + impl->ref(); + return { BunStringTag::WTFStringImpl, { .wtf = &impl.leakRef() } }; +} + +extern "C" BunString BunString__fromLatin1Unitialized(size_t length) +{ + unsigned latin1Length = length; + LChar* ptr; + auto impl = WTF::StringImpl::createUninitialized(latin1Length, ptr); + if (UNLIKELY(!ptr)) + return { BunStringTag::Dead }; + impl->ref(); + return { BunStringTag::WTFStringImpl, { .wtf = &impl.leakRef() } }; +} + extern "C" BunString BunString__fromUTF8(const char* bytes, size_t length) { if (simdutf::validate_utf8(bytes, length)) { diff --git a/src/bun.js/bindings/CommonJSModuleRecord.cpp b/src/bun.js/bindings/CommonJSModuleRecord.cpp index c7dac89c2..8adba197c 100644 --- a/src/bun.js/bindings/CommonJSModuleRecord.cpp +++ b/src/bun.js/bindings/CommonJSModuleRecord.cpp @@ -817,6 +817,12 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionRequireCommonJS, (JSGlobalObject * lexicalGlo WTF::String specifier = specifierValue.toWTFString(globalObject); RETURN_IF_EXCEPTION(throwScope, {}); + // Special-case for "process" to just return the process object directly. + if (UNLIKELY(specifier == "process"_s || specifier == "node:process"_s)) { + jsDynamicCast<JSCommonJSModule*>(callframe->argument(1))->putDirect(vm, builtinNames(vm).exportsPublicName(), globalObject->processObject(), 0); + return JSValue::encode(globalObject->processObject()); + } + WTF::String referrer = thisObject->id().toWTFString(globalObject); RETURN_IF_EXCEPTION(throwScope, {}); diff --git a/src/bun.js/bindings/Process.cpp b/src/bun.js/bindings/Process.cpp index 1d6b5d33a..7d7bdd982 100644 --- a/src/bun.js/bindings/Process.cpp +++ b/src/bun.js/bindings/Process.cpp @@ -11,13 +11,40 @@ #include <sys/stat.h> #include "ZigConsoleClient.h" #include <JavaScriptCore/GetterSetter.h> +#include <JavaScriptCore/JSSet.h> +#include <JavaScriptCore/LazyProperty.h> +#include <JavaScriptCore/LazyPropertyInlines.h> +#include <JavaScriptCore/VMTrapsInlines.h> + #pragma mark - Node.js Process +#if defined(__APPLE__) +#include <mach/mach.h> +#include <mach/mach_time.h> +#endif + +#if defined(__linux__) +#include <sys/resource.h> +#include <sys/time.h> +#include <sys/stat.h> +#include <fcntl.h> +#endif + +#if !defined(_MSC_VER) +#include <unistd.h> // setuid, getuid +#endif + namespace Zig { using namespace JSC; #define REPORTED_NODE_VERSION "18.15.0" +#define processObjectBindingCodeGenerator processObjectInternalsBindingCodeGenerator +#define processObjectMainModuleCodeGenerator moduleMainCodeGenerator + +#if !defined(BUN_WEBKIT_VERSION) +#define BUN_WEBKIT_VERSION "unknown" +#endif using JSGlobalObject = JSC::JSGlobalObject; using Exception = JSC::Exception; @@ -31,23 +58,20 @@ using JSObject = JSC::JSObject; using JSNonFinalObject = JSC::JSNonFinalObject; namespace JSCastingHelpers = JSC::JSCastingHelpers; -static JSC_DECLARE_CUSTOM_SETTER(Process_setTitle); -static JSC_DECLARE_CUSTOM_GETTER(Process_getArgv); -static JSC_DECLARE_CUSTOM_SETTER(Process_setArgv); -static JSC_DECLARE_CUSTOM_GETTER(Process_getTitle); -static JSC_DECLARE_CUSTOM_GETTER(Process_getVersionsLazy); -static JSC_DECLARE_CUSTOM_SETTER(Process_setVersionsLazy); - -static JSC_DECLARE_CUSTOM_GETTER(Process_getPID); -static JSC_DECLARE_CUSTOM_GETTER(Process_getPPID); - -static JSC_DECLARE_HOST_FUNCTION(Process_functionCwd); +JSC_DECLARE_CUSTOM_SETTER(Process_setTitle); +JSC_DECLARE_CUSTOM_GETTER(Process_getArgv); +JSC_DECLARE_CUSTOM_SETTER(Process_setArgv); +JSC_DECLARE_CUSTOM_GETTER(Process_getTitle); +JSC_DECLARE_CUSTOM_GETTER(Process_getPID); +JSC_DECLARE_CUSTOM_GETTER(Process_getPPID); +JSC_DECLARE_HOST_FUNCTION(Process_functionCwd); static bool processIsExiting = false; extern "C" uint8_t Bun__getExitCode(void*); extern "C" uint8_t Bun__setExitCode(void*, uint8_t); extern "C" void* Bun__getVM(); extern "C" Zig::GlobalObject* Bun__getDefaultGlobal(); +extern "C" const char* Bun__githubURL; static void dispatchExitInternal(JSC::JSGlobalObject* globalObject, Process* process, int exitCode) { @@ -72,107 +96,6 @@ static void dispatchExitInternal(JSC::JSGlobalObject* globalObject, Process* pro emitter.emit(event, arguments); } -static JSValue constructStdioWriteStream(JSC::JSGlobalObject* globalObject, int fd) -{ - auto& vm = globalObject->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - auto* thisObject = reinterpret_cast<Zig::GlobalObject*>(globalObject); - JSC::JSFunction* getStdioWriteStream = JSC::JSFunction::create(vm, processObjectInternalsGetStdioWriteStreamCodeGenerator(vm), globalObject); - JSC::MarkedArgumentBuffer args; - WTF::String process = WTF::String("node:process"_s); - JSC::JSValue requireFunction = Zig::ImportMetaObject::createRequireFunction( - vm, - globalObject, - process); - - args.append(JSC::jsNumber(fd)); - args.append(requireFunction); - - auto clientData = WebCore::clientData(vm); - JSC::CallData callData = JSC::getCallData(getStdioWriteStream); - - NakedPtr<JSC::Exception> returnedException = nullptr; - auto result = JSC::call(globalObject, getStdioWriteStream, callData, globalObject->globalThis(), args, returnedException); - RETURN_IF_EXCEPTION(scope, {}); - - if (returnedException) { - throwException(globalObject, scope, returnedException.get()); - return {}; - } - - return result; -} - -JSC_DEFINE_CUSTOM_GETTER( - Process_lazyStdinGetter, - (JSGlobalObject * globalObject, EncodedJSValue thisValue, PropertyName property)) -{ - auto& vm = globalObject->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - JSC::JSValue value = JSC::JSValue::decode(thisValue); - if (!value || value.isUndefinedOrNull() || !value.isObject()) - return JSValue::encode(jsUndefined()); - - auto* thisObject = reinterpret_cast<Zig::GlobalObject*>(globalObject); - JSC::JSFunction* getStdioWriteStream = JSC::JSFunction::create(vm, processObjectInternalsGetStdinStreamCodeGenerator(vm), globalObject); - JSC::MarkedArgumentBuffer args; - WTF::String process = WTF::String("node:process"_s); - JSC::JSValue requireFunction = Zig::ImportMetaObject::createRequireFunction( - vm, - globalObject, - process); - - args.append(JSC::jsNumber(STDIN_FILENO)); - args.append(requireFunction); - args.append(thisObject->get(globalObject, PropertyName(JSC::Identifier::fromString(vm, "Bun"_s)))); - - auto clientData = WebCore::clientData(vm); - JSC::CallData callData = JSC::getCallData(getStdioWriteStream); - - NakedPtr<JSC::Exception> returnedException = nullptr; - auto result = JSC::call(globalObject, getStdioWriteStream, callData, globalObject->globalThis(), args, returnedException); - RETURN_IF_EXCEPTION(scope, {}); - - if (UNLIKELY(returnedException)) { - throwException(globalObject, scope, returnedException.get()); - return {}; - } - - if (LIKELY(result)) - value.getObject()->putDirect(vm, property, result, 0); - - return JSValue::encode(result); -} - -JSC_DEFINE_CUSTOM_GETTER( - Process_lazyStdoutGetter, - (JSGlobalObject * globalObject, EncodedJSValue thisValue, PropertyName property)) -{ - JSValue value = JSValue::decode(thisValue); - auto& vm = globalObject->vm(); - JSC::JSObject* thisObject = value.toObject(globalObject); - JSC::JSValue stream = constructStdioWriteStream(globalObject, 1); - - if (stream) - thisObject->putDirect(vm, property, stream, 0); - - return JSValue::encode(stream); -} - -JSC_DEFINE_CUSTOM_GETTER( - Process_lazyStderrGetter, (JSGlobalObject * globalObject, EncodedJSValue thisValue, PropertyName property)) -{ - JSValue value = JSValue::decode(thisValue); - auto& vm = globalObject->vm(); - JSC::JSObject* thisObject = value.toObject(globalObject); - JSC::JSValue stream = constructStdioWriteStream(globalObject, 2); - - if (stream) - thisObject->putDirect(vm, property, stream, 0); - - return JSValue::encode(stream); -} - JSC_DEFINE_CUSTOM_SETTER(Process_defaultSetter, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::EncodedJSValue value, JSC::PropertyName propertyName)) @@ -420,6 +343,7 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionExit, Process__dispatchOnExit(zigGlobal, exitCode); Bun__Process__exit(zigGlobal, exitCode); + __builtin_unreachable(); } extern "C" uint64_t Bun__readOriginTimer(void*); @@ -427,9 +351,12 @@ extern "C" uint64_t Bun__readOriginTimer(void*); JSC_DEFINE_HOST_FUNCTION(Process_functionHRTime, (JSC::JSGlobalObject * globalObject_, JSC::CallFrame* callFrame)) { + Zig::GlobalObject* globalObject = reinterpret_cast<Zig::GlobalObject*>(globalObject_); auto& vm = globalObject->vm(); + auto throwScope = DECLARE_THROW_SCOPE(vm); + uint64_t time = Bun__readOriginTimer(globalObject->bunVM()); int64_t seconds = static_cast<int64_t>(time / 1000000000); int64_t nanoseconds = time % 1000000000; @@ -438,7 +365,6 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionHRTime, JSC::JSValue arg0 = callFrame->uncheckedArgument(0); if (!arg0.isUndefinedOrNull()) { JSArray* relativeArray = JSC::jsDynamicCast<JSC::JSArray*>(arg0); - auto throwScope = DECLARE_THROW_SCOPE(vm); if ((!relativeArray && !arg0.isUndefinedOrNull()) || relativeArray->length() < 2) { JSC::throwTypeError(globalObject, throwScope, "hrtime() argument must be an array or undefined"_s); return JSC::JSValue::encode(JSC::JSValue {}); @@ -458,14 +384,28 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionHRTime, seconds--; nanoseconds += 1000000000; } - throwScope.release(); } } - auto* array = JSArray::create(vm, globalObject->originalArrayStructureForIndexingType(ArrayWithContiguous), 2); - array->setIndexQuickly(vm, 0, JSC::jsNumber(seconds)); - array->setIndexQuickly(vm, 1, JSC::jsNumber(nanoseconds)); - return JSC::JSValue::encode(JSC::JSValue(array)); + JSC::JSArray* array = nullptr; + { + JSC::ObjectInitializationScope initializationScope(vm); + if ((array = JSC::JSArray::tryCreateUninitializedRestricted( + initializationScope, nullptr, + globalObject->arrayStructureForIndexingTypeDuringAllocation(JSC::ArrayWithContiguous), + 2))) { + + array->initializeIndex(initializationScope, 0, JSC::jsNumber(seconds)); + array->initializeIndex(initializationScope, 1, JSC::jsNumber(nanoseconds)); + } + } + + if (UNLIKELY(!array)) { + JSC::throwOutOfMemoryError(globalObject, throwScope); + return JSC::JSValue::encode(JSC::JSValue {}); + } + + RELEASE_AND_RETURN(throwScope, JSC::JSValue::encode(array)); } JSC_DEFINE_HOST_FUNCTION(Process_functionHRTimeBigInt, @@ -497,34 +437,6 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionChdir, return JSC::JSValue::encode(result); } -extern "C" const char* Bun__githubURL; - -JSC_DEFINE_CUSTOM_GETTER(Process_getterRelease, (JSGlobalObject * globalObject, EncodedJSValue thisValue, PropertyName)) -{ - auto& vm = globalObject->vm(); - - auto* release = JSC::constructEmptyObject(globalObject); - release->putDirect(vm, Identifier::fromString(vm, "name"_s), jsString(vm, WTF::String("bun"_s)), 0); - release->putDirect(vm, Identifier::fromString(vm, "lts"_s), jsBoolean(false), 0); - release->putDirect(vm, Identifier::fromString(vm, "sourceUrl"_s), jsString(vm, WTF::String(Bun__githubURL, strlen(Bun__githubURL))), 0); - release->putDirect(vm, Identifier::fromString(vm, "headersUrl"_s), jsEmptyString(vm), 0); - release->putDirect(vm, Identifier::fromString(vm, "libUrl"_s), jsEmptyString(vm), 0); - - return JSValue::encode(release); -} - -JSC_DEFINE_CUSTOM_SETTER(Process_setterRelease, - (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, - JSC::EncodedJSValue value, JSC::PropertyName)) -{ - JSC::VM& vm = globalObject->vm(); - - JSC::JSObject* thisObject = JSC::jsDynamicCast<JSC::JSObject*>(JSValue::decode(thisValue)); - thisObject->putDirect(vm, JSC::Identifier::fromString(vm, "release"_s), JSValue::decode(value), 0); - - return true; -} - // static const NeverDestroyed<String> signalNames[] = { // MAKE_STATIC_STRING_IMPL("SIGHUP"), // MAKE_STATIC_STRING_IMPL("SIGINT"), @@ -660,31 +572,7 @@ JSC_DEFINE_HOST_FUNCTION(Process_emitWarning, (JSGlobalObject * lexicalGlobalObj return JSValue::encode(jsUndefined()); } -JSC_DEFINE_CUSTOM_GETTER(Process_lazyArgv0Getter, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName name)) -{ - JSC::JSObject* thisObject = JSValue::decode(thisValue).getObject(); - EncodedJSValue ret = Bun__Process__getArgv0(globalObject); - - if (LIKELY(thisObject)) { - thisObject->putDirect(globalObject->vm(), name, JSValue::decode(ret), 0); - } - - return ret; -} - -JSC_DEFINE_CUSTOM_GETTER(Process_lazyExecArgvGetter, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName name)) -{ - JSC::JSObject* thisObject = JSValue::decode(thisValue).getObject(); - EncodedJSValue ret = Bun__Process__getExecArgv(globalObject); - - if (LIKELY(thisObject)) { - thisObject->putDirect(globalObject->vm(), name, JSValue::decode(ret), 0); - } - - return ret; -} - -JSC_DEFINE_CUSTOM_GETTER(Process__getExitCode, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName name)) +JSC_DEFINE_CUSTOM_GETTER(processExitCode, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName name)) { Process* process = jsDynamicCast<Process*>(JSValue::decode(thisValue)); if (!process) { @@ -693,7 +581,7 @@ JSC_DEFINE_CUSTOM_GETTER(Process__getExitCode, (JSC::JSGlobalObject * lexicalGlo return JSValue::encode(jsNumber(Bun__getExitCode(jsCast<Zig::GlobalObject*>(process->globalObject())->bunVM()))); } -JSC_DEFINE_CUSTOM_SETTER(Process__setExitCode, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, JSC::EncodedJSValue value, JSC::PropertyName)) +JSC_DEFINE_CUSTOM_SETTER(setProcessExitCode, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, JSC::EncodedJSValue value, JSC::PropertyName)) { Process* process = jsDynamicCast<Process*>(JSValue::decode(thisValue)); if (!process) { @@ -724,158 +612,56 @@ JSC_DEFINE_CUSTOM_SETTER(Process__setExitCode, (JSC::JSGlobalObject * lexicalGlo return true; } -JSC_DEFINE_CUSTOM_GETTER(Process_lazyExecPathGetter, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName name)) +static JSValue constructVersions(VM& vm, JSObject* processObject) { - JSC::JSObject* thisObject = JSValue::decode(thisValue).getObject(); - EncodedJSValue ret = Bun__Process__getExecPath(globalObject); - - if (LIKELY(thisObject)) { - thisObject->putDirect(globalObject->vm(), name, JSValue::decode(ret), 0); - } - - return ret; -} - -void Process::finishCreation(JSC::VM& vm) -{ - Base::finishCreation(vm); - auto clientData = WebCore::clientData(vm); - auto* globalObject = reinterpret_cast<Zig::GlobalObject*>(this->globalObject()); - - putDirectCustomAccessor(vm, clientData->builtinNames().pidPublicName(), - JSC::CustomGetterSetter::create(vm, Process_getPID, nullptr), - static_cast<unsigned>(JSC::PropertyAttribute::CustomValue)); - - putDirectCustomAccessor(vm, clientData->builtinNames().ppidPublicName(), - JSC::CustomGetterSetter::create(vm, Process_getPPID, nullptr), - static_cast<unsigned>(JSC::PropertyAttribute::CustomValue)); - - putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "title"_s), - JSC::CustomGetterSetter::create(vm, Process_getTitle, Process_setTitle), - static_cast<unsigned>(JSC::PropertyAttribute::CustomValue)); - - putDirectCustomAccessor(vm, clientData->builtinNames().argvPublicName(), - JSC::CustomGetterSetter::create(vm, Process_getArgv, Process_setArgv), - static_cast<unsigned>(JSC::PropertyAttribute::CustomValue)); - - putDirect(vm, JSC::Identifier::fromString(vm, "revision"_s), - JSC::jsString(vm, makeAtomString(Bun__version_sha)), 0); - - this->putDirect(vm, clientData->builtinNames().nextTickPublicName(), - JSC::JSFunction::create(vm, globalObject, 1, - MAKE_STATIC_STRING_IMPL("nextTick"), Process_functionNextTick, ImplementationVisibility::Public), - PropertyAttribute::Function | 0); - - this->putDirect(vm, JSC::Identifier::fromString(vm, "dlopen"_s), - JSC::JSFunction::create(vm, globalObject, 1, - MAKE_STATIC_STRING_IMPL("dlopen"), Process_functionDlopen, ImplementationVisibility::Public), - PropertyAttribute::Function | 0); - - this->putDirect(vm, clientData->builtinNames().cwdPublicName(), - JSC::JSFunction::create(vm, globalObject, 0, - MAKE_STATIC_STRING_IMPL("cwd"), Process_functionCwd, ImplementationVisibility::Public), - PropertyAttribute::Function | 0); - - this->putDirect(vm, clientData->builtinNames().chdirPublicName(), - JSC::JSFunction::create(vm, globalObject, 0, - MAKE_STATIC_STRING_IMPL("chdir"), Process_functionChdir, ImplementationVisibility::Public), - PropertyAttribute::Function | 0); - - this->putDirect(vm, JSC::Identifier::fromString(vm, "exit"_s), - JSC::JSFunction::create(vm, globalObject, 0, - MAKE_STATIC_STRING_IMPL("exit"), Process_functionExit, ImplementationVisibility::Public), - PropertyAttribute::Function | 0); - - putDirectCustomAccessor( - vm, clientData->builtinNames().versionsPublicName(), - JSC::CustomGetterSetter::create(vm, Process_getVersionsLazy, Process_setVersionsLazy), 0); - // this should be transpiled out, but just incase - this->putDirect(vm, JSC::Identifier::fromString(vm, "browser"_s), - JSC::JSValue(false), PropertyAttribute::DontEnum | 0); - - this->putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "exitCode"_s), - JSC::CustomGetterSetter::create(vm, - Process__getExitCode, - Process__setExitCode), - 0); - - this->putDirect(vm, clientData->builtinNames().versionPublicName(), - JSC::jsString(vm, makeString("v", REPORTED_NODE_VERSION))); - - // this gives some way of identifying at runtime whether the SSR is happening in node or not. - // this should probably be renamed to what the name of the bundler is, instead of "notNodeJS" - // but it must be something that won't evaluate to truthy in Node.js - this->putDirect(vm, JSC::Identifier::fromString(vm, "isBun"_s), JSC::JSValue(true)); -#if defined(__APPLE__) - this->putDirect(vm, JSC::Identifier::fromString(vm, "platform"_s), - JSC::jsString(vm, makeAtomString("darwin"))); -#else - this->putDirect(vm, JSC::Identifier::fromString(vm, "platform"_s), - JSC::jsString(vm, makeAtomString("linux"))); -#endif - -#if defined(__x86_64__) - this->putDirect(vm, JSC::Identifier::fromString(vm, "arch"_s), - JSC::jsString(vm, makeAtomString("x64"))); -#elif defined(__i386__) - this->putDirect(vm, JSC::Identifier::fromString(vm, "arch"_s), - JSC::jsString(vm, makeAtomString("x86"))); -#elif defined(__arm__) - this->putDirect(vm, JSC::Identifier::fromString(vm, "arch"_s), - JSC::jsString(vm, makeAtomString("arm"))); -#elif defined(__aarch64__) - this->putDirect(vm, JSC::Identifier::fromString(vm, "arch"_s), - JSC::jsString(vm, makeAtomString("arm64"))); -#endif - - JSC::JSFunction* hrtime = JSC::JSFunction::create(vm, globalObject, 0, - MAKE_STATIC_STRING_IMPL("hrtime"), Process_functionHRTime, ImplementationVisibility::Public); - - JSC::JSFunction* hrtimeBigInt = JSC::JSFunction::create(vm, globalObject, 0, - MAKE_STATIC_STRING_IMPL("bigint"), Process_functionHRTimeBigInt, ImplementationVisibility::Public); - - hrtime->putDirect(vm, JSC::Identifier::fromString(vm, "bigint"_s), hrtimeBigInt); - this->putDirect(vm, JSC::Identifier::fromString(vm, "hrtime"_s), hrtime); - - this->putDirectCustomAccessor(vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "release"_s)), - JSC::CustomGetterSetter::create(vm, Process_getterRelease, Process_setterRelease), 0); - - this->putDirectCustomAccessor(vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "stdout"_s)), - JSC::CustomGetterSetter::create(vm, Process_lazyStdoutGetter, Process_defaultSetter), 0); - - this->putDirectCustomAccessor(vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "stderr"_s)), - JSC::CustomGetterSetter::create(vm, Process_lazyStderrGetter, Process_defaultSetter), 0); - - this->putDirectCustomAccessor(vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "stdin"_s)), - JSC::CustomGetterSetter::create(vm, Process_lazyStdinGetter, Process_defaultSetter), 0); - - this->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "abort"_s), - 0, Process_functionAbort, ImplementationVisibility::Public, NoIntrinsic, 0); - - this->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "abort"_s), - 0, Process_functionAbort, ImplementationVisibility::Public, NoIntrinsic, 0); - - this->putDirectCustomAccessor(vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "argv0"_s)), - JSC::CustomGetterSetter::create(vm, Process_lazyArgv0Getter, Process_defaultSetter), 0); - - this->putDirectCustomAccessor(vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "execPath"_s)), - JSC::CustomGetterSetter::create(vm, Process_lazyExecPathGetter, Process_defaultSetter), 0); - - this->putDirectCustomAccessor(vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "execArgv"_s)), - JSC::CustomGetterSetter::create(vm, Process_lazyExecArgvGetter, Process_defaultSetter), 0); + auto* globalObject = processObject->globalObject(); + JSC::JSObject* object = JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), 19); - this->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "uptime"_s), - 0, Process_functionUptime, ImplementationVisibility::Public, NoIntrinsic, 0); + object->putDirect(vm, JSC::Identifier::fromString(vm, "node"_s), + JSC::JSValue(JSC::jsOwnedString(vm, makeAtomString(REPORTED_NODE_VERSION)))); + object->putDirect( + vm, JSC::Identifier::fromString(vm, "bun"_s), + JSC::JSValue(JSC::jsOwnedString(vm, makeAtomString(Bun__version + 1 /* prefix with v */)))); + object->putDirect(vm, JSC::Identifier::fromString(vm, "webkit"_s), + JSC::JSValue(JSC::jsOwnedString(vm, makeAtomString(BUN_WEBKIT_VERSION)))); + object->putDirect(vm, JSC::Identifier::fromString(vm, "boringssl"_s), + JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_boringssl))), 0); + object->putDirect(vm, JSC::Identifier::fromString(vm, "libarchive"_s), + JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_libarchive))), 0); + object->putDirect(vm, JSC::Identifier::fromString(vm, "mimalloc"_s), + JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_mimalloc))), 0); + object->putDirect(vm, JSC::Identifier::fromString(vm, "picohttpparser"_s), + JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_picohttpparser))), 0); + object->putDirect(vm, JSC::Identifier::fromString(vm, "uwebsockets"_s), + JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_uws))), 0); + object->putDirect(vm, JSC::Identifier::fromString(vm, "webkit"_s), + JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_webkit))), 0); + object->putDirect(vm, JSC::Identifier::fromString(vm, "zig"_s), + JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_zig))), 0); + object->putDirect(vm, JSC::Identifier::fromString(vm, "zlib"_s), + JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_zlib))), 0); + object->putDirect(vm, JSC::Identifier::fromString(vm, "tinycc"_s), + JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_tinycc))), 0); + object->putDirect(vm, JSC::Identifier::fromString(vm, "lolhtml"_s), + JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_lolhtml))), 0); + object->putDirect(vm, JSC::Identifier::fromString(vm, "ares"_s), + JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_c_ares))), 0); + object->putDirect(vm, JSC::Identifier::fromString(vm, "usockets"_s), + JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_usockets))), 0); - this->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "umask"_s), - 1, Process_functionUmask, ImplementationVisibility::Public, NoIntrinsic, 0); + object->putDirect(vm, JSC::Identifier::fromString(vm, "v8"_s), JSValue(JSC::jsString(vm, makeString("10.8.168.20-node.8"_s))), 0); + object->putDirect(vm, JSC::Identifier::fromString(vm, "uv"_s), JSValue(JSC::jsString(vm, makeString("1.44.2"_s))), 0); + object->putDirect(vm, JSC::Identifier::fromString(vm, "napi"_s), JSValue(JSC::jsString(vm, makeString("8"_s))), 0); - this->putDirectBuiltinFunction(vm, globalObject, JSC::Identifier::fromString(vm, "binding"_s), - processObjectInternalsBindingCodeGenerator(vm), - 0); + object->putDirect(vm, JSC::Identifier::fromString(vm, "modules"_s), + JSC::JSValue(JSC::jsString(vm, makeAtomString("108")))); - this->putDirect(vm, vm.propertyNames->toStringTagSymbol, jsString(vm, String("process"_s)), 0); + return object; +} +static JSValue constructProcessConfigObject(VM& vm, JSObject* processObject) +{ + auto* globalObject = processObject->globalObject(); // target_defaults: // { cflags: [], // default_configuration: 'Release', @@ -905,179 +691,779 @@ void Process::finishCreation(JSC::VM& vm) JSC::jsNumber(1), 0); config->putDirect(vm, JSC::Identifier::fromString(vm, "target_defaults"_s), JSC::constructEmptyObject(globalObject), 0); config->putDirect(vm, JSC::Identifier::fromString(vm, "variables"_s), variables, 0); - this->putDirect(vm, JSC::Identifier::fromString(vm, "config"_s), config, 0); - this->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "emitWarning"_s), - 1, Process_emitWarning, ImplementationVisibility::Public, NoIntrinsic, 0); + return config; +} + +static JSValue constructProcessReleaseObject(VM& vm, JSObject* processObject) +{ + auto* globalObject = processObject->globalObject(); + auto* release = JSC::constructEmptyObject(globalObject); + release->putDirect(vm, Identifier::fromString(vm, "name"_s), jsString(vm, WTF::String("bun"_s)), 0); + release->putDirect(vm, Identifier::fromString(vm, "lts"_s), jsBoolean(false), 0); + release->putDirect(vm, Identifier::fromString(vm, "sourceUrl"_s), jsString(vm, WTF::String(Bun__githubURL, strlen(Bun__githubURL))), 0); + release->putDirect(vm, Identifier::fromString(vm, "headersUrl"_s), jsEmptyString(vm), 0); + release->putDirect(vm, Identifier::fromString(vm, "libUrl"_s), jsEmptyString(vm), 0); + + return release; +} + +static JSValue constructProcessHrtimeObject(VM& vm, JSObject* processObject) +{ + auto* globalObject = processObject->globalObject(); + JSC::JSFunction* hrtime = JSC::JSFunction::create(vm, globalObject, 0, + String("hrtime"_s), Process_functionHRTime, ImplementationVisibility::Public); + + JSC::JSFunction* hrtimeBigInt = JSC::JSFunction::create(vm, globalObject, 0, + String("bigint"_s), Process_functionHRTimeBigInt, ImplementationVisibility::Public); + + hrtime->putDirect(vm, JSC::Identifier::fromString(vm, "bigint"_s), hrtimeBigInt); + + return hrtime; +} + +static JSValue constructStdioWriteStream(JSC::JSGlobalObject* globalObject, int fd) +{ + auto& vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + JSC::JSFunction* getStdioWriteStream = JSC::JSFunction::create(vm, processObjectInternalsGetStdioWriteStreamCodeGenerator(vm), globalObject); + JSC::MarkedArgumentBuffer args; + args.append(JSC::jsNumber(fd)); + + auto clientData = WebCore::clientData(vm); + JSC::CallData callData = JSC::getCallData(getStdioWriteStream); + + NakedPtr<JSC::Exception> returnedException = nullptr; + auto result = JSC::call(globalObject, getStdioWriteStream, callData, globalObject->globalThis(), args, returnedException); + RETURN_IF_EXCEPTION(scope, {}); + + if (returnedException) { + throwException(globalObject, scope, returnedException.get()); + return {}; + } + + return result; +} + +static JSValue constructStdout(VM& vm, JSObject* processObject) +{ + auto* globalObject = Bun__getDefaultGlobal(); + return constructStdioWriteStream(globalObject, 1); +} + +static JSValue constructStderr(VM& vm, JSObject* processObject) +{ + auto* globalObject = Bun__getDefaultGlobal(); + return constructStdioWriteStream(globalObject, 2); +} + +static JSValue constructStdin(VM& vm, JSObject* processObject) +{ + auto* globalObject = Bun__getDefaultGlobal(); + auto scope = DECLARE_THROW_SCOPE(vm); + auto* thisObject = reinterpret_cast<Zig::GlobalObject*>(globalObject); + JSC::JSFunction* getStdioWriteStream = JSC::JSFunction::create(vm, processObjectInternalsGetStdinStreamCodeGenerator(vm), globalObject); + JSC::MarkedArgumentBuffer args; + args.append(JSC::jsNumber(STDIN_FILENO)); + + auto clientData = WebCore::clientData(vm); + JSC::CallData callData = JSC::getCallData(getStdioWriteStream); + + NakedPtr<JSC::Exception> returnedException = nullptr; + auto result = JSC::call(globalObject, getStdioWriteStream, callData, globalObject, args, returnedException); + RETURN_IF_EXCEPTION(scope, {}); + + if (UNLIKELY(returnedException)) { + throwException(globalObject, scope, returnedException.get()); + return {}; + } + + RELEASE_AND_RETURN(scope, result); +} + +static JSValue constructPid(VM& vm, JSObject* processObject) +{ + return jsNumber(getpid()); +} + +static JSValue constructPpid(VM& vm, JSObject* processObject) +{ + return jsNumber(getppid()); +} + +static JSValue constructArgv0(VM& vm, JSObject* processObject) +{ + auto* globalObject = processObject->globalObject(); + return JSValue::decode(Bun__Process__getArgv0(globalObject)); +} + +static JSValue constructExecArgv(VM& vm, JSObject* processObject) +{ + auto* globalObject = processObject->globalObject(); + return JSValue::decode(Bun__Process__getExecArgv(globalObject)); +} + +static JSValue constructExecPath(VM& vm, JSObject* processObject) +{ + auto* globalObject = processObject->globalObject(); + return JSValue::decode(Bun__Process__getExecPath(globalObject)); +} + +static JSValue constructArgv(VM& vm, JSObject* processObject) +{ + auto* globalObject = processObject->globalObject(); + return JSValue::decode(Bun__Process__getArgv(globalObject)); +} + +static JSValue constructArch(VM& vm, JSObject* processObject) +{ +#if defined(__x86_64__) + return JSC::jsString(vm, makeAtomString("x64")); +#elif defined(__i386__) + return JSC::jsString(vm, makeAtomString("x86")); +#elif defined(__arm__) + return JSC::jsString(vm, makeAtomString("arm")); +#elif defined(__aarch64__) + return JSC::jsString(vm, makeAtomString("arm64")); +#else +#error "Unknown architecture" +#endif +} - JSC::JSFunction* requireDotMainFunction = JSFunction::create( +static JSValue constructPlatform(VM& vm, JSObject* processObject) +{ +#if defined(__APPLE__) + return JSC::jsString(vm, makeAtomString("darwin")); +#elif defined(__linux__) + return JSC::jsString(vm, makeAtomString("linux")); +#else +#error "Unknown platform" +#endif +} + +static JSValue constructBrowser(VM& vm, JSObject* processObject) +{ + return jsBoolean(false); +} + +static JSValue constructVersion(VM& vm, JSObject* processObject) +{ + return JSC::jsString(vm, makeString("v", REPORTED_NODE_VERSION)); +} + +static JSValue constructIsBun(VM& vm, JSObject* processObject) +{ + return jsBoolean(true); +} + +static JSValue constructRevision(VM& vm, JSObject* processObject) +{ + return JSC::jsString(vm, makeAtomString(Bun__version_sha)); +} + +static JSValue constructEnv(VM& vm, JSObject* processObject) +{ + auto* globalObject = jsCast<Zig::GlobalObject*>(processObject->globalObject()); + return globalObject->processEnvObject(); +} + +JSC_DEFINE_HOST_FUNCTION(Process_functiongetuid, (JSGlobalObject * globalObject, CallFrame* callFrame)) +{ + return JSValue::encode(jsNumber(getuid())); +} + +JSC_DEFINE_HOST_FUNCTION(Process_functiongeteuid, (JSGlobalObject * globalObject, CallFrame* callFrame)) +{ + return JSValue::encode(jsNumber(geteuid())); +} + +JSC_DEFINE_HOST_FUNCTION(Process_functiongetegid, (JSGlobalObject * globalObject, CallFrame* callFrame)) +{ + return JSValue::encode(jsNumber(getegid())); +} + +JSC_DEFINE_HOST_FUNCTION(Process_functiongetgid, (JSGlobalObject * globalObject, CallFrame* callFrame)) +{ + return JSValue::encode(jsNumber(getgid())); +} + +JSC_DEFINE_HOST_FUNCTION(Process_functiongetgroups, (JSGlobalObject * globalObject, CallFrame* callFrame)) +{ + auto& vm = globalObject->vm(); + int ngroups = getgroups(0, nullptr); + auto throwScope = DECLARE_THROW_SCOPE(vm); + if (ngroups == -1) { + SystemError error; + error.errno_ = errno; + error.syscall = Bun::toString("getgroups"_s); + throwException(globalObject, throwScope, JSValue::decode(SystemError__toErrorInstance(&error, globalObject))); + return JSValue::encode(jsUndefined()); + } + + gid_t egid = getegid(); + JSArray* groups = constructEmptyArray(globalObject, nullptr, static_cast<unsigned int>(ngroups)); + Vector<gid_t> groupVector(ngroups); + getgroups(1, &egid); + bool needsEgid = true; + for (unsigned i = 0; i < ngroups; i++) { + auto current = groupVector[i]; + if (current == needsEgid) { + needsEgid = false; + } + + groups->putDirectIndex(globalObject, i, jsNumber(current)); + } + + if (needsEgid) + groups->push(globalObject, jsNumber(egid)); + + return JSValue::encode(groups); +} + +JSC_DEFINE_HOST_FUNCTION(Process_functionAssert, (JSGlobalObject * globalObject, CallFrame* callFrame)) +{ + auto& vm = globalObject->vm(); + auto throwScope = DECLARE_THROW_SCOPE(vm); + + JSValue arg0 = callFrame->argument(0); + bool condition = arg0.toBoolean(globalObject); + RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined())); + if (condition) { + return JSValue::encode(jsUndefined()); + } + + JSValue arg1 = callFrame->argument(1); + String message = arg1.isUndefined() ? String() : arg1.toWTFString(globalObject); + RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined())); + auto error = createError(globalObject, makeString("Assertion failed: "_s, message)); + error->putDirect(vm, Identifier::fromString(vm, "code"_s), jsString(vm, makeString("ERR_ASSERTION"_s))); + throwException(globalObject, throwScope, error); + return JSValue::encode(jsUndefined()); +} + +JSC_DEFINE_HOST_FUNCTION(Process_functionReallyExit, (JSGlobalObject * globalObject, CallFrame* callFrame)) +{ + auto& vm = globalObject->vm(); + auto throwScope = DECLARE_THROW_SCOPE(vm); + uint8_t exitCode = 0; + JSValue arg0 = callFrame->argument(0); + if (arg0.isNumber()) { + if (!arg0.isInt32()) { + throwRangeError(globalObject, throwScope, "The \"code\" argument must be an integer"_s); + return JSC::JSValue::encode(JSC::JSValue {}); + } + + int extiCode32 = arg0.toInt32(globalObject); + RETURN_IF_EXCEPTION(throwScope, JSC::JSValue::encode(JSC::JSValue {})); + + if (extiCode32 < 0 || extiCode32 > 127) { + throwRangeError(globalObject, throwScope, "The \"code\" argument must be an integer between 0 and 127"_s); + return JSC::JSValue::encode(JSC::JSValue {}); + } + + exitCode = static_cast<uint8_t>(extiCode32); + } else if (!arg0.isUndefinedOrNull()) { + throwTypeError(globalObject, throwScope, "The \"code\" argument must be an integer"_s); + return JSC::JSValue::encode(JSC::JSValue {}); + } else { + exitCode = Bun__getExitCode(Bun__getVM()); + } + + auto* zigGlobal = jsDynamicCast<Zig::GlobalObject*>(globalObject); + if (UNLIKELY(!zigGlobal)) { + zigGlobal = Bun__getDefaultGlobal(); + } + Bun__Process__exit(zigGlobal, exitCode); + __builtin_unreachable(); +} + +template<typename Visitor> +void Process::visitChildrenImpl(JSCell* cell, Visitor& visitor) +{ + Process* thisObject = jsCast<Process*>(cell); + ASSERT_GC_OBJECT_INHERITS(thisObject, info()); + Base::visitChildren(thisObject, visitor); + thisObject->cpuUsageStructure.visit(visitor); + thisObject->memoryUsageStructure.visit(visitor); +} + +DEFINE_VISIT_CHILDREN(Process); + +static Structure* constructCPUUsageStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject) +{ + JSC::Structure* structure = globalObject->structureCache().emptyObjectStructureForPrototype(globalObject, globalObject->objectPrototype(), 2); + PropertyOffset offset; + structure = structure->addPropertyTransition( vm, - moduleMainCodeGenerator(vm), - globalObject->globalScope()); - // https://nodejs.org/api/process.html#processmainmodule - this->putDirect( + structure, + JSC::Identifier::fromString(vm, "user"_s), + 0, + offset); + structure = structure->addPropertyTransition( vm, - JSC::Identifier::fromString(vm, "mainModule"_s), - JSC::GetterSetter::create(vm, globalObject, requireDotMainFunction, JSValue()), - PropertyAttribute::Builtin | PropertyAttribute::Accessor | PropertyAttribute::ReadOnly | PropertyAttribute::DontEnum | 0); + structure, + JSC::Identifier::fromString(vm, "system"_s), + 0, + offset); + return structure; } +static Structure* constructMemoryUsageStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject) +{ + JSC::Structure* structure = globalObject->structureCache().emptyObjectStructureForPrototype(globalObject, globalObject->objectPrototype(), 5); + PropertyOffset offset; + structure = structure->addPropertyTransition( + vm, + structure, + JSC::Identifier::fromString(vm, "rss"_s), + 0, + offset); + structure = structure->addPropertyTransition( + vm, + structure, + JSC::Identifier::fromString(vm, "heapTotal"_s), + 0, + offset); + structure = structure->addPropertyTransition( + vm, + structure, + JSC::Identifier::fromString(vm, "heapUsed"_s), + 0, + offset); + structure = structure->addPropertyTransition( + vm, + structure, + JSC::Identifier::fromString(vm, "external"_s), + 0, + offset); + structure = structure->addPropertyTransition( + vm, + structure, + JSC::Identifier::fromString(vm, "arrayBuffers"_s), + 0, + offset); -const JSC::ClassInfo Process::s_info = { "Process"_s, &Base::s_info, nullptr, nullptr, - CREATE_METHOD_TABLE(Process) }; + return structure; +} -JSC_DEFINE_CUSTOM_GETTER(Process_getTitle, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName)) +static Process* getProcessObject(JSC::JSGlobalObject* lexicalGlobalObject, JSValue thisValue) { - ZigString str; - Bun__Process__getTitle(globalObject, &str); - return JSValue::encode(Zig::toJSStringValue(str, globalObject)); + Process* process = jsDynamicCast<Process*>(thisValue); + + // Handle "var memoryUsage = process.memoryUsage; memoryUsage()" + if (UNLIKELY(!process)) { + // Handle calling this function from inside a node:vm + Zig::GlobalObject* zigGlobalObject = jsDynamicCast<Zig::GlobalObject*>(lexicalGlobalObject); + + if (UNLIKELY(!zigGlobalObject)) { + zigGlobalObject = Bun__getDefaultGlobal(); + } + + return jsCast<Process*>(zigGlobalObject->processObject()); + } + + return process; } -JSC_DEFINE_CUSTOM_SETTER(Process_setTitle, - (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, - JSC::EncodedJSValue value, JSC::PropertyName)) +JSC_DEFINE_HOST_FUNCTION(Process_functionCpuUsage, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame)) { JSC::VM& vm = globalObject->vm(); + auto throwScope = DECLARE_THROW_SCOPE(vm); + struct rusage rusage; + if (getrusage(RUSAGE_SELF, &rusage) != 0) { + SystemError error; + error.errno_ = errno; + error.syscall = Bun::toString("getrusage"_s); + error.message = Bun::toString("Failed to get CPU usage"_s); + throwException(globalObject, throwScope, JSValue::decode(SystemError__toErrorInstance(&error, globalObject))); + return JSValue::encode(jsUndefined()); + } - JSC::JSObject* thisObject = JSC::jsDynamicCast<JSC::JSObject*>(JSValue::decode(thisValue)); - JSC::JSString* jsString = JSC::jsDynamicCast<JSC::JSString*>(JSValue::decode(value)); - if (!thisObject || !jsString) { - return false; + auto* process = getProcessObject(globalObject, callFrame->thisValue()); + + Structure* cpuUsageStructure = process->cpuUsageStructure.getInitializedOnMainThread(process); + + constexpr double MICROS_PER_SEC = 1000000.0; + + double user = MICROS_PER_SEC * rusage.ru_utime.tv_sec + rusage.ru_utime.tv_usec; + double system = MICROS_PER_SEC * rusage.ru_stime.tv_sec + rusage.ru_stime.tv_usec; + + if (callFrame->argumentCount() > 0) { + JSValue comparatorValue = callFrame->argument(0); + if (!comparatorValue.isUndefined()) { + if (UNLIKELY(!comparatorValue.isObject())) { + throwTypeError(globalObject, throwScope, "Expected an object as the first argument"_s); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + JSC::JSObject* comparator = comparatorValue.getObject(); + JSValue userValue; + JSValue systemValue; + + if (LIKELY(comparator->structureID() == cpuUsageStructure->id())) { + userValue = comparator->getDirect(0); + systemValue = comparator->getDirect(1); + } else { + userValue = comparator->getIfPropertyExists(globalObject, JSC::Identifier::fromString(vm, "user"_s)); + RETURN_IF_EXCEPTION(throwScope, JSC::JSValue::encode(JSC::jsUndefined())); + + systemValue = comparator->getIfPropertyExists(globalObject, JSC::Identifier::fromString(vm, "system"_s)); + RETURN_IF_EXCEPTION(throwScope, JSC::JSValue::encode(JSC::jsUndefined())); + } + + if (UNLIKELY(!userValue || !userValue.isNumber())) { + throwTypeError(globalObject, throwScope, "Expected a number for the user property"_s); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + if (UNLIKELY(!systemValue || !systemValue.isNumber())) { + throwTypeError(globalObject, throwScope, "Expected a number for the system property"_s); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + double userComparator = userValue.asNumber(); + double systemComparator = systemValue.asNumber(); + + user -= userComparator; + system -= systemComparator; + } } - ZigString str = Zig::toZigString(jsString, globalObject); - Bun__Process__setTitle(globalObject, &str); + JSC::JSObject* result = JSC::constructEmptyObject(vm, cpuUsageStructure); + RETURN_IF_EXCEPTION(throwScope, JSC::JSValue::encode(JSC::jsUndefined())); - return true; + result->putDirectOffset(vm, 0, JSC::jsNumber(user)); + result->putDirectOffset(vm, 1, JSC::jsNumber(system)); + + RELEASE_AND_RETURN(throwScope, JSC::JSValue::encode(result)); } -JSC_DEFINE_CUSTOM_GETTER(Process_getArgv, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName)) +static int getRSS(size_t* rss) +{ +#if defined(__APPLE__) + mach_msg_type_number_t count; + task_basic_info_data_t info; + kern_return_t err; + + count = TASK_BASIC_INFO_COUNT; + err = task_info(mach_task_self(), + TASK_BASIC_INFO, + reinterpret_cast<task_info_t>(&info), + &count); + + if (err == KERN_SUCCESS) { + *rss = (size_t)info.resident_size; + return 0; + } + + return -1; +#elif defined(__linux__) + // Taken from libuv. + char buf[1024]; + const char* s; + ssize_t n; + long val; + int fd; + int i; + + do + fd = open("/proc/self/stat", O_RDONLY); + while (fd == -1 && errno == EINTR); + + if (fd == -1) + return errno; + + do + n = read(fd, buf, sizeof(buf) - 1); + while (n == -1 && errno == EINTR); + + int closeErrno = 0; + do { + closeErrno = close(fd); + } while (closeErrno == -1 && errno == EINTR); + + if (n == -1) + return errno; + buf[n] = '\0'; + + s = strchr(buf, ' '); + if (s == NULL) + goto err; + + s += 1; + if (*s != '(') + goto err; + + s = strchr(s, ')'); + if (s == NULL) + goto err; + + for (i = 1; i <= 22; i++) { + s = strchr(s + 1, ' '); + if (s == NULL) + goto err; + } + + errno = 0; + val = strtol(s, NULL, 10); + if (errno != 0) + goto err; + if (val < 0) + goto err; + + *rss = val * getpagesize(); + return 0; + +err: + return EINVAL; +#else +#error "Unsupported platform" +#endif +} + +JSC_DEFINE_HOST_FUNCTION(Process_functionMemoryUsage, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame)) { JSC::VM& vm = globalObject->vm(); + auto throwScope = DECLARE_THROW_SCOPE(vm); + auto* process = getProcessObject(globalObject, callFrame->thisValue()); + + size_t current_rss = 0; + if (getRSS(¤t_rss) != 0) { + SystemError error; + error.errno_ = errno; + error.syscall = Bun::toString("memoryUsage"_s); + error.message = Bun::toString("Failed to get memory usage"_s); + throwException(globalObject, throwScope, JSValue::decode(SystemError__toErrorInstance(&error, globalObject))); + return JSC::JSValue::encode(JSC::JSValue {}); + } - Zig::Process* thisObject = JSC::jsDynamicCast<Zig::Process*>(JSValue::decode(thisValue)); - if (!thisObject) { - return JSValue::encode(JSC::jsUndefined()); + JSC::JSObject* result = JSC::constructEmptyObject(vm, process->memoryUsageStructure.getInitializedOnMainThread(process)); + if (UNLIKELY(throwScope.exception())) { + return JSC::JSValue::encode(JSC::JSValue {}); } - JSC::EncodedJSValue argv_ = Bun__Process__getArgv(globalObject); - auto clientData = WebCore::clientData(vm); + // Node.js: + // { + // rss: 4935680, + // heapTotal: 1826816, + // heapUsed: 650472, + // external: 49879, + // arrayBuffers: 9386 + // } + + result->putDirectOffset(vm, 0, JSC::jsNumber(current_rss)); + result->putDirectOffset(vm, 1, JSC::jsNumber(vm.heap.blockBytesAllocated())); + + // heap.size() loops through every cell... + // TODO: add a binding for heap.sizeAfterLastCollection() + result->putDirectOffset(vm, 2, JSC::jsNumber(vm.heap.sizeAfterLastEdenCollection())); - thisObject->putDirect(vm, clientData->builtinNames().argvPublicName(), - JSC::JSValue::decode(argv_), 0); + result->putDirectOffset(vm, 3, JSC::jsNumber(vm.heap.externalMemorySize())); - return argv_; + // We report 0 for this because m_arrayBuffers in JSC::Heap is private and we need to add a binding + // If we use objectTypeCounts(), it's hideously slow because it loops through every single object in the heap + // TODO: add a binding for m_arrayBuffers, registerWrapper() in TypedArrayController doesn't work + result->putDirectOffset(vm, 4, JSC::jsNumber(0)); + + RELEASE_AND_RETURN(throwScope, JSC::JSValue::encode(result)); } -JSC_DEFINE_CUSTOM_SETTER(Process_setArgv, - (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, - JSC::EncodedJSValue value, JSC::PropertyName)) +JSC_DEFINE_HOST_FUNCTION(Process_functionMemoryUsageRSS, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame)) { JSC::VM& vm = globalObject->vm(); + auto throwScope = DECLARE_THROW_SCOPE(vm); - JSC::JSObject* thisObject = JSC::jsDynamicCast<JSC::JSObject*>(JSValue::decode(thisValue)); - if (!thisObject) { - return false; + size_t current_rss = 0; + if (getRSS(¤t_rss) != 0) { + SystemError error; + error.errno_ = errno; + error.syscall = Bun::toString("memoryUsage"_s); + error.message = Bun::toString("Failed to get memory usage"_s); + throwException(globalObject, throwScope, JSValue::decode(SystemError__toErrorInstance(&error, globalObject))); + return JSC::JSValue::encode(JSC::JSValue {}); } - auto clientData = WebCore::clientData(vm); + RELEASE_AND_RETURN(throwScope, JSValue::encode(jsNumber(current_rss))); +} + +JSC_DEFINE_HOST_FUNCTION(Process_functionOpenStdin, (JSGlobalObject * globalObject, CallFrame* callFrame)) +{ + auto& vm = globalObject->vm(); + Zig::GlobalObject* global = jsDynamicCast<Zig::GlobalObject*>(globalObject); + if (UNLIKELY(!global)) { + global = Bun__getDefaultGlobal(); + } + auto throwScope = DECLARE_THROW_SCOPE(vm); + + if (JSValue stdin = global->processObject()->getIfPropertyExists(globalObject, Identifier::fromString(vm, "stdin"_s))) { + RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined())); + + if (!stdin.isObject()) { + throwTypeError(globalObject, throwScope, "stdin is not an object"_s); + return JSValue::encode(jsUndefined()); + } - return thisObject->putDirect(vm, clientData->builtinNames().argvPublicName(), - JSC::JSValue::decode(value)); + JSValue resumeValue = stdin.getObject()->getIfPropertyExists(globalObject, Identifier::fromString(vm, "resume"_s)); + RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined())); + if (!resumeValue.isUndefinedOrNull()) { + auto resumeFunction = jsDynamicCast<JSFunction*>(resumeValue); + if (UNLIKELY(!resumeFunction)) { + throwTypeError(globalObject, throwScope, "stdin.resume is not a function"_s); + return JSValue::encode(jsUndefined()); + } + + auto callData = getCallData(resumeFunction); + + MarkedArgumentBuffer args; + JSC::call(globalObject, resumeFunction, callData, stdin, args); + RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined())); + } + + RELEASE_AND_RETURN(throwScope, JSValue::encode(stdin)); + } + + RELEASE_AND_RETURN(throwScope, JSValue::encode(jsUndefined())); } -JSC_DEFINE_CUSTOM_GETTER(Process_getPID, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName)) +JSC_DEFINE_HOST_FUNCTION(Process_stubEmptyFunction, (JSGlobalObject * globalObject, CallFrame* callFrame)) { - return JSC::JSValue::encode(JSC::JSValue(getpid())); + return JSValue::encode(jsUndefined()); } -JSC_DEFINE_CUSTOM_GETTER(Process_getPPID, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName)) +JSC_DEFINE_HOST_FUNCTION(Process_stubFunctionReturningArray, (JSGlobalObject * globalObject, CallFrame* callFrame)) { - return JSC::JSValue::encode(JSC::JSValue(getppid())); + return JSValue::encode(JSC::constructEmptyArray(globalObject, nullptr)); } -#if !defined(BUN_WEBKIT_VERSION) -#define BUN_WEBKIT_VERSION "unknown" -#endif +static JSValue Process_stubEmptyObject(VM& vm, JSObject* processObject) +{ + return JSC::constructEmptyObject(processObject->globalObject()); +} -JSC_DEFINE_CUSTOM_GETTER(Process_getVersionsLazy, - (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, - JSC::PropertyName)) +static JSValue Process_stubEmptyArray(VM& vm, JSObject* processObject) { - JSC::VM& vm = globalObject->vm(); - auto clientData = WebCore::clientData(vm); + return JSC::constructEmptyArray(processObject->globalObject(), nullptr); +} - Zig::Process* thisObject = JSC::jsDynamicCast<Zig::Process*>(JSValue::decode(thisValue)); - if (!thisObject) { - return JSValue::encode(JSC::jsUndefined()); +static JSValue Process_stubEmptySet(VM& vm, JSObject* processObject) +{ + auto* globalObject = processObject->globalObject(); + return JSSet::create(vm, globalObject->setStructure()); +} + +static JSValue constructMemoryUsage(VM& vm, JSObject* processObject) +{ + auto* globalObject = processObject->globalObject(); + JSC::JSFunction* memoryUsage = JSC::JSFunction::create(vm, globalObject, 0, + String("memoryUsage"_s), Process_functionMemoryUsage, ImplementationVisibility::Public); + + JSC::JSFunction* rss = JSC::JSFunction::create(vm, globalObject, 0, + String("rss"_s), Process_functionMemoryUsageRSS, ImplementationVisibility::Public); + + memoryUsage->putDirect(vm, JSC::Identifier::fromString(vm, "rss"_s), rss, JSC::PropertyAttribute::Function | 0); + return memoryUsage; +} + +static JSValue constructFeatures(VM& vm, JSObject* processObject) +{ + // { + // inspector: true, + // debug: false, + // uv: true, + // ipv6: true, + // tls_alpn: true, + // tls_sni: true, + // tls_ocsp: true, + // tls: true, + // cached_builtins: [Getter] + // } + auto* globalObject = processObject->globalObject(); + auto* object = constructEmptyObject(globalObject); + + object->putDirect(vm, Identifier::fromString(vm, "inspector"_s), jsBoolean(true)); +#ifdef BUN_DEBUG + object->putDirect(vm, Identifier::fromString(vm, "debug"_s), jsBoolean(true)); +#else + object->putDirect(vm, Identifier::fromString(vm, "debug"_s), jsBoolean(false)); +#endif + // lying + object->putDirect(vm, Identifier::fromString(vm, "uv"_s), jsBoolean(true)); + + object->putDirect(vm, Identifier::fromString(vm, "ipv6"_s), jsBoolean(true)); + object->putDirect(vm, Identifier::fromString(vm, "tls_alpn"_s), jsBoolean(true)); + object->putDirect(vm, Identifier::fromString(vm, "tls_sni"_s), jsBoolean(true)); + object->putDirect(vm, Identifier::fromString(vm, "tls_ocsp"_s), jsBoolean(true)); + object->putDirect(vm, Identifier::fromString(vm, "tls"_s), jsBoolean(true)); + object->putDirect(vm, Identifier::fromString(vm, "cached_builtins"_s), jsBoolean(true)); + + return object; +} + +static int _debugPort; + +JSC_DEFINE_CUSTOM_GETTER(processDebugPort, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName)) +{ + if (_debugPort == 0) { + _debugPort = 9229; } - auto scope = DECLARE_THROW_SCOPE(vm); - JSC::JSObject* object = JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), 19); + return JSC::JSValue::encode(jsNumber(_debugPort)); +} - object->putDirect(vm, JSC::Identifier::fromString(vm, "node"_s), - JSC::JSValue(JSC::jsOwnedString(vm, makeAtomString(REPORTED_NODE_VERSION)))); - object->putDirect( - vm, JSC::Identifier::fromString(vm, "bun"_s), - JSC::JSValue(JSC::jsOwnedString(vm, makeAtomString(Bun__version + 1 /* prefix with v */)))); - object->putDirect(vm, JSC::Identifier::fromString(vm, "webkit"_s), - JSC::JSValue(JSC::jsOwnedString(vm, makeAtomString(BUN_WEBKIT_VERSION)))); - object->putDirect(vm, JSC::Identifier::fromString(vm, "boringssl"_s), - JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_boringssl))), 0); - object->putDirect(vm, JSC::Identifier::fromString(vm, "libarchive"_s), - JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_libarchive))), 0); - object->putDirect(vm, JSC::Identifier::fromString(vm, "mimalloc"_s), - JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_mimalloc))), 0); - object->putDirect(vm, JSC::Identifier::fromString(vm, "picohttpparser"_s), - JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_picohttpparser))), 0); - object->putDirect(vm, JSC::Identifier::fromString(vm, "uwebsockets"_s), - JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_uws))), 0); - object->putDirect(vm, JSC::Identifier::fromString(vm, "webkit"_s), - JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_webkit))), 0); - object->putDirect(vm, JSC::Identifier::fromString(vm, "zig"_s), - JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_zig))), 0); - object->putDirect(vm, JSC::Identifier::fromString(vm, "zlib"_s), - JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_zlib))), 0); - object->putDirect(vm, JSC::Identifier::fromString(vm, "tinycc"_s), - JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_tinycc))), 0); - object->putDirect(vm, JSC::Identifier::fromString(vm, "lolhtml"_s), - JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_lolhtml))), 0); - object->putDirect(vm, JSC::Identifier::fromString(vm, "ares"_s), - JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_c_ares))), 0); - object->putDirect(vm, JSC::Identifier::fromString(vm, "usockets"_s), - JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_usockets))), 0); +JSC_DEFINE_CUSTOM_SETTER(setProcessDebugPort, + (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, + JSC::EncodedJSValue encodedValue, JSC::PropertyName)) +{ + auto& vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + JSValue value = JSValue::decode(encodedValue); - object->putDirect(vm, JSC::Identifier::fromString(vm, "v8"_s), JSValue(JSC::jsString(vm, makeString("10.8.168.20-node.8"_s))), 0); - object->putDirect(vm, JSC::Identifier::fromString(vm, "uv"_s), JSValue(JSC::jsString(vm, makeString("1.44.2"_s))), 0); - object->putDirect(vm, JSC::Identifier::fromString(vm, "napi"_s), JSValue(JSC::jsString(vm, makeString("8"_s))), 0); + if (!value.isInt32()) { + throwRangeError(globalObject, scope, "debugPort must be 0 or in range 1024 to 65535"_s); + return false; + } - object->putDirect(vm, JSC::Identifier::fromString(vm, "modules"_s), - JSC::JSValue(JSC::jsOwnedString(vm, makeAtomString("108")))); + int port = value.asInt32(); - thisObject->putDirect(vm, clientData->builtinNames().versionsPublicName(), object, 0); + if (port != 0) { + if (port < 1024 || port > 65535) { + throwRangeError(globalObject, scope, "debugPort must be 0 or in range 1024 to 65535"_s); + return false; + } + } - RETURN_IF_EXCEPTION(scope, {}); + _debugPort = port; + return true; +} - return JSValue::encode(object); +JSC_DEFINE_CUSTOM_GETTER(processTitle, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName)) +{ + ZigString str; + Bun__Process__getTitle(globalObject, &str); + return JSValue::encode(Zig::toJSStringValue(str, globalObject)); } -JSC_DEFINE_CUSTOM_SETTER(Process_setVersionsLazy, + +JSC_DEFINE_CUSTOM_SETTER(setProcessTitle, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::EncodedJSValue value, JSC::PropertyName)) { JSC::VM& vm = globalObject->vm(); - auto clientData = WebCore::clientData(vm); - Zig::Process* thisObject = JSC::jsDynamicCast<Zig::Process*>(JSValue::decode(thisValue)); - if (!thisObject) { - return JSValue::encode(JSC::jsUndefined()); + JSC::JSObject* thisObject = JSC::jsDynamicCast<JSC::JSObject*>(JSValue::decode(thisValue)); + JSC::JSString* jsString = JSC::jsDynamicCast<JSC::JSString*>(JSValue::decode(value)); + if (!thisObject || !jsString) { + return false; } - thisObject->putDirect(vm, clientData->builtinNames().versionsPublicName(), - JSC::JSValue::decode(value), 0); + ZigString str = Zig::toZigString(jsString, globalObject); + Bun__Process__setTitle(globalObject, &str); return true; } -static JSC_DEFINE_HOST_FUNCTION(Process_functionCwd, +JSC_DEFINE_HOST_FUNCTION(Process_functionCwd, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame)) { auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); @@ -1091,4 +1477,88 @@ static JSC_DEFINE_HOST_FUNCTION(Process_functionCwd, return JSC::JSValue::encode(result); } +/* Source for Process.lut.h +@begin processObjectTable + abort Process_functionAbort Function 1 + allowedNodeEnvironmentFlags Process_stubEmptySet PropertyCallback + arch constructArch PropertyCallback + argv constructArgv PropertyCallback + argv0 constructArgv0 PropertyCallback + assert Process_functionAssert Function 1 + binding JSBuiltin Function 1 + browser constructBrowser PropertyCallback + chdir Process_functionChdir Function 1 + config constructProcessConfigObject PropertyCallback + cpuUsage Process_functionCpuUsage Function 1 + cwd Process_functionCwd Function 1 + debugPort processDebugPort CustomAccessor + dlopen Process_functionDlopen Function 1 + emitWarning Process_emitWarning Function 1 + env constructEnv PropertyCallback + execArgv constructExecArgv PropertyCallback + execPath constructExecPath PropertyCallback + exit Process_functionExit Function 1 + exitCode processExitCode CustomAccessor + features constructFeatures PropertyCallback + getActiveResourcesInfo Process_stubFunctionReturningArray Function 0 + getegid Process_functiongetegid Function 0 + geteuid Process_functiongeteuid Function 0 + getgid Process_functiongetgid Function 0 + getgroups Process_functiongetgroups Function 0 + getuid Process_functiongetuid Function 0 + hrtime constructProcessHrtimeObject PropertyCallback + isBun constructIsBun PropertyCallback + mainModule JSBuiltin ReadOnly|Builtin|Accessor|Function 0 + memoryUsage constructMemoryUsage PropertyCallback + moduleLoadList Process_stubEmptyArray PropertyCallback + nextTick Process_functionNextTick Function 1 + openStdin Process_functionOpenStdin Function 0 + pid constructPid PropertyCallback + platform constructPlatform PropertyCallback + ppid constructPpid PropertyCallback + reallyExit Process_functionReallyExit Function 1 + release constructProcessReleaseObject PropertyCallback + revision constructRevision PropertyCallback + setSourceMapsEnabled Process_stubEmptyFunction Function 1 + stderr constructStderr PropertyCallback + stdin constructStdin PropertyCallback + stdout constructStdout PropertyCallback + title processTitle CustomAccessor + umask Process_functionUmask Function 1 + uptime Process_functionUptime Function 1 + version constructVersion PropertyCallback + versions constructVersions PropertyCallback + _debugEnd Process_stubEmptyFunction Function 0 + _debugProcess Process_stubEmptyFunction Function 0 + _fatalException Process_stubEmptyFunction Function 1 + _getActiveRequests Process_stubFunctionReturningArray Function 0 + _getActiveHandles Process_stubFunctionReturningArray Function 0 + _linkedBinding Process_stubEmptyFunction Function 0 + _preload_modules Process_stubEmptyObject PropertyCallback + _rawDebug Process_stubEmptyFunction Function 0 + _startProfilerIdleNotifier Process_stubEmptyFunction Function 0 + _stopProfilerIdleNotifier Process_stubEmptyFunction Function 0 + _tickCallback Process_stubEmptyFunction Function 0 +@end +*/ + +#include "Process.lut.h" +const JSC::ClassInfo Process::s_info = { "Process"_s, &Base::s_info, &processObjectTable, nullptr, + CREATE_METHOD_TABLE(Process) }; + +void Process::finishCreation(JSC::VM& vm) +{ + Base::finishCreation(vm); + + this->cpuUsageStructure.initLater([](const JSC::LazyProperty<JSC::JSObject, JSC::Structure>::Initializer& init) { + init.set(constructCPUUsageStructure(init.vm, init.owner->globalObject())); + }); + + this->memoryUsageStructure.initLater([](const JSC::LazyProperty<JSC::JSObject, JSC::Structure>::Initializer& init) { + init.set(constructMemoryUsageStructure(init.vm, init.owner->globalObject())); + }); + + this->putDirect(vm, vm.propertyNames->toStringTagSymbol, jsString(vm, String("process"_s)), 0); +} + } // namespace Zig diff --git a/src/bun.js/bindings/Process.h b/src/bun.js/bindings/Process.h index 322b39078..fbad9b1ff 100644 --- a/src/bun.js/bindings/Process.h +++ b/src/bun.js/bindings/Process.h @@ -28,7 +28,7 @@ public: ~Process(); - static constexpr unsigned StructureFlags = Base::StructureFlags; + static constexpr unsigned StructureFlags = Base::StructureFlags | HasStaticPropertyTable; static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) @@ -45,6 +45,24 @@ public: return accessor; } + LazyProperty<JSObject, Structure> cpuUsageStructure; + LazyProperty<JSObject, Structure> memoryUsageStructure; + + DECLARE_VISIT_CHILDREN; + + template<typename, SubspaceAccess mode> + static JSC::GCClient::IsoSubspace* subspaceFor(JSC::VM& vm) + { + if constexpr (mode == JSC::SubspaceAccess::Concurrently) + return nullptr; + return WebCore::subspaceForImpl<Process, WebCore::UseCustomHeapCellType::No>( + vm, + [](auto& spaces) { return spaces.m_clientSubspaceForProcessObject.get(); }, + [](auto& spaces, auto&& space) { spaces.m_clientSubspaceForProcessObject = std::forward<decltype(space)>(space); }, + [](auto& spaces) { return spaces.m_subspaceForProcessObject.get(); }, + [](auto& spaces, auto&& space) { spaces.m_subspaceForProcessObject = std::forward<decltype(space)>(space); }); + } + void finishCreation(JSC::VM& vm); }; diff --git a/src/bun.js/bindings/Process.lut.h b/src/bun.js/bindings/Process.lut.h new file mode 100644 index 000000000..81eb1b7b9 --- /dev/null +++ b/src/bun.js/bindings/Process.lut.h @@ -0,0 +1,211 @@ +// File generated via `make generate-builtins` +static const struct CompactHashIndex processObjectTableIndex[142] = { + { 43, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { 15, 129 }, + { -1, -1 }, + { -1, -1 }, + { 18, 138 }, + { -1, -1 }, + { 45, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { 3, 141 }, + { 1, 128 }, + { -1, -1 }, + { 59, -1 }, + { -1, -1 }, + { 10, -1 }, + { -1, -1 }, + { -1, -1 }, + { 31, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { 52, -1 }, + { 27, -1 }, + { 12, -1 }, + { -1, -1 }, + { 19, -1 }, + { -1, -1 }, + { 14, 137 }, + { -1, -1 }, + { 36, -1 }, + { -1, -1 }, + { 38, -1 }, + { 55, -1 }, + { 35, -1 }, + { 6, 139 }, + { -1, -1 }, + { 51, -1 }, + { 4, -1 }, + { 47, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { 2, -1 }, + { 7, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { 40, -1 }, + { -1, -1 }, + { 37, -1 }, + { -1, -1 }, + { 0, -1 }, + { 26, 135 }, + { 16, 130 }, + { 39, -1 }, + { -1, -1 }, + { 23, -1 }, + { 11, -1 }, + { -1, -1 }, + { -1, -1 }, + { 58, -1 }, + { -1, -1 }, + { -1, -1 }, + { 30, 136 }, + { -1, -1 }, + { 29, -1 }, + { 22, -1 }, + { -1, -1 }, + { -1, -1 }, + { 24, -1 }, + { -1, -1 }, + { -1, -1 }, + { 20, -1 }, + { -1, -1 }, + { 5, -1 }, + { -1, -1 }, + { -1, -1 }, + { 48, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { 13, 131 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { 9, -1 }, + { 25, 133 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { 21, 134 }, + { -1, -1 }, + { -1, -1 }, + { -1, -1 }, + { 46, 140 }, + { -1, -1 }, + { 17, -1 }, + { 8, -1 }, + { 28, -1 }, + { 32, 132 }, + { 33, -1 }, + { 34, -1 }, + { 41, -1 }, + { 42, -1 }, + { 44, -1 }, + { 49, -1 }, + { 50, -1 }, + { 53, -1 }, + { 54, -1 }, + { 56, -1 }, + { 57, -1 }, +}; + +static const struct HashTableValue processObjectTableValues[60] = { + { "abort"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functionAbort, 1 } }, + { "allowedNodeEnvironmentFlags"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, Process_stubEmptySet } }, + { "arch"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructArch } }, + { "argv"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructArgv } }, + { "argv0"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructArgv0 } }, + { "assert"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functionAssert, 1 } }, + { "binding"_s, ((static_cast<unsigned>(PropertyAttribute::Function)) & ~PropertyAttribute::Function) | PropertyAttribute::Builtin, NoIntrinsic, { HashTableValue::BuiltinGeneratorType, processObjectBindingCodeGenerator, 1 } }, + { "browser"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructBrowser } }, + { "chdir"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functionChdir, 1 } }, + { "config"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructProcessConfigObject } }, + { "cpuUsage"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functionCpuUsage, 1 } }, + { "cwd"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functionCwd, 1 } }, + { "debugPort"_s, static_cast<unsigned>(PropertyAttribute::CustomAccessor), NoIntrinsic, { HashTableValue::GetterSetterType, processDebugPort, setProcessDebugPort } }, + { "dlopen"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functionDlopen, 1 } }, + { "emitWarning"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_emitWarning, 1 } }, + { "env"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructEnv } }, + { "execArgv"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructExecArgv } }, + { "execPath"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructExecPath } }, + { "exit"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functionExit, 1 } }, + { "exitCode"_s, static_cast<unsigned>(PropertyAttribute::CustomAccessor), NoIntrinsic, { HashTableValue::GetterSetterType, processExitCode, setProcessExitCode } }, + { "features"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructFeatures } }, + { "getActiveResourcesInfo"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_stubFunctionReturningArray, 0 } }, + { "getegid"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functiongetegid, 0 } }, + { "geteuid"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functiongeteuid, 0 } }, + { "getgid"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functiongetgid, 0 } }, + { "getgroups"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functiongetgroups, 0 } }, + { "getuid"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functiongetuid, 0 } }, + { "hrtime"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructProcessHrtimeObject } }, + { "isBun"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructIsBun } }, + { "mainModule"_s, ((static_cast<unsigned>(PropertyAttribute::ReadOnly|PropertyAttribute::Builtin|PropertyAttribute::Accessor|PropertyAttribute::Function)) & ~PropertyAttribute::Function) | PropertyAttribute::Builtin, NoIntrinsic, { HashTableValue::BuiltinGeneratorType, processObjectMainModuleCodeGenerator, 0 } }, + { "memoryUsage"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructMemoryUsage } }, + { "moduleLoadList"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, Process_stubEmptyArray } }, + { "nextTick"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functionNextTick, 1 } }, + { "openStdin"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functionOpenStdin, 0 } }, + { "pid"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructPid } }, + { "platform"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructPlatform } }, + { "ppid"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructPpid } }, + { "reallyExit"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functionReallyExit, 1 } }, + { "release"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructProcessReleaseObject } }, + { "revision"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructRevision } }, + { "setSourceMapsEnabled"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_stubEmptyFunction, 1 } }, + { "stderr"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructStderr } }, + { "stdin"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructStdin } }, + { "stdout"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructStdout } }, + { "title"_s, static_cast<unsigned>(PropertyAttribute::CustomAccessor), NoIntrinsic, { HashTableValue::GetterSetterType, processTitle, setProcessTitle } }, + { "umask"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functionUmask, 1 } }, + { "uptime"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_functionUptime, 1 } }, + { "version"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructVersion } }, + { "versions"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, constructVersions } }, + { "_debugEnd"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_stubEmptyFunction, 0 } }, + { "_debugProcess"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_stubEmptyFunction, 0 } }, + { "_fatalException"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_stubEmptyFunction, 1 } }, + { "_getActiveRequests"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_stubFunctionReturningArray, 0 } }, + { "_getActiveHandles"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_stubFunctionReturningArray, 0 } }, + { "_linkedBinding"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_stubEmptyFunction, 0 } }, + { "_preload_modules"_s, static_cast<unsigned>(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, Process_stubEmptyObject } }, + { "_rawDebug"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_stubEmptyFunction, 0 } }, + { "_startProfilerIdleNotifier"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_stubEmptyFunction, 0 } }, + { "_stopProfilerIdleNotifier"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_stubEmptyFunction, 0 } }, + { "_tickCallback"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, Process_stubEmptyFunction, 0 } }, +}; + +static const struct HashTable processObjectTable = + { 60, 127, true, nullptr, processObjectTableValues, processObjectTableIndex }; diff --git a/src/bun.js/bindings/ZigGlobalObject.cpp b/src/bun.js/bindings/ZigGlobalObject.cpp index 4bb5445e1..3291b204e 100644 --- a/src/bun.js/bindings/ZigGlobalObject.cpp +++ b/src/bun.js/bindings/ZigGlobalObject.cpp @@ -3160,11 +3160,7 @@ void GlobalObject::finishCreation(VM& vm) Zig::GlobalObject* globalObject = reinterpret_cast<Zig::GlobalObject*>(init.owner); auto* process = Zig::Process::create( *globalObject, Zig::Process::createStructure(init.vm, init.owner, WebCore::JSEventEmitter::prototype(init.vm, *globalObject))); - process->putDirectCustomAccessor(init.vm, JSC::Identifier::fromString(init.vm, "env"_s), - JSC::CustomGetterSetter::create(init.vm, lazyProcessEnvGetter, lazyProcessEnvSetter), - JSC::PropertyAttribute::DontDelete - | JSC::PropertyAttribute::CustomValue - | 0); + init.set(process); }); diff --git a/src/bun.js/bindings/webcore/DOMClientIsoSubspaces.h b/src/bun.js/bindings/webcore/DOMClientIsoSubspaces.h index 65875d091..82a2c6a24 100644 --- a/src/bun.js/bindings/webcore/DOMClientIsoSubspaces.h +++ b/src/bun.js/bindings/webcore/DOMClientIsoSubspaces.h @@ -38,6 +38,7 @@ public: std::unique_ptr<GCClient::IsoSubspace> m_clientSubspaceForJSMockImplementation; std::unique_ptr<GCClient::IsoSubspace> m_clientSubspaceForJSMockFunction; std::unique_ptr<GCClient::IsoSubspace> m_clientSubspaceForMockWithImplementationCleanupData; + std::unique_ptr<GCClient::IsoSubspace> m_clientSubspaceForProcessObject; #include "ZigGeneratedClasses+DOMClientIsoSubspaces.h" /* --- bun --- */ diff --git a/src/bun.js/bindings/webcore/DOMIsoSubspaces.h b/src/bun.js/bindings/webcore/DOMIsoSubspaces.h index 433832450..f1b290d25 100644 --- a/src/bun.js/bindings/webcore/DOMIsoSubspaces.h +++ b/src/bun.js/bindings/webcore/DOMIsoSubspaces.h @@ -38,6 +38,7 @@ public: std::unique_ptr<IsoSubspace> m_subspaceForJSMockImplementation; std::unique_ptr<IsoSubspace> m_subspaceForJSMockFunction; std::unique_ptr<IsoSubspace> m_subspaceForMockWithImplementationCleanupData; + std::unique_ptr<IsoSubspace> m_subspaceForProcessObject; #include "ZigGeneratedClasses+DOMIsoSubspaces.h" /*-- BUN --*/ diff --git a/src/bun.js/modules/ProcessModule.h b/src/bun.js/modules/ProcessModule.h index 2df74598a..fab0298ae 100644 --- a/src/bun.js/modules/ProcessModule.h +++ b/src/bun.js/modules/ProcessModule.h @@ -44,11 +44,19 @@ inline void generateProcessSourceCode(JSC::JSGlobalObject *lexicalGlobalObject, reinterpret_cast<GlobalObject *>(lexicalGlobalObject); JSC::JSObject *process = globalObject->processObject(); + auto scope = DECLARE_THROW_SCOPE(vm); + if (!process->staticPropertiesReified()) { + process->reifyAllStaticProperties(globalObject); + if (scope.exception()) + return; + } PropertyNameArray properties(vm, PropertyNameMode::Strings, PrivateSymbolMode::Exclude); process->getPropertyNames(globalObject, properties, DontEnumPropertiesMode::Exclude); + if (scope.exception()) + return; exportNames.append(vm.propertyNames->defaultKeyword); exportValues.append(process); diff --git a/src/bun.js/node/types.zig b/src/bun.js/node/types.zig index 553b292d6..642039ba5 100644 --- a/src/bun.js/node/types.zig +++ b/src/bun.js/node/types.zig @@ -541,9 +541,18 @@ pub const Encoding = enum(u8) { const result = JSC.ZigString.init(out).toValueGC(globalThis); return result; }, - else => { - globalThis.throwInvalidArguments("Unexpected encoding", .{}); - return JSC.JSValue.zero; + .buffer => { + return JSC.ArrayBuffer.createBuffer(globalThis, input); + }, + + inline else => |enc| { + const res = JSC.WebCore.Encoder.toString(input.ptr, size, globalThis, enc); + if (res.isError()) { + globalThis.throwValue(res); + return .zero; + } + + return res; }, } } @@ -571,9 +580,18 @@ pub const Encoding = enum(u8) { const result = JSC.ZigString.init(out).toValueGC(globalThis); return result; }, - else => { - globalThis.throwInvalidArguments("Unexpected encoding", .{}); - return JSC.JSValue.zero; + .buffer => { + return JSC.ArrayBuffer.createBuffer(globalThis, input); + }, + inline else => |enc| { + const res = JSC.WebCore.Encoder.toString(input.ptr, input.len, globalThis, enc); + + if (res.isError()) { + globalThis.throwValue(res); + return .zero; + } + + return res; }, } } diff --git a/src/bun.js/rare_data.zig b/src/bun.js/rare_data.zig index ddda96bf4..3b29896a4 100644 --- a/src/bun.js/rare_data.zig +++ b/src/bun.js/rare_data.zig @@ -9,6 +9,7 @@ const std = @import("std"); const BoringSSL = @import("root").bun.BoringSSL; const bun = @import("root").bun; const WebSocketClientMask = @import("../http/websocket_http_client.zig").Mask; +const UUID = @import("./uuid.zig"); boring_ssl_engine: ?*BoringSSL.ENGINE = null, editor_context: EditorContext = EditorContext{}, @@ -47,13 +48,16 @@ pub fn filePolls(this: *RareData, vm: *JSC.VirtualMachine) *JSC.FilePoll.HiveArr }; } -pub fn nextUUID(this: *RareData) [16]u8 { +pub fn nextUUID(this: *RareData) UUID { if (this.entropy_cache == null) { this.entropy_cache = default_allocator.create(EntropyCache) catch unreachable; this.entropy_cache.?.init(); } - return this.entropy_cache.?.get(); + this.entropy_cache.?.fill(); + + const bytes = this.entropy_cache.?.get(); + return UUID.initWith(&bytes); } pub fn entropySlice(this: *RareData, len: usize) []u8 { diff --git a/src/bun.js/uuid.zig b/src/bun.js/uuid.zig index e8bdff661..e38ed567f 100644 --- a/src/bun.js/uuid.zig +++ b/src/bun.js/uuid.zig @@ -18,6 +18,16 @@ pub fn init() UUID { uuid.bytes[6] = (uuid.bytes[6] & 0x0f) | 0x40; // Variant 1 uuid.bytes[8] = (uuid.bytes[8] & 0x3f) | 0x80; + + return uuid; +} + +pub fn initWith(bytes: *const [16]u8) UUID { + var uuid = UUID{ .bytes = bytes.* }; + + uuid.bytes[6] = (uuid.bytes[6] & 0x0f) | 0x40; + uuid.bytes[8] = (uuid.bytes[8] & 0x3f) | 0x80; + return uuid; } diff --git a/src/bun.js/webcore.zig b/src/bun.js/webcore.zig index fd69b0262..8cb9ec80a 100644 --- a/src/bun.js/webcore.zig +++ b/src/bun.js/webcore.zig @@ -366,7 +366,6 @@ pub const Prompt = struct { }; pub const Crypto = struct { - const UUID = @import("./uuid.zig"); const BoringSSL = @import("root").bun.BoringSSL; pub const Class = JSC.NewClass( void, @@ -693,9 +692,8 @@ pub const Crypto = struct { _: []const JSC.JSValue, ) JSC.JSValue { var out: [36]u8 = undefined; - const uuid: UUID = .{ - .bytes = globalThis.bunVM().rareData().nextUUID(), - }; + const uuid = globalThis.bunVM().rareData().nextUUID(); + uuid.print(&out); return JSC.ZigString.init(&out).toValueGC(globalThis); } @@ -723,9 +721,8 @@ pub const Crypto = struct { _: *anyopaque, ) callconv(.C) JSC.JSValue { var out: [36]u8 = undefined; - const uuid: UUID = .{ - .bytes = globalThis.bunVM().rareData().nextUUID(), - }; + const uuid = globalThis.bunVM().rareData().nextUUID(); + uuid.print(&out); return JSC.ZigString.init(&out).toValueGC(globalThis); } diff --git a/src/bun.js/webcore/blob.zig b/src/bun.js/webcore/blob.zig index 86b5414e3..ef2520049 100644 --- a/src/bun.js/webcore/blob.zig +++ b/src/bun.js/webcore/blob.zig @@ -249,7 +249,7 @@ pub const Blob = struct { var hex_buf: [70]u8 = undefined; const boundary = brk: { - var random = globalThis.bunVM().rareData().nextUUID(); + var random = globalThis.bunVM().rareData().nextUUID().bytes; var formatter = std.fmt.fmtSliceHexLower(&random); break :brk std.fmt.bufPrint(&hex_buf, "-WebkitFormBoundary{any}", .{formatter}) catch unreachable; }; diff --git a/src/bun.js/webcore/encoding.zig b/src/bun.js/webcore/encoding.zig index bb1180acb..dd47ccc29 100644 --- a/src/bun.js/webcore/encoding.zig +++ b/src/bun.js/webcore/encoding.zig @@ -829,23 +829,18 @@ pub const Encoder = struct { return ZigString.init(input).toValueGC(global); } - if (input.len < 512) { - var buf: [512]u8 = undefined; - var to = buf[0..input.len]; - strings.copyLatin1IntoASCII(to, input); - return ZigString.init(to).toValueGC(global); - } - - var to = allocator.alloc(u8, len) catch return ZigString.init("Out of memory").toErrorInstance(global); - strings.copyLatin1IntoASCII(to, input); - return ZigString.init(to).toExternalValue(global); + var str = bun.String.createUninitialized(.latin1, len) orelse return ZigString.init("Out of memory").toErrorInstance(global); + defer str.deref(); + strings.copyLatin1IntoASCII(@constCast(str.latin1()), input); + return str.toJS(global); }, .latin1 => { - var to = allocator.alloc(u8, len) catch return ZigString.init("Out of memory").toErrorInstance(global); + var str = bun.String.createUninitialized(.latin1, len) orelse return ZigString.init("Out of memory").toErrorInstance(global); + defer str.deref(); - @memcpy(to, input_ptr[0..to.len]); + @memcpy(@constCast(str.latin1()), input_ptr[0..len]); - return ZigString.init(to).toExternalValue(global); + return str.toJS(global); }, .buffer, .utf8 => { const converted = strings.toUTF16Alloc(allocator, input, false) catch return ZigString.init("Out of memory").toErrorInstance(global); @@ -861,21 +856,22 @@ pub const Encoder = struct { // Avoid incomplete characters if (len / 2 == 0) return ZigString.Empty.toValue(global); - var output = allocator.alloc(u16, len / 2) catch return ZigString.init("Out of memory").toErrorInstance(global); - var output_bytes = std.mem.sliceAsBytes(output); + var output = bun.String.createUninitialized(.utf16, len / 2) orelse return ZigString.init("Out of memory").toErrorInstance(global); + defer output.deref(); + var output_bytes = std.mem.sliceAsBytes(@constCast(output.utf16())); output_bytes[output_bytes.len - 1] = 0; @memcpy(output_bytes, input_ptr[0..output_bytes.len]); - return ZigString.toExternalU16(output.ptr, output.len, global); + return output.toJS(global); }, .hex => { - var output = allocator.alloc(u8, input.len * 2) catch return ZigString.init("Out of memory").toErrorInstance(global); + var str = bun.String.createUninitialized(.latin1, len * 2) orelse return ZigString.init("Out of memory").toErrorInstance(global); + defer str.deref(); + var output = @constCast(str.latin1()); const wrote = strings.encodeBytesToHex(output, input); std.debug.assert(wrote == output.len); - var val = ZigString.init(output); - val.mark(); - return val.toExternalValue(global); + return str.toJS(global); }, .base64url => { diff --git a/src/http/websocket_http_client.zig b/src/http/websocket_http_client.zig index f495af3b7..ae8e40763 100644 --- a/src/http/websocket_http_client.zig +++ b/src/http/websocket_http_client.zig @@ -60,7 +60,7 @@ fn buildRequestBody( extra_headers: NonUTF8Headers, ) std.mem.Allocator.Error![]u8 { const allocator = vm.allocator; - const input_rand_buf = vm.rareData().nextUUID(); + const input_rand_buf = vm.rareData().nextUUID().bytes; const temp_buf_size = comptime std.base64.standard.Encoder.calcSize(16); var encoded_buf: [temp_buf_size]u8 = undefined; const accept_key = std.base64.standard.Encoder.encode(&encoded_buf, &input_rand_buf); diff --git a/src/js/build-esm.ts b/src/js/build-esm.ts index edfe7c04f..8cdca3688 100644 --- a/src/js/build-esm.ts +++ b/src/js/build-esm.ts @@ -55,23 +55,39 @@ const opts = { }, } as const; +const productionOpts = { + ...opts, + define: { + ...opts.define, + "IS_BUN_DEVELOPMENT": "false", + }, +}; + +const devOpts = { + ...opts, + define: { + ...opts.define, + "IS_BUN_DEVELOPMENT": "true", + }, +}; + const build_prod_minified = await Bun.build({ entrypoints: entrypoints.filter(file => minifyList.includes(file.slice(import.meta.dir.length + 1))), minify: true, - ...opts, + ...productionOpts, }); const build_prod_unminified = await Bun.build({ entrypoints: entrypoints.filter(file => !minifyList.includes(file.slice(import.meta.dir.length + 1))), minify: { syntax: true }, - ...opts, + ...productionOpts, }); const build_dev = await Bun.build({ entrypoints: entrypoints, minify: { syntax: true }, sourcemap: "external", - ...opts, + ...devOpts, }); for (const [build, outdir] of [ diff --git a/src/js/builtins/ProcessObjectInternals.ts b/src/js/builtins/ProcessObjectInternals.ts index 8b24e68ba..8e2449a43 100644 --- a/src/js/builtins/ProcessObjectInternals.ts +++ b/src/js/builtins/ProcessObjectInternals.ts @@ -49,9 +49,14 @@ export function binding(bindingName) { return constants; } -export function getStdioWriteStream(fd_, rawRequire) { - var module = { path: "node:process", require: rawRequire }; - var require = path => module.require(path); +export function getStdioWriteStream(fd_) { + var require = path => { + var existing = $requireMap.get(path); + if (existing) return existing.exports; + + return $internalRequire(path); + }; + var module = { path: "node:process", require }; function createStdioWriteStream(fd_) { var { Duplex, eos, destroy } = require("node:stream"); @@ -472,10 +477,15 @@ export function getStdioWriteStream(fd_, rawRequire) { return new FastStdioWriteStream(fd_); } -export function getStdinStream(fd_, rawRequire, Bun) { - var module = { path: "node:process", require: rawRequire }; - var require = path => module.require(path); +export function getStdinStream(fd_) { + var require = path => { + var existing = $requireMap.get(path); + if (existing) return existing.exports; + + return $internalRequire(path); + }; + var module = { path: "node:process", require: require }; var { Duplex, eos, destroy } = require("node:stream"); var StdinStream = class StdinStream extends Duplex { diff --git a/src/js/builtins/codegen/index.ts b/src/js/builtins/codegen/index.ts index e20601a15..a5d3c2dc8 100644 --- a/src/js/builtins/codegen/index.ts +++ b/src/js/builtins/codegen/index.ts @@ -3,7 +3,35 @@ import path from "path"; import { sliceSourceCode } from "./builtin-parser"; import { applyGlobalReplacements, enums, globalsToPrefix } from "./replacements"; import { cap, fmtCPPString, low } from "./helpers"; +import { spawn, spawnSync } from "bun"; + +async function createStaticHashtables() { + const STATIC_HASH_TABLES = ["src/bun.js/bindings/Process.cpp"]; + console.time("Creating static hash tables..."); + const create_hash_table = path.join( + import.meta.dir, + "../../../../bun-webkit/Source/JavaScriptCore/create_hash_table", + ); + for (let cpp of STATIC_HASH_TABLES) { + cpp = path.join(import.meta.dir, "../../../../", cpp); + const { stdout, exited } = spawn({ + cmd: [create_hash_table, cpp], + stdout: "pipe", + stderr: "inherit", + }); + await exited; + let str = await new Response(stdout).text(); + str = str.replaceAll(/^\/\/.*$/gm, ""); + str = str.replaceAll(/^#include.*$/gm, ""); + str = str.replaceAll(`namespace JSC {`, ""); + str = str.replaceAll(`} // namespace JSC`, ""); + str = "// File generated via `make generate-builtins`\n" + str.trim() + "\n"; + await Bun.write(cpp.replace(/\.cpp$/, ".lut.h"), str); + } + console.timeEnd("Creating static hash tables..."); +} +const staticHashTablePromise = createStaticHashtables(); console.log("Bundling Bun builtins..."); const MINIFY = process.argv.includes("--minify") || process.argv.includes("-m"); @@ -618,6 +646,8 @@ if (!KEEP_TMP) { await rmSync(TMP_DIR, { recursive: true }); } +await staticHashTablePromise; + console.log( `Embedded JS size: %s bytes (across %s functions, %s files)`, totalJSSize, diff --git a/src/js/node/http.ts b/src/js/node/http.ts index 0c42b247b..c8fbf20d6 100644 --- a/src/js/node/http.ts +++ b/src/js/node/http.ts @@ -109,6 +109,28 @@ function isValidTLSArray(obj) { } } +class ERR_INVALID_ARG_TYPE extends TypeError { + constructor(name, expected, actual) { + super(`The ${name} argument must be of type ${expected}. Received type ${typeof actual}`); + this.code = "ERR_INVALID_ARG_TYPE"; + } +} + +function validateMsecs(numberlike: any, field: string) { + if (typeof numberlike !== "number" || numberlike < 0) { + throw new ERR_INVALID_ARG_TYPE(field, "number", numberlike); + } + + return numberlike; +} +function validateFunction(callable: any, field: string) { + if (typeof callable !== "function") { + throw new ERR_INVALID_ARG_TYPE(field, "Function", callable); + } + + return callable; +} + function getHeader(headers, name) { if (!headers) return; const result = headers.get(name); @@ -792,12 +814,13 @@ export class OutgoingMessage extends Writable { headersSent = false; sendDate = true; req; + timeout; #finished = false; [kEndCalled] = false; #fakeSocket; - #timeoutTimer: Timer | null = null; + #timeoutTimer?: Timer; [kAbortController]: AbortController | null = null; // Express "compress" package uses this @@ -894,21 +917,41 @@ export class OutgoingMessage extends Writable { [kClearTimeout]() { if (this.#timeoutTimer) { clearTimeout(this.#timeoutTimer); - this.#timeoutTimer = null; + this.removeAllListeners("timeout"); + this.#timeoutTimer = undefined; } } + #onTimeout() { + this.#timeoutTimer = undefined; + this[kAbortController]?.abort(); + this.emit("timeout"); + } + setTimeout(msecs, callback) { - if (this.#timeoutTimer) return this; - if (callback) { - this.on("timeout", callback); - } + if (this.destroyed) return this; + + this.timeout = msecs = validateMsecs(msecs, "msecs"); - this.#timeoutTimer = setTimeout(async () => { - this.#timeoutTimer = null; - this[kAbortController]?.abort(); - this.emit("timeout"); - }, msecs); + // Attempt to clear an existing timer in both cases - + // even if it will be rescheduled we don't want to leak an existing timer. + clearTimeout(this.#timeoutTimer!); + + if (msecs === 0) { + if (callback !== undefined) { + validateFunction(callback, "callback"); + this.removeListener("timeout", callback); + } + + this.#timeoutTimer = undefined; + } else { + this.#timeoutTimer = setTimeout(this.#onTimeout.bind(this), msecs).unref(); + + if (callback !== undefined) { + validateFunction(callback, "callback"); + this.once("timeout", callback); + } + } return this; } @@ -1159,7 +1202,7 @@ export class ClientRequest extends OutgoingMessage { #fetchRequest; #signal: AbortSignal | null = null; [kAbortController]: AbortController | null = null; - #timeoutTimer: Timer | null = null; + #timeoutTimer?: Timer = undefined; #options; #finished; @@ -1228,6 +1271,9 @@ export class ClientRequest extends OutgoingMessage { redirect: "manual", verbose: Boolean(__DEBUG__), signal: this[kAbortController].signal, + + // Timeouts are handled via this.setTimeout. + timeout: false, }, ) .then(response => { @@ -1352,8 +1398,6 @@ export class ClientRequest extends OutgoingMessage { 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 @@ -1431,7 +1475,12 @@ export class ClientRequest extends OutgoingMessage { this.#reusedSocket = false; this.#host = host; this.#protocol = protocol; - this.#timeoutTimer = null; + + var timeout = options.timeout; + if (timeout !== undefined && timeout !== 0) { + this.setTimeout(timeout, undefined); + } + const headersArray = ArrayIsArray(headers); if (!headersArray) { var headers = options.headers; @@ -1486,17 +1535,8 @@ export class ClientRequest extends OutgoingMessage { // this[kUniqueHeaders] = parseUniqueHeadersOption(options.uniqueHeaders); - var optsWithoutSignal = options; - if (optsWithoutSignal.signal) { - optsWithoutSignal = ObjectAssign({}, options); - delete optsWithoutSignal.signal; - } + var { signal: _signal, ...optsWithoutSignal } = options; this.#options = optsWithoutSignal; - - var timeout = options.timeout; - if (timeout) { - this.setTimeout(timeout); - } } setSocketKeepAlive(enable = true, initialDelay = 0) { @@ -1509,21 +1549,41 @@ export class ClientRequest extends OutgoingMessage { [kClearTimeout]() { if (this.#timeoutTimer) { clearTimeout(this.#timeoutTimer); - this.#timeoutTimer = null; + this.#timeoutTimer = undefined; + this.removeAllListeners("timeout"); } } - setTimeout(msecs, callback?) { - if (this.#timeoutTimer) return this; - if (callback) { - this.on("timeout", callback); - } + #onTimeout() { + this.#timeoutTimer = undefined; + this[kAbortController]?.abort(); + this.emit("timeout"); + } - this.#timeoutTimer = setTimeout(async () => { - this.#timeoutTimer = null; - this[kAbortController]?.abort(); - this.emit("timeout"); - }, msecs); + setTimeout(msecs, callback) { + if (this.destroyed) return this; + + this.timeout = msecs = validateMsecs(msecs, "msecs"); + + // Attempt to clear an existing timer in both cases - + // even if it will be rescheduled we don't want to leak an existing timer. + clearTimeout(this.#timeoutTimer!); + + if (msecs === 0) { + if (callback !== undefined) { + validateFunction(callback, "callback"); + this.removeListener("timeout", callback); + } + + this.#timeoutTimer = undefined; + } else { + this.#timeoutTimer = setTimeout(this.#onTimeout.bind(this), msecs).unref(); + + if (callback !== undefined) { + validateFunction(callback, "callback"); + this.once("timeout", callback); + } + } return this; } diff --git a/src/js/node/stream.js b/src/js/node/stream.js index 9344fa73f..741b2f65c 100644 --- a/src/js/node/stream.js +++ b/src/js/node/stream.js @@ -1,15 +1,20 @@ // Hardcoded module "node:stream" / "readable-stream" // "readable-stream" npm package // just transpiled -var { isPromise, isCallable, direct, Object } = globalThis[Symbol.for("Bun.lazy")]("primordials"); -import { EventEmitter as EE } from "bun:events_native"; -import { StringDecoder } from "node:string_decoder"; -globalThis.__IDS_TO_TRACK = process.env.DEBUG_TRACK_EE?.length - ? process.env.DEBUG_TRACK_EE.split(",") - : process.env.DEBUG_STREAMS?.length - ? process.env.DEBUG_STREAMS.split(",") - : null; +// This must go at the top of the file, before any side effects. +// IS_BUN_DEVELOPMENT is a bundle-only global variable that is set to true when +// building a development bundle. +const __TRACK_EE__ = IS_BUN_DEVELOPMENT && !!process.env.DEBUG_TRACK_EE; +const __DEBUG__ = IS_BUN_DEVELOPMENT && !!(process.env.DEBUG || process.env.DEBUG_STREAMS || __TRACK_EE__); + +if (__DEBUG__) { + globalThis.__IDS_TO_TRACK = process.env.DEBUG_TRACK_EE?.length + ? process.env.DEBUG_TRACK_EE.split(",") + : process.env.DEBUG_STREAMS?.length + ? process.env.DEBUG_STREAMS.split(",") + : null; +} // Separating DEBUG, DEBUG_STREAMS and DEBUG_TRACK_EE env vars makes it easier to focus on the // events in this file rather than all debug output across all files @@ -18,9 +23,6 @@ globalThis.__IDS_TO_TRACK = process.env.DEBUG_TRACK_EE?.length // The events and/or all of the outputs for the given stream IDs assigned at stream construction // By default, child_process gives -const __TRACK_EE__ = !!process.env.DEBUG_TRACK_EE; -const __DEBUG__ = !!(process.env.DEBUG || process.env.DEBUG_STREAMS || __TRACK_EE__); - var debug = __DEBUG__ ? globalThis.__IDS_TO_TRACK ? // If we are tracking IDs for debug event emitters, we should prefix the debug output with the ID @@ -32,6 +34,10 @@ var debug = __DEBUG__ : (...args) => console.log(...args.slice(0, -1)) : () => {}; +var { isPromise, isCallable, direct, Object } = globalThis[Symbol.for("Bun.lazy")]("primordials"); +import { EventEmitter as EE } from "bun:events_native"; +import { StringDecoder } from "node:string_decoder"; + var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; diff --git a/src/js/out/WebCoreJSBuiltins.cpp b/src/js/out/WebCoreJSBuiltins.cpp index 5ad79fa10..f20f626d4 100644 --- a/src/js/out/WebCoreJSBuiltins.cpp +++ b/src/js/out/WebCoreJSBuiltins.cpp @@ -372,7 +372,7 @@ const JSC::ConstructorKind s_writableStreamInternalsSetUpWritableStreamDefaultCo const JSC::ImplementationVisibility s_writableStreamInternalsSetUpWritableStreamDefaultControllerFromUnderlyingSinkCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_writableStreamInternalsSetUpWritableStreamDefaultControllerFromUnderlyingSinkCodeLength = 561; static const JSC::Intrinsic s_writableStreamInternalsSetUpWritableStreamDefaultControllerFromUnderlyingSinkCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsSetUpWritableStreamDefaultControllerFromUnderlyingSinkCode = "(function (C,_,v,E,F){\"use strict\";const f=new @WritableStreamDefaultController;let p=()=>{},q=()=>{return @Promise.@resolve()},x=()=>{return @Promise.@resolve()},B=()=>{return @Promise.@resolve()};if(\"start\"in v){const P=v.start;p=()=>@promiseInvokeOrNoopMethodNoCatch(_,P,[f])}if(\"write\"in v){const P=v.write;q=(j)=>@promiseInvokeOrNoopMethod(_,P,[j,f])}if(\"close\"in v){const P=v.close;x=()=>@promiseInvokeOrNoopMethod(_,P,[])}if(\"abort\"in v){const P=v.abort;B=(j)=>@promiseInvokeOrNoopMethod(_,P,[j])}@setUpWritableStreamDefaultController(C,f,p,q,x,B,E,F)})\n"; +const char* const s_writableStreamInternalsSetUpWritableStreamDefaultControllerFromUnderlyingSinkCode = "(function (C,O,_,E,F){\"use strict\";const f=new @WritableStreamDefaultController;let q=()=>{},v=()=>{return @Promise.@resolve()},x=()=>{return @Promise.@resolve()},B=()=>{return @Promise.@resolve()};if(\"start\"in _){const p=_.start;q=()=>@promiseInvokeOrNoopMethodNoCatch(O,p,[f])}if(\"write\"in _){const p=_.write;v=(j)=>@promiseInvokeOrNoopMethod(O,p,[j,f])}if(\"close\"in _){const p=_.close;x=()=>@promiseInvokeOrNoopMethod(O,p,[])}if(\"abort\"in _){const p=_.abort;B=(j)=>@promiseInvokeOrNoopMethod(O,p,[j])}@setUpWritableStreamDefaultController(C,f,q,v,x,B,E,F)})\n"; // writableStreamDefaultControllerAdvanceQueueIfNeeded const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultControllerAdvanceQueueIfNeededCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -646,17 +646,17 @@ const char* const s_processObjectInternalsBindingCode = "(function (I){\"use str const JSC::ConstructAbility s_processObjectInternalsGetStdioWriteStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_processObjectInternalsGetStdioWriteStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_processObjectInternalsGetStdioWriteStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_processObjectInternalsGetStdioWriteStreamCodeLength = 4250; +const int s_processObjectInternalsGetStdioWriteStreamCodeLength = 4311; static const JSC::Intrinsic s_processObjectInternalsGetStdioWriteStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_processObjectInternalsGetStdioWriteStreamCode = "(function (Z,Y){\"use strict\";var P={path:\"node:process\",require:Y},L=(M)=>P.require(M);function A(M){var{Duplex:B,eos:j,destroy:z}=L(\"node:stream\"),J=class O extends B{#j;#$;#M=!0;#N=!0;#J;#z;#B;#G;#H;#K;get isTTY(){return this.#K\?\?=L(\"node:tty\").isatty(M)}get fd(){return M}constructor(G){super({readable:!0,writable:!0});this.#J=`/dev/fd/${G}`}#L(G){const H=this.#z;if(this.#z=null,H)H(G);else if(G)this.destroy(G);else if(!this.#M&&!this.#N)this.destroy()}_destroy(G,H){if(!G&&this.#z!==null){var N=class X extends Error{code;name;constructor(Q=\"The operation was aborted\",K=void 0){if(K!==void 0&&typeof K!==\"object\")throw new Error(`Invalid AbortError options:\\n\\n${JSON.stringify(K,null,2)}`);super(Q,K);this.code=\"ABORT_ERR\",this.name=\"AbortError\"}};G=new N}if(this.#B=null,this.#G=null,this.#z===null)H(G);else{if(this.#z=H,this.#j)z(this.#j,G);if(this.#$)z(this.#$,G)}}_write(G,H,N){if(!this.#j){var{createWriteStream:X}=L(\"node:fs\"),Q=this.#j=X(this.#J);Q.on(\"finish\",()=>{if(this.#G){const K=this.#G;this.#G=null,K()}}),Q.on(\"drain\",()=>{if(this.#B){const K=this.#B;this.#B=null,K()}}),j(Q,(K)=>{if(this.#N=!1,K)z(Q,K);this.#L(K)})}if(Q.write(G,H))N();else this.#B=N}_final(G){this.#j&&this.#j.end(),this.#G=G}#O(){var{createReadStream:G}=L(\"node:fs\"),H=this.#$=G(this.#J);return H.on(\"readable\",()=>{if(this.#H){const N=this.#H;this.#H=null,N()}else this.read()}),H.on(\"end\",()=>{this.push(null)}),j(H,(N)=>{if(this.#M=!1,N)z(H,N);this.#L(N)}),H}_read(){var G=this.#$;if(!G)G=this.#O();while(!0){const H=G.read();if(H===null||!this.push(H))return}}};return new J(M)}var{EventEmitter:T}=L(\"node:events\");function V(M){if(!M)return!0;var B=M.toLowerCase();return B===\"utf8\"||B===\"utf-8\"||B===\"buffer\"||B===\"binary\"}var U,x=class M extends T{#j;#$;#M;#N;bytesWritten=0;setDefaultEncoding(B){if(this.#$||!V(B))return this.#B(),this.#$.setDefaultEncoding(B)}#J(){switch(this.#j){case 1:{var B=@Bun.stdout.writer({highWaterMark:0});return B.unref(),B}case 2:{var B=@Bun.stderr.writer({highWaterMark:0});return B.unref(),B}default:throw new Error(\"Unsupported writer\")}}#z(){return this.#M\?\?=this.#J()}constructor(B){super();this.#j=B}get fd(){return this.#j}get isTTY(){return this.#N\?\?=L(\"node:tty\").isatty(this.#j)}cursorTo(B,j,z){return(U\?\?=L(\"readline\")).cursorTo(this,B,j,z)}moveCursor(B,j,z){return(U\?\?=L(\"readline\")).moveCursor(this,B,j,z)}clearLine(B,j){return(U\?\?=L(\"readline\")).clearLine(this,B,j)}clearScreenDown(B){return(U\?\?=L(\"readline\")).clearScreenDown(this,B)}ref(){this.#z().ref()}unref(){this.#z().unref()}on(B,j){if(B===\"close\"||B===\"finish\")return this.#B(),this.#$.on(B,j);if(B===\"drain\")return super.on(\"drain\",j);if(B===\"error\")return super.on(\"error\",j);return super.on(B,j)}get _writableState(){return this.#B(),this.#$._writableState}get _readableState(){return this.#B(),this.#$._readableState}pipe(B){return this.#B(),this.#$.pipe(B)}unpipe(B){return this.#B(),this.#$.unpipe(B)}#B(){if(this.#$)return;this.#$=A(this.#j);const B=this.eventNames();for(let j of B)this.#$.on(j,(...z)=>{this.emit(j,...z)})}#G(B){var j=this.#z();const z=j.write(B);this.bytesWritten+=z;const J=j.flush(!1);return!!(z||J)}#H(B,j){if(!V(j))return this.#B(),this.#$.write(B,j);return this.#G(B)}#K(B,j){if(j)this.emit(\"error\",j);try{B(j\?j:null)}catch(z){this.emit(\"error\",z)}}#L(B,j,z){if(!V(j))return this.#B(),this.#$.write(B,j,z);var J=this.#z();const O=J.write(B),G=J.flush(!0);if(G\?.then)return G.then(()=>{this.#K(z),this.emit(\"drain\")},(H)=>this.#K(z,H)),!1;return queueMicrotask(()=>{this.#K(z)}),!!(O||G)}write(B,j,z){const J=this._write(B,j,z);if(J)this.emit(\"drain\");return J}get hasColors(){return @Bun.tty[this.#j].hasColors}_write(B,j,z){var J=this.#$;if(J)return J.write(B,j,z);switch(arguments.length){case 0:{var O=new Error(\"Invalid arguments\");throw O.code=\"ERR_INVALID_ARG_TYPE\",O}case 1:return this.#G(B);case 2:if(typeof j===\"function\")return this.#L(B,\"\",j);else if(typeof j===\"string\")return this.#H(B,j);default:{if(typeof j!==\"undefined\"&&typeof j!==\"string\"||typeof z!==\"undefined\"&&typeof z!==\"function\"){var O=new Error(\"Invalid arguments\");throw O.code=\"ERR_INVALID_ARG_TYPE\",O}if(typeof z===\"undefined\")return this.#H(B,j);return this.#L(B,j,z)}}}destroy(){return this}end(){return this}};return new x(Z)})\n"; +const char* const s_processObjectInternalsGetStdioWriteStreamCode = "(function (Z){\"use strict\";var L=(M)=>{var G=@requireMap.get(M);if(G)return G.exports;return @internalRequire(M)},D={path:\"node:process\",require:L};function Y(M){var{Duplex:G,eos:j,destroy:z}=L(\"node:stream\"),J=class O extends G{#j;#$;#M=!0;#N=!0;#J;#z;#G;#B;#H;#K;get isTTY(){return this.#K\?\?=L(\"node:tty\").isatty(M)}get fd(){return M}constructor(B){super({readable:!0,writable:!0});this.#J=`/dev/fd/${B}`}#L(B){const H=this.#z;if(this.#z=null,H)H(B);else if(B)this.destroy(B);else if(!this.#M&&!this.#N)this.destroy()}_destroy(B,H){if(!B&&this.#z!==null){var N=class X extends Error{code;name;constructor(Q=\"The operation was aborted\",K=void 0){if(K!==void 0&&typeof K!==\"object\")throw new Error(`Invalid AbortError options:\\n\\n${JSON.stringify(K,null,2)}`);super(Q,K);this.code=\"ABORT_ERR\",this.name=\"AbortError\"}};B=new N}if(this.#G=null,this.#B=null,this.#z===null)H(B);else{if(this.#z=H,this.#j)z(this.#j,B);if(this.#$)z(this.#$,B)}}_write(B,H,N){if(!this.#j){var{createWriteStream:X}=L(\"node:fs\"),Q=this.#j=X(this.#J);Q.on(\"finish\",()=>{if(this.#B){const K=this.#B;this.#B=null,K()}}),Q.on(\"drain\",()=>{if(this.#G){const K=this.#G;this.#G=null,K()}}),j(Q,(K)=>{if(this.#N=!1,K)z(Q,K);this.#L(K)})}if(Q.write(B,H))N();else this.#G=N}_final(B){this.#j&&this.#j.end(),this.#B=B}#O(){var{createReadStream:B}=L(\"node:fs\"),H=this.#$=B(this.#J);return H.on(\"readable\",()=>{if(this.#H){const N=this.#H;this.#H=null,N()}else this.read()}),H.on(\"end\",()=>{this.push(null)}),j(H,(N)=>{if(this.#M=!1,N)z(H,N);this.#L(N)}),H}_read(){var B=this.#$;if(!B)B=this.#O();while(!0){const H=B.read();if(H===null||!this.push(H))return}}};return new J(M)}var{EventEmitter:P}=L(\"node:events\");function V(M){if(!M)return!0;var G=M.toLowerCase();return G===\"utf8\"||G===\"utf-8\"||G===\"buffer\"||G===\"binary\"}var U,A=class M extends P{#j;#$;#M;#N;bytesWritten=0;setDefaultEncoding(G){if(this.#$||!V(G))return this.#G(),this.#$.setDefaultEncoding(G)}#J(){switch(this.#j){case 1:{var G=@Bun.stdout.writer({highWaterMark:0});return G.unref(),G}case 2:{var G=@Bun.stderr.writer({highWaterMark:0});return G.unref(),G}default:throw new Error(\"Unsupported writer\")}}#z(){return this.#M\?\?=this.#J()}constructor(G){super();this.#j=G}get fd(){return this.#j}get isTTY(){return this.#N\?\?=L(\"node:tty\").isatty(this.#j)}cursorTo(G,j,z){return(U\?\?=L(\"readline\")).cursorTo(this,G,j,z)}moveCursor(G,j,z){return(U\?\?=L(\"readline\")).moveCursor(this,G,j,z)}clearLine(G,j){return(U\?\?=L(\"readline\")).clearLine(this,G,j)}clearScreenDown(G){return(U\?\?=L(\"readline\")).clearScreenDown(this,G)}ref(){this.#z().ref()}unref(){this.#z().unref()}on(G,j){if(G===\"close\"||G===\"finish\")return this.#G(),this.#$.on(G,j);if(G===\"drain\")return super.on(\"drain\",j);if(G===\"error\")return super.on(\"error\",j);return super.on(G,j)}get _writableState(){return this.#G(),this.#$._writableState}get _readableState(){return this.#G(),this.#$._readableState}pipe(G){return this.#G(),this.#$.pipe(G)}unpipe(G){return this.#G(),this.#$.unpipe(G)}#G(){if(this.#$)return;this.#$=Y(this.#j);const G=this.eventNames();for(let j of G)this.#$.on(j,(...z)=>{this.emit(j,...z)})}#B(G){var j=this.#z();const z=j.write(G);this.bytesWritten+=z;const J=j.flush(!1);return!!(z||J)}#H(G,j){if(!V(j))return this.#G(),this.#$.write(G,j);return this.#B(G)}#K(G,j){if(j)this.emit(\"error\",j);try{G(j\?j:null)}catch(z){this.emit(\"error\",z)}}#L(G,j,z){if(!V(j))return this.#G(),this.#$.write(G,j,z);var J=this.#z();const O=J.write(G),B=J.flush(!0);if(B\?.then)return B.then(()=>{this.#K(z),this.emit(\"drain\")},(H)=>this.#K(z,H)),!1;return queueMicrotask(()=>{this.#K(z)}),!!(O||B)}write(G,j,z){const J=this._write(G,j,z);if(J)this.emit(\"drain\");return J}get hasColors(){return @Bun.tty[this.#j].hasColors}_write(G,j,z){var J=this.#$;if(J)return J.write(G,j,z);switch(arguments.length){case 0:{var O=new Error(\"Invalid arguments\");throw O.code=\"ERR_INVALID_ARG_TYPE\",O}case 1:return this.#B(G);case 2:if(typeof j===\"function\")return this.#L(G,\"\",j);else if(typeof j===\"string\")return this.#H(G,j);default:{if(typeof j!==\"undefined\"&&typeof j!==\"string\"||typeof z!==\"undefined\"&&typeof z!==\"function\"){var O=new Error(\"Invalid arguments\");throw O.code=\"ERR_INVALID_ARG_TYPE\",O}if(typeof z===\"undefined\")return this.#H(G,j);return this.#L(G,j,z)}}}destroy(){return this}end(){return this}};return new A(Z)})\n"; // getStdinStream const JSC::ConstructAbility s_processObjectInternalsGetStdinStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_processObjectInternalsGetStdinStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_processObjectInternalsGetStdinStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_processObjectInternalsGetStdinStreamCodeLength = 1799; +const int s_processObjectInternalsGetStdinStreamCodeLength = 1861; static const JSC::Intrinsic s_processObjectInternalsGetStdinStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_processObjectInternalsGetStdinStreamCode = "(function (L,N,P){\"use strict\";var Q={path:\"node:process\",require:N},J=(K)=>Q.require(K),{Duplex:T,eos:U,destroy:M}=J(\"node:stream\"),V=class K extends T{#K;#j;#Y;#H=!0;#I=!1;#L=!0;#z;#$;#G;get isTTY(){return J(\"tty\").isatty(L)}get fd(){return L}constructor(){super({readable:!0,writable:!0})}#J(Y){const j=this.#$;if(this.#$=null,j)j(Y);else if(Y)this.destroy(Y);else if(!this.#H&&!this.#L)this.destroy()}_destroy(Y,j){if(!Y&&this.#$!==null){var z=class G extends Error{constructor(H=\"The operation was aborted\",I=void 0){if(I!==void 0&&typeof I!==\"object\")throw new Error(`Invalid AbortError options:\\n\\n${JSON.stringify(I,null,2)}`);super(H,I);this.code=\"ABORT_ERR\",this.name=\"AbortError\"}};Y=new z}if(this.#$===null)j(Y);else if(this.#$=j,this.#Y)M(this.#Y,Y)}setRawMode(Y){}on(Y,j){if(Y===\"readable\")this.ref(),this.#I=!0;return super.on(Y,j)}pause(){return this.unref(),super.pause()}resume(){return this.ref(),super.resume()}ref(){this.#K\?\?=P.stdin.stream().getReader(),this.#j\?\?=setInterval(()=>{},1<<30)}unref(){if(this.#j)clearInterval(this.#j),this.#j=null}async#M(){try{var Y,j;const z=this.#K.readMany();if(!z\?.then)({done:Y,value:j}=z);else({done:Y,value:j}=await z);if(!Y){this.push(j[0]);const G=j.length;for(let H=1;H<G;H++)this.push(j[H])}else this.push(null),this.pause(),this.#H=!1,this.#J()}catch(z){this.#H=!1,this.#J(z)}}_read(Y){if(this.#I)this.unref(),this.#I=!1;this.#M()}#N(){var{createWriteStream:Y}=J(\"node:fs\"),j=this.#Y=Y(\"/dev/fd/0\");return j.on(\"finish\",()=>{if(this.#z){const z=this.#z;this.#z=null,z()}}),j.on(\"drain\",()=>{if(this.#G){const z=this.#G;this.#G=null,z()}}),U(j,(z)=>{if(this.#L=!1,z)M(j,z);this.#J(z)}),j}_write(Y,j,z){var G=this.#Y;if(!G)G=this.#N();if(G.write(Y,j))z();else this.#G=z}_final(Y){this.#Y.end(),this.#z=(...j)=>Y(...j)}};return new V})\n"; +const char* const s_processObjectInternalsGetStdinStreamCode = "(function (K){\"use strict\";var H=(I)=>{var N=@requireMap.get(I);if(N)return N.exports;return @internalRequire(I)},T={path:\"node:process\",require:H},{Duplex:M,eos:P,destroy:L}=H(\"node:stream\"),Q=class I extends M{#J;#j;#$;#G=!0;#H=!1;#K=!0;#z;#N;#B;get isTTY(){return H(\"tty\").isatty(K)}get fd(){return K}constructor(){super({readable:!0,writable:!0})}#I(N){const j=this.#N;if(this.#N=null,j)j(N);else if(N)this.destroy(N);else if(!this.#G&&!this.#K)this.destroy()}_destroy(N,j){if(!N&&this.#N!==null){var z=class B extends Error{constructor(G=\"The operation was aborted\",J=void 0){if(J!==void 0&&typeof J!==\"object\")throw new Error(`Invalid AbortError options:\\n\\n${JSON.stringify(J,null,2)}`);super(G,J);this.code=\"ABORT_ERR\",this.name=\"AbortError\"}};N=new z}if(this.#N===null)j(N);else if(this.#N=j,this.#$)L(this.#$,N)}setRawMode(N){}on(N,j){if(N===\"readable\")this.ref(),this.#H=!0;return super.on(N,j)}pause(){return this.unref(),super.pause()}resume(){return this.ref(),super.resume()}ref(){this.#J\?\?=@Bun.stdin.stream().getReader(),this.#j\?\?=setInterval(()=>{},1<<30)}unref(){if(this.#j)clearInterval(this.#j),this.#j=null}async#L(){try{var N,j;const z=this.#J.readMany();if(!z\?.then)({done:N,value:j}=z);else({done:N,value:j}=await z);if(!N){this.push(j[0]);const B=j.length;for(let G=1;G<B;G++)this.push(j[G])}else this.push(null),this.pause(),this.#G=!1,this.#I()}catch(z){this.#G=!1,this.#I(z)}}_read(N){if(this.#H)this.unref(),this.#H=!1;this.#L()}#M(){var{createWriteStream:N}=H(\"node:fs\"),j=this.#$=N(\"/dev/fd/0\");return j.on(\"finish\",()=>{if(this.#z){const z=this.#z;this.#z=null,z()}}),j.on(\"drain\",()=>{if(this.#B){const z=this.#B;this.#B=null,z()}}),P(j,(z)=>{if(this.#K=!1,z)L(j,z);this.#I(z)}),j}_write(N,j,z){var B=this.#$;if(!B)B=this.#M();if(B.write(N,j))z();else this.#B=z}_final(N){this.#$.end(),this.#z=(...j)=>N(...j)}};return new Q})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -2028,7 +2028,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 k=@getByIdDirectPrivate(this,\"ownerReadableStream\");if(!k)@throwTypeError(\"readMany() called on a reader owned by no readable stream\");const H=@getByIdDirectPrivate(k,\"state\");if(@putByIdDirectPrivate(k,\"disturbed\",!0),H===@streamClosed)return{value:[],size:0,done:!0};else if(H===@streamErrored)throw @getByIdDirectPrivate(k,\"storedError\");var w=@getByIdDirectPrivate(k,\"readableStreamController\"),E=@getByIdDirectPrivate(w,\"queue\");if(!E)return w.@pull(w).@then(function({done:_,value:B}){return _\?{done:!0,value:[],size:0}:{value:[B],size:1,done:!1}});const N=E.content;var O=E.size,A=N.toArray(!1),C=A.length;if(C>0){var j=@newArrayWithSize(C);if(@isReadableByteStreamController(w)){{const _=A[0];if(!(@ArrayBuffer.@isView(_)||_ instanceof @ArrayBuffer))@putByValDirect(j,0,new @Uint8Array(_.buffer,_.byteOffset,_.byteLength));else @putByValDirect(j,0,_)}for(var d=1;d<C;d++){const _=A[d];if(!(@ArrayBuffer.@isView(_)||_ instanceof @ArrayBuffer))@putByValDirect(j,d,new @Uint8Array(_.buffer,_.byteOffset,_.byteLength));else @putByValDirect(j,d,_)}}else{@putByValDirect(j,0,A[0].value);for(var d=1;d<C;d++)@putByValDirect(j,d,A[d].value)}if(@resetQueue(@getByIdDirectPrivate(w,\"queue\")),@getByIdDirectPrivate(w,\"closeRequested\"))@readableStreamClose(@getByIdDirectPrivate(w,\"controlledReadableStream\"));else if(@isReadableStreamDefaultController(w))@readableStreamDefaultControllerCallPullIfNeeded(w);else if(@isReadableByteStreamController(w))@readableByteStreamControllerCallPullIfNeeded(w);return{value:j,size:O,done:!1}}var J=(_)=>{if(_.done)return{value:[],size:0,done:!0};var B=@getByIdDirectPrivate(k,\"readableStreamController\"),F=@getByIdDirectPrivate(B,\"queue\"),x=[_.value].concat(F.content.toArray(!1)),K=x.length;if(@isReadableByteStreamController(B))for(var I=0;I<K;I++){const G=x[I];if(!(@ArrayBuffer.@isView(G)||G instanceof @ArrayBuffer)){const{buffer:S,byteOffset:T,byteLength:U}=G;@putByValDirect(x,I,new @Uint8Array(S,T,U))}}else for(var I=1;I<K;I++)@putByValDirect(x,I,x[I].value);var Q=F.size;if(@resetQueue(F),@getByIdDirectPrivate(B,\"closeRequested\"))@readableStreamClose(@getByIdDirectPrivate(B,\"controlledReadableStream\"));else if(@isReadableStreamDefaultController(B))@readableStreamDefaultControllerCallPullIfNeeded(B);else if(@isReadableByteStreamController(B))@readableByteStreamControllerCallPullIfNeeded(B);return{value:x,size:Q,done:!1}},D=w.@pull(w);if(D&&@isPromise(D))return D.@then(J);return J(D)})\n"; +const char* const s_readableStreamDefaultReaderReadManyCode = "(function (){\"use strict\";if(!@isReadableStreamDefaultReader(this))@throwTypeError(\"ReadableStreamDefaultReader.readMany() should not be called directly\");const j=@getByIdDirectPrivate(this,\"ownerReadableStream\");if(!j)@throwTypeError(\"readMany() called on a reader owned by no readable stream\");const I=@getByIdDirectPrivate(j,\"state\");if(@putByIdDirectPrivate(j,\"disturbed\",!0),I===@streamClosed)return{value:[],size:0,done:!0};else if(I===@streamErrored)throw @getByIdDirectPrivate(j,\"storedError\");var B=@getByIdDirectPrivate(j,\"readableStreamController\"),F=@getByIdDirectPrivate(B,\"queue\");if(!F)return B.@pull(B).@then(function({done:_,value:w}){return _\?{done:!0,value:[],size:0}:{value:[w],size:1,done:!1}});const N=F.content;var Q=F.size,x=N.toArray(!1),C=x.length;if(C>0){var D=@newArrayWithSize(C);if(@isReadableByteStreamController(B)){{const _=x[0];if(!(@ArrayBuffer.@isView(_)||_ instanceof @ArrayBuffer))@putByValDirect(D,0,new @Uint8Array(_.buffer,_.byteOffset,_.byteLength));else @putByValDirect(D,0,_)}for(var d=1;d<C;d++){const _=x[d];if(!(@ArrayBuffer.@isView(_)||_ instanceof @ArrayBuffer))@putByValDirect(D,d,new @Uint8Array(_.buffer,_.byteOffset,_.byteLength));else @putByValDirect(D,d,_)}}else{@putByValDirect(D,0,x[0].value);for(var d=1;d<C;d++)@putByValDirect(D,d,x[d].value)}if(@resetQueue(@getByIdDirectPrivate(B,\"queue\")),@getByIdDirectPrivate(B,\"closeRequested\"))@readableStreamClose(@getByIdDirectPrivate(B,\"controlledReadableStream\"));else if(@isReadableStreamDefaultController(B))@readableStreamDefaultControllerCallPullIfNeeded(B);else if(@isReadableByteStreamController(B))@readableByteStreamControllerCallPullIfNeeded(B);return{value:D,size:Q,done:!1}}var J=(_)=>{if(_.done)return{value:[],size:0,done:!0};var w=@getByIdDirectPrivate(j,\"readableStreamController\"),G=@getByIdDirectPrivate(w,\"queue\"),k=[_.value].concat(G.content.toArray(!1)),K=k.length;if(@isReadableByteStreamController(w))for(var A=0;A<K;A++){const H=k[A];if(!(@ArrayBuffer.@isView(H)||H instanceof @ArrayBuffer)){const{buffer:T,byteOffset:U,byteLength:W}=H;@putByValDirect(k,A,new @Uint8Array(T,U,W))}}else for(var A=1;A<K;A++)@putByValDirect(k,A,k[A].value);var S=G.size;if(@resetQueue(G),@getByIdDirectPrivate(w,\"closeRequested\"))@readableStreamClose(@getByIdDirectPrivate(w,\"controlledReadableStream\"));else if(@isReadableStreamDefaultController(w))@readableStreamDefaultControllerCallPullIfNeeded(w);else if(@isReadableByteStreamController(w))@readableByteStreamControllerCallPullIfNeeded(w);return{value:k,size:S,done:!1}},E=B.@pull(B);if(E&&@isPromise(E))return E.@then(J);return J(E)})\n"; // read const JSC::ConstructAbility s_readableStreamDefaultReaderReadCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2132,9 +2132,9 @@ const char* const s_streamInternalsValidateAndNormalizeQueuingStrategyCode = "(f const JSC::ConstructAbility s_streamInternalsCreateFIFOCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_streamInternalsCreateFIFOCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_streamInternalsCreateFIFOCodeImplementationVisibility = JSC::ImplementationVisibility::Private; -const int s_streamInternalsCreateFIFOCodeLength = 1472; +const int s_streamInternalsCreateFIFOCodeLength = 1473; static const JSC::Intrinsic s_streamInternalsCreateFIFOCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_streamInternalsCreateFIFOCode = "(function (){\"use strict\";var E=@Array.prototype.slice;class A{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._head<this._tail)return this._tail-this._head;else return this._capacityMask+1-(this._head-this._tail)}isEmpty(){return this.size()==0}isNotEmpty(){return this.size()>0}shift(){var{_head:v,_tail:b,_list:g,_capacityMask:k}=this;if(v===b)return @undefined;var w=g[v];if(@putByValDirect(g,v,@undefined),v=this._head=v+1&k,v<2&&b>1e4&&b<=g.length>>>2)this._shrinkArray();return w}peek(){if(this._head===this._tail)return @undefined;return this._list[this._head]}push(v){var b=this._tail;if(@putByValDirect(this._list,b,v),this._tail=b+1&this._capacityMask,this._tail===this._head)this._growArray()}toArray(v){var b=this._list,g=@toLength(b.length);if(v||this._head>this._tail){var k=@toLength(this._head),w=@toLength(this._tail),F=@toLength(g-k+w),z=@newArrayWithSize(F),B=0;for(var x=k;x<g;x++)@putByValDirect(z,B++,b[x]);for(var x=0;x<w;x++)@putByValDirect(z,B++,b[x]);return z}else return E.@call(b,this._head,this._tail)}clear(){this._head=0,this._tail=0,this._list.fill(@undefined)}_growArray(){if(this._head)this._list=this.toArray(!0),this._head=0;this._tail=@toLength(this._list.length),this._list.length<<=1,this._capacityMask=this._capacityMask<<1|1}shrinkArray(){this._list.length>>>=1,this._capacityMask>>>=1}}return new A})\n"; +const char* const s_streamInternalsCreateFIFOCode = "(function (){\"use strict\";var E=@Array.prototype.slice;class A{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._head<this._tail)return this._tail-this._head;else return this._capacityMask+1-(this._head-this._tail)}isEmpty(){return this.size()==0}isNotEmpty(){return this.size()>0}shift(){var{_head:g,_tail:b,_list:x,_capacityMask:M}=this;if(g===b)return @undefined;var w=x[g];if(@putByValDirect(x,g,@undefined),g=this._head=g+1&M,g<2&&b>1e4&&b<=x.length>>>2)this._shrinkArray();return w}peek(){if(this._head===this._tail)return @undefined;return this._list[this._head]}push(g){var b=this._tail;if(@putByValDirect(this._list,b,g),this._tail=b+1&this._capacityMask,this._tail===this._head)this._growArray()}toArray(g){var b=this._list,x=@toLength(b.length);if(g||this._head>this._tail){var M=@toLength(this._head),w=@toLength(this._tail),F=@toLength(x-M+w),z=@newArrayWithSize(F),B=0;for(var v=M;v<x;v++)@putByValDirect(z,B++,b[v]);for(var v=0;v<w;v++)@putByValDirect(z,B++,b[v]);return z}else return E.@call(b,this._head,this._tail)}clear(){this._head=0,this._tail=0,this._list.fill(@undefined)}_growArray(){if(this._head)this._list=this.toArray(!0),this._head=0;this._tail=@toLength(this._list.length),this._list.length<<=1,this._capacityMask=this._capacityMask<<1|1}_shrinkArray(){this._list.length>>>=1,this._capacityMask>>>=1}}return new A})\n"; // newQueue const JSC::ConstructAbility s_streamInternalsNewQueueCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; diff --git a/src/js/out/WebCoreJSBuiltins.h b/src/js/out/WebCoreJSBuiltins.h index d00ae735e..42d14b154 100644 --- a/src/js/out/WebCoreJSBuiltins.h +++ b/src/js/out/WebCoreJSBuiltins.h @@ -1181,8 +1181,8 @@ extern const JSC::ImplementationVisibility s_processObjectInternalsGetStdinStrea #define WEBCORE_FOREACH_PROCESSOBJECTINTERNALS_BUILTIN_DATA(macro) \ macro(binding, processObjectInternalsBinding, 1) \ - macro(getStdioWriteStream, processObjectInternalsGetStdioWriteStream, 2) \ - macro(getStdinStream, processObjectInternalsGetStdinStream, 3) \ + macro(getStdioWriteStream, processObjectInternalsGetStdioWriteStream, 1) \ + macro(getStdinStream, processObjectInternalsGetStdinStream, 1) \ #define WEBCORE_FOREACH_PROCESSOBJECTINTERNALS_BUILTIN_CODE(macro) \ macro(processObjectInternalsBindingCode, binding, ASCIILiteral(), s_processObjectInternalsBindingCodeLength) \ diff --git a/src/js/out/modules/node/http.js b/src/js/out/modules/node/http.js index f07dcc2e0..13ee7fded 100644 --- a/src/js/out/modules/node/http.js +++ b/src/js/out/modules/node/http.js @@ -14,6 +14,14 @@ var checkInvalidHeaderChar = function(val) { return !1; return !0; } +}, validateMsecs = function(numberlike, field) { + if (typeof numberlike !== "number" || numberlike < 0) + throw new ERR_INVALID_ARG_TYPE(field, "number", numberlike); + return numberlike; +}, validateFunction = function(callable, field) { + if (typeof callable !== "function") + throw new ERR_INVALID_ARG_TYPE(field, "Function", callable); + return callable; }, getHeader = function(headers, name) { if (!headers) return; @@ -108,7 +116,15 @@ var headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/, validateHeaderName = (name, lab 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 { +}, __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); + +class ERR_INVALID_ARG_TYPE extends TypeError { + constructor(name, expected, actual) { + super(`The ${name} argument must be of type ${expected}. Received type ${typeof actual}`); + this.code = "ERR_INVALID_ARG_TYPE"; + } +} +var FakeSocket = class Socket extends Duplex { bytesRead = 0; bytesWritten = 0; connecting = !1; @@ -514,10 +530,11 @@ class OutgoingMessage extends Writable { headersSent = !1; sendDate = !0; req; + timeout; #finished = !1; [kEndCalled] = !1; #fakeSocket; - #timeoutTimer = null; + #timeoutTimer; [kAbortController] = null; _implicitHeader() { } @@ -592,16 +609,21 @@ class OutgoingMessage extends Writable { } [kClearTimeout]() { if (this.#timeoutTimer) - clearTimeout(this.#timeoutTimer), this.#timeoutTimer = null; + clearTimeout(this.#timeoutTimer), this.removeAllListeners("timeout"), this.#timeoutTimer = void 0; + } + #onTimeout() { + this.#timeoutTimer = void 0, this[kAbortController]?.abort(), this.emit("timeout"); } setTimeout(msecs, callback) { - if (this.#timeoutTimer) + if (this.destroyed) return this; - if (callback) - this.on("timeout", callback); - return this.#timeoutTimer = setTimeout(async () => { - this.#timeoutTimer = null, this[kAbortController]?.abort(), this.emit("timeout"); - }, msecs), this; + if (this.timeout = msecs = validateMsecs(msecs, "msecs"), clearTimeout(this.#timeoutTimer), msecs === 0) { + if (callback !== void 0) + validateFunction(callback, "callback"), this.removeListener("timeout", callback); + this.#timeoutTimer = void 0; + } else if (this.#timeoutTimer = setTimeout(this.#onTimeout.bind(this), msecs).unref(), callback !== void 0) + validateFunction(callback, "callback"), this.once("timeout", callback); + return this; } } @@ -780,7 +802,7 @@ class ClientRequest extends OutgoingMessage { #fetchRequest; #signal = null; [kAbortController] = null; - #timeoutTimer = null; + #timeoutTimer = void 0; #options; #finished; get path() { @@ -827,7 +849,8 @@ class ClientRequest extends OutgoingMessage { body: body && method !== "GET" && method !== "HEAD" && method !== "OPTIONS" ? body : void 0, redirect: "manual", verbose: Boolean(__DEBUG__), - signal: this[kAbortController].signal + signal: this[kAbortController].signal, + timeout: !1 }).then((response) => { var res = this.#res = new IncomingMessage(response, { type: "response", @@ -910,8 +933,7 @@ class ClientRequest extends OutgoingMessage { 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"; - if (this.#socketPath = options.socketPath, options.timeout !== void 0) - this.setTimeout(options.timeout, null); + this.#socketPath = options.socketPath; const signal = options.signal; if (signal) signal.addEventListener("abort", () => { @@ -932,7 +954,11 @@ class ClientRequest extends OutgoingMessage { var _joinDuplicateHeaders = options.joinDuplicateHeaders; if (this.#joinDuplicateHeaders = _joinDuplicateHeaders, this.#path = options.path || "/", cb) this.once("response", cb); - if (__DEBUG__ && debug(`new ClientRequest: ${this.#method} ${this.#protocol}//${this.#host}:${this.#port}${this.#path}`), this.#finished = !1, this.#res = null, this.#upgradeOrConnect = !1, this.#parser = null, this.#maxHeadersCount = null, this.#reusedSocket = !1, this.#host = host, this.#protocol = protocol, this.#timeoutTimer = null, !ArrayIsArray(headers)) { + __DEBUG__ && debug(`new ClientRequest: ${this.#method} ${this.#protocol}//${this.#host}:${this.#port}${this.#path}`), this.#finished = !1, this.#res = null, this.#upgradeOrConnect = !1, this.#parser = null, this.#maxHeadersCount = null, this.#reusedSocket = !1, this.#host = host, this.#protocol = protocol; + var timeout = options.timeout; + if (timeout !== void 0 && timeout !== 0) + this.setTimeout(timeout, void 0); + if (!ArrayIsArray(headers)) { var headers = options.headers; if (headers) for (let key in headers) @@ -941,13 +967,8 @@ class ClientRequest extends OutgoingMessage { if (auth && !this.getHeader("Authorization")) this.setHeader("Authorization", "Basic " + Buffer.from(auth).toString("base64")); } - var optsWithoutSignal = options; - if (optsWithoutSignal.signal) - optsWithoutSignal = ObjectAssign({}, options), delete optsWithoutSignal.signal; + var { signal: _signal, ...optsWithoutSignal } = options; this.#options = optsWithoutSignal; - var timeout = options.timeout; - if (timeout) - this.setTimeout(timeout); } setSocketKeepAlive(enable = !0, initialDelay = 0) { __DEBUG__ && debug(`${NODE_HTTP_WARNING}\n`, "WARN: ClientRequest.setSocketKeepAlive is a no-op"); @@ -957,16 +978,21 @@ class ClientRequest extends OutgoingMessage { } [kClearTimeout]() { if (this.#timeoutTimer) - clearTimeout(this.#timeoutTimer), this.#timeoutTimer = null; + clearTimeout(this.#timeoutTimer), this.#timeoutTimer = void 0, this.removeAllListeners("timeout"); + } + #onTimeout() { + this.#timeoutTimer = void 0, this[kAbortController]?.abort(), this.emit("timeout"); } setTimeout(msecs, callback) { - if (this.#timeoutTimer) + if (this.destroyed) return this; - if (callback) - this.on("timeout", callback); - return this.#timeoutTimer = setTimeout(async () => { - this.#timeoutTimer = null, this[kAbortController]?.abort(), this.emit("timeout"); - }, msecs), this; + if (this.timeout = msecs = validateMsecs(msecs, "msecs"), clearTimeout(this.#timeoutTimer), msecs === 0) { + if (callback !== void 0) + validateFunction(callback, "callback"), this.removeListener("timeout", callback); + this.#timeoutTimer = void 0; + } else if (this.#timeoutTimer = setTimeout(this.#onTimeout.bind(this), msecs).unref(), callback !== void 0) + validateFunction(callback, "callback"), this.once("timeout", callback); + return this; } } var tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/, METHODS = [ diff --git a/src/js/out/modules/node/stream.js b/src/js/out/modules/node/stream.js index f7e94b00d..0497ffd82 100644 --- a/src/js/out/modules/node/stream.js +++ b/src/js/out/modules/node/stream.js @@ -1,2 +1,2 @@ -import{EventEmitter as Tq} from"bun:events_native";import{StringDecoder as rq} from"node:string_decoder";var qQ=function(t){return typeof t==="object"&&t!==null&&t instanceof ReadableStream},QQ=function(t,M){if(typeof t!=="boolean")throw new XQ(M,"boolean",t)};var XQ=function(t,M,B){return new Error(`The argument '${t}' is invalid. Received '${B}' for type '${M}'`)},JQ=function(t,M,B){return new Error(`The value '${M}' is invalid for argument '${t}'. Reason: ${B}`)},zQ=function(t,M){var[B,F,y,I,j,R,x]=globalThis[Symbol.for("Bun.lazy")](t),g=[!1],f=function(P,A,K,U){if(A>0){const T=K.subarray(0,A),C=K.subarray(A);if(T.byteLength>0)P.push(T);if(U)P.push(null);return C.byteLength>0?C:void 0}if(U)P.push(null);return K},c=function(P,A,K,U){if(A.byteLength>0)P.push(A);if(U)P.push(null);return K},_=process.env.BUN_DISABLE_DYNAMIC_CHUNK_SIZE!=="1";const i=new FinalizationRegistry((P)=>P&&j(P)),D=512;var p=class P extends M{#q;#Q=1;#X=!1;#H=void 0;#J;#K=!1;#Z=!_;#B;constructor(A,K={}){super(K);if(typeof K.highWaterMark==="number")this.#J=K.highWaterMark;else this.#J=262144;this.#q=A,this.#X=!1,this.#H=void 0,this.#K=!1,this.#B={},i.register(this,this.#q,this.#B)}_read(A){if(n&&d("NativeReadable._read",this.__id),this.#K){n&&d("pendingRead is true",this.__id);return}var K=this.#q;if(n&&d("ptr @ NativeReadable._read",K,this.__id),K===0){this.push(null);return}if(!this.#X)n&&d("NativeReadable not constructed yet",this.__id),this.#$(K);return this.#V(this.#z(A),K)}#$(A){this.#X=!0;const K=F(A,this.#J);if(n&&d("NativeReadable internal `start` result",K,this.__id),typeof K==="number"&&K>1)this.#Z=!0,n&&d("NativeReadable resized",this.__id),this.#J=Math.min(this.#J,K);if(x){const U=x(A);if(n&&d("NativeReadable drain result",U,this.__id),(U?.byteLength??0)>0)this.push(U)}}#z(A=this.#J){var K=this.#H;if(n&&d("chunk @ #getRemainingChunk",K,this.__id),K?.byteLength??0<D){var U=A>D?A:D;this.#H=K=new Buffer(U)}return K}push(A,K){return n&&d("NativeReadable push -- result, encoding",A,K,this.__id),super.push(...arguments)}#Y(A,K,U){if(n&&d("result, isClosed @ #handleResult",A,U,this.__id),typeof A==="number"){if(A>=this.#J&&!this.#Z&&!U)this.#J*=2,this.#Z=!0;return f(this,A,K,U)}else if(typeof A==="boolean")return this.push(null),K?.byteLength??0>0?K:void 0;else if(ArrayBuffer.isView(A)){if(A.byteLength>=this.#J&&!this.#Z&&!U)this.#J*=2,this.#Z=!0,n&&d("Resized",this.__id);return c(this,A,K,U)}else throw n&&d("Unknown result type",A,this.__id),new Error("Invalid result from pull")}#V(A,K){n&&d("#internalRead()",this.__id),g[0]=!1;var U=B(K,A,g);if(Oq(U))return this.#K=!0,U.then((T)=>{this.#K=!1,n&&d("pending no longerrrrrrrr (result returned from pull)",this.__id),this.#H=this.#Y(T,A,g[0])},(T)=>{n&&d("error from pull",T,this.__id),errorOrDestroy(this,T)});else this.#H=this.#Y(U,A,g[0])}_destroy(A,K){var U=this.#q;if(U===0){K(A);return}if(i.unregister(this.#B),this.#q=0,R)R(U,!1);n&&d("NativeReadable destroyed",this.__id),y(U,A),K(A)}ref(){var A=this.#q;if(A===0)return;if(this.#Q++===0)R(A,!0)}unref(){var A=this.#q;if(A===0)return;if(this.#Q--===1)R(A,!1)}};if(!R)p.prototype.ref=void 0,p.prototype.unref=void 0;return p},iq=function(t,M){return VQ[t]||=zQ(t,M)},UQ=function(t,M,B){if(!(M&&typeof M==="object"&&M instanceof ReadableStream))return;const F=aq(M);if(!F){d("no native readable stream");return}const{stream:y,data:I}=F;return new(iq(I,t))(y,B)},{isPromise:Oq,isCallable:sq,direct:aq,Object:Uq}=globalThis[Symbol.for("Bun.lazy")]("primordials");globalThis.__IDS_TO_TRACK=process.env.DEBUG_TRACK_EE?.length?process.env.DEBUG_TRACK_EE.split(","):process.env.DEBUG_STREAMS?.length?process.env.DEBUG_STREAMS.split(","):null;var tq=!!process.env.DEBUG_TRACK_EE,n=!!(process.env.DEBUG||process.env.DEBUG_STREAMS||tq),d=n?globalThis.__IDS_TO_TRACK?(...t)=>{const M=t[t.length-1];if(!globalThis.__IDS_TO_TRACK.includes(M))return;console.log(`ID: ${M}`,...t.slice(0,-1))}:(...t)=>console.log(...t.slice(0,-1)):()=>{},FQ=Uq.create,LQ=Uq.defineProperty,jQ=Uq.getOwnPropertyDescriptor,eq=Uq.getOwnPropertyNames,NQ=Uq.getPrototypeOf,AQ=Uq.prototype.hasOwnProperty,EQ=Uq.setPrototypeOf,$q=(t,M)=>function B(){return M||(0,t[eq(t)[0]])((M={exports:{}}).exports,M),M.exports};var Hq=process.nextTick;var IQ=Array.isArray,Wq=$q({"node_modules/readable-stream/lib/ours/primordials.js"(t,M){M.exports={ArrayIsArray(B){return Array.isArray(B)},ArrayPrototypeIncludes(B,F){return B.includes(F)},ArrayPrototypeIndexOf(B,F){return B.indexOf(F)},ArrayPrototypeJoin(B,F){return B.join(F)},ArrayPrototypeMap(B,F){return B.map(F)},ArrayPrototypePop(B,F){return B.pop(F)},ArrayPrototypePush(B,F){return B.push(F)},ArrayPrototypeSlice(B,F,y){return B.slice(F,y)},Error,FunctionPrototypeCall(B,F,...y){return B.call(F,...y)},FunctionPrototypeSymbolHasInstance(B,F){return Function.prototype[Symbol.hasInstance].call(B,F)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(B,F){return Uq.defineProperties(B,F)},ObjectDefineProperty(B,F,y){return Uq.defineProperty(B,F,y)},ObjectGetOwnPropertyDescriptor(B,F){return Uq.getOwnPropertyDescriptor(B,F)},ObjectKeys(B){return Uq.keys(B)},ObjectSetPrototypeOf(B,F){return Uq.setPrototypeOf(B,F)},Promise,PromisePrototypeCatch(B,F){return B.catch(F)},PromisePrototypeThen(B,F,y){return B.then(F,y)},PromiseReject(B){return Promise.reject(B)},ReflectApply:Reflect.apply,RegExpPrototypeTest(B,F){return B.test(F)},SafeSet:Set,String,StringPrototypeSlice(B,F,y){return B.slice(F,y)},StringPrototypeToLowerCase(B){return B.toLowerCase()},StringPrototypeToUpperCase(B){return B.toUpperCase()},StringPrototypeTrim(B){return B.trim()},Symbol,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,TypedArrayPrototypeSet(B,F,y){return B.set(F,y)},Uint8Array}}}),Eq=$q({"node_modules/readable-stream/lib/ours/util.js"(t,M){var B=Uq.getPrototypeOf(async function(){}).constructor,F=typeof Blob!=="undefined"?function I(j){return j instanceof Blob}:function I(j){return!1},y=class extends Error{constructor(I){if(!Array.isArray(I))throw new TypeError(`Expected input to be an Array, got ${typeof I}`);let j="";for(let R=0;R<I.length;R++)j+=` ${I[R].stack} -`;super(j);this.name="AggregateError",this.errors=I}};M.exports={AggregateError:y,once(I){let j=!1;return function(...R){if(j)return;j=!0,I.apply(this,R)}},createDeferredPromise:function(){let I,j;return{promise:new Promise((x,g)=>{I=x,j=g}),resolve:I,reject:j}},promisify(I){return new Promise((j,R)=>{I((x,...g)=>{if(x)return R(x);return j(...g)})})},debuglog(){return function(){}},format(I,...j){return I.replace(/%([sdifj])/g,function(...[R,x]){const g=j.shift();if(x==="f")return g.toFixed(6);else if(x==="j")return JSON.stringify(g);else if(x==="s"&&typeof g==="object")return`${g.constructor!==Uq?g.constructor.name:""} {}`.trim();else return g.toString()})},inspect(I){switch(typeof I){case"string":if(I.includes("'")){if(!I.includes('"'))return`"${I}"`;else if(!I.includes("`")&&!I.includes("${"))return`\`${I}\``}return`'${I}'`;case"number":if(isNaN(I))return"NaN";else if(Uq.is(I,-0))return String(I);return I;case"bigint":return`${String(I)}n`;case"boolean":case"undefined":return String(I);case"object":return"{}"}},types:{isAsyncFunction(I){return I instanceof B},isArrayBufferView(I){return ArrayBuffer.isView(I)}},isBlob:F},M.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}}),Mq=$q({"node_modules/readable-stream/lib/ours/errors.js"(t,M){var{format:B,inspect:F,AggregateError:y}=Eq(),I=globalThis.AggregateError||y,j=Symbol("kIsNodeError"),R=["string","function","number","object","Function","Object","boolean","bigint","symbol"],x=/^([A-Z][a-z0-9]*)+$/,g="__node_internal_",f={};function c(K,U){if(!K)throw new f.ERR_INTERNAL_ASSERTION(U)}function _(K){let U="",T=K.length;const C=K[0]==="-"?1:0;for(;T>=C+4;T-=3)U=`_${K.slice(T-3,T)}${U}`;return`${K.slice(0,T)}${U}`}function i(K,U,T){if(typeof U==="function")return c(U.length<=T.length,`Code: ${K}; The provided arguments length (${T.length}) does not match the required ones (${U.length}).`),U(...T);const C=(U.match(/%[dfijoOs]/g)||[]).length;if(c(C===T.length,`Code: ${K}; The provided arguments length (${T.length}) does not match the required ones (${C}).`),T.length===0)return U;return B(U,...T)}function D(K,U,T){if(!T)T=Error;class C extends T{constructor(...qq){super(i(K,U,qq))}toString(){return`${this.name} [${K}]: ${this.message}`}}Uq.defineProperties(C.prototype,{name:{value:T.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${K}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),C.prototype.code=K,C.prototype[j]=!0,f[K]=C}function p(K){const U=g+K.name;return Uq.defineProperty(K,"name",{value:U}),K}function P(K,U){if(K&&U&&K!==U){if(Array.isArray(U.errors))return U.errors.push(K),U;const T=new I([U,K],U.message);return T.code=U.code,T}return K||U}var A=class extends Error{constructor(K="The operation was aborted",U=void 0){if(U!==void 0&&typeof U!=="object")throw new f.ERR_INVALID_ARG_TYPE("options","Object",U);super(K,U);this.code="ABORT_ERR",this.name="AbortError"}};D("ERR_ASSERTION","%s",Error),D("ERR_INVALID_ARG_TYPE",(K,U,T)=>{if(c(typeof K==="string","'name' must be a string"),!Array.isArray(U))U=[U];let C="The ";if(K.endsWith(" argument"))C+=`${K} `;else C+=`"${K}" ${K.includes(".")?"property":"argument"} `;C+="must be ";const qq=[],o=[],$=[];for(let Y of U)if(c(typeof Y==="string","All expected entries have to be of type string"),R.includes(Y))qq.push(Y.toLowerCase());else if(x.test(Y))o.push(Y);else c(Y!=="object",'The value "object" should be written as "Object"'),$.push(Y);if(o.length>0){const Y=qq.indexOf("object");if(Y!==-1)qq.splice(qq,Y,1),o.push("Object")}if(qq.length>0){switch(qq.length){case 1:C+=`of type ${qq[0]}`;break;case 2:C+=`one of type ${qq[0]} or ${qq[1]}`;break;default:{const Y=qq.pop();C+=`one of type ${qq.join(", ")}, or ${Y}`}}if(o.length>0||$.length>0)C+=" or "}if(o.length>0){switch(o.length){case 1:C+=`an instance of ${o[0]}`;break;case 2:C+=`an instance of ${o[0]} or ${o[1]}`;break;default:{const Y=o.pop();C+=`an instance of ${o.join(", ")}, or ${Y}`}}if($.length>0)C+=" or "}switch($.length){case 0:break;case 1:if($[0].toLowerCase()!==$[0])C+="an ";C+=`${$[0]}`;break;case 2:C+=`one of ${$[0]} or ${$[1]}`;break;default:{const Y=$.pop();C+=`one of ${$.join(", ")}, or ${Y}`}}if(T==null)C+=`. Received ${T}`;else if(typeof T==="function"&&T.name)C+=`. Received function ${T.name}`;else if(typeof T==="object"){var s;if((s=T.constructor)!==null&&s!==void 0&&s.name)C+=`. Received an instance of ${T.constructor.name}`;else{const Y=F(T,{depth:-1});C+=`. Received ${Y}`}}else{let Y=F(T,{colors:!1});if(Y.length>25)Y=`${Y.slice(0,25)}...`;C+=`. Received type ${typeof T} (${Y})`}return C},TypeError),D("ERR_INVALID_ARG_VALUE",(K,U,T="is invalid")=>{let C=F(U);if(C.length>128)C=C.slice(0,128)+"...";return`The ${K.includes(".")?"property":"argument"} '${K}' ${T}. Received ${C}`},TypeError),D("ERR_INVALID_RETURN_VALUE",(K,U,T)=>{var C;const qq=T!==null&&T!==void 0&&(C=T.constructor)!==null&&C!==void 0&&C.name?`instance of ${T.constructor.name}`:`type ${typeof T}`;return`Expected ${K} to be returned from the "${U}" function but got ${qq}.`},TypeError),D("ERR_MISSING_ARGS",(...K)=>{c(K.length>0,"At least one arg needs to be specified");let U;const T=K.length;switch(K=(Array.isArray(K)?K:[K]).map((C)=>`"${C}"`).join(" or "),T){case 1:U+=`The ${K[0]} argument`;break;case 2:U+=`The ${K[0]} and ${K[1]} arguments`;break;default:{const C=K.pop();U+=`The ${K.join(", ")}, and ${C} arguments`}break}return`${U} must be specified`},TypeError),D("ERR_OUT_OF_RANGE",(K,U,T)=>{c(U,'Missing "range" argument');let C;if(Number.isInteger(T)&&Math.abs(T)>4294967296)C=_(String(T));else if(typeof T==="bigint"){if(C=String(T),T>2n**32n||T<-(2n**32n))C=_(C);C+="n"}else C=F(T);return`The value of "${K}" is out of range. It must be ${U}. Received ${C}`},RangeError),D("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),D("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),D("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),D("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),D("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),D("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),D("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),D("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),D("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),D("ERR_STREAM_WRITE_AFTER_END","write after end",Error),D("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),M.exports={AbortError:A,aggregateTwoErrors:p(P),hideStackFrames:p,codes:f}}}),Cq=$q({"node_modules/readable-stream/lib/internal/validators.js"(t,M){var{ArrayIsArray:B,ArrayPrototypeIncludes:F,ArrayPrototypeJoin:y,ArrayPrototypeMap:I,NumberIsInteger:j,NumberMAX_SAFE_INTEGER:R,NumberMIN_SAFE_INTEGER:x,NumberParseInt:g,RegExpPrototypeTest:f,String:c,StringPrototypeToUpperCase:_,StringPrototypeTrim:i}=Wq(),{hideStackFrames:D,codes:{ERR_SOCKET_BAD_PORT:p,ERR_INVALID_ARG_TYPE:P,ERR_INVALID_ARG_VALUE:A,ERR_OUT_OF_RANGE:K,ERR_UNKNOWN_SIGNAL:U}}=Mq(),{normalizeEncoding:T}=Eq(),{isAsyncFunction:C,isArrayBufferView:qq}=Eq().types,o={};function $(V){return V===(V|0)}function s(V){return V===V>>>0}var Y=/^[0-7]+$/,Z="must be a 32-bit unsigned integer or an octal string";function N(V,h,X){if(typeof V==="undefined")V=X;if(typeof V==="string"){if(!f(Y,V))throw new A(h,V,Z);V=g(V,8)}return u(V,h,0,4294967295),V}var m=D((V,h,X=x,H=R)=>{if(typeof V!=="number")throw new P(h,"number",V);if(!j(V))throw new K(h,"an integer",V);if(V<X||V>H)throw new K(h,`>= ${X} && <= ${H}`,V)}),u=D((V,h,X=-2147483648,H=2147483647)=>{if(typeof V!=="number")throw new P(h,"number",V);if(!$(V)){if(!j(V))throw new K(h,"an integer",V);throw new K(h,`>= ${X} && <= ${H}`,V)}if(V<X||V>H)throw new K(h,`>= ${X} && <= ${H}`,V)}),J=D((V,h,X)=>{if(typeof V!=="number")throw new P(h,"number",V);if(!s(V)){if(!j(V))throw new K(h,"an integer",V);throw new K(h,`>= ${X?1:0} && < 4294967296`,V)}if(X&&V===0)throw new K(h,">= 1 && < 4294967296",V)});function z(V,h){if(typeof V!=="string")throw new P(h,"string",V)}function w(V,h){if(typeof V!=="number")throw new P(h,"number",V)}var S=D((V,h,X)=>{if(!F(X,V)){const L="must be one of: "+y(I(X,(l)=>typeof l==="string"?`'${l}'`:c(l)),", ");throw new A(h,V,L)}});function E(V,h){if(typeof V!=="boolean")throw new P(h,"boolean",V)}var W=D((V,h,X)=>{const H=X==null,L=H?!1:X.allowArray,l=H?!1:X.allowFunction;if(!(H?!1:X.nullable)&&V===null||!L&&B(V)||typeof V!=="object"&&(!l||typeof V!=="function"))throw new P(h,"Object",V)}),b=D((V,h,X=0)=>{if(!B(V))throw new P(h,"Array",V);if(V.length<X){const H=`must be longer than ${X}`;throw new A(h,V,H)}});function a(V,h="signal"){if(z(V,h),o[V]===void 0){if(o[_(V)]!==void 0)throw new U(V+" (signals must use all capital letters)");throw new U(V)}}var r=D((V,h="buffer")=>{if(!qq(V))throw new P(h,["Buffer","TypedArray","DataView"],V)});function Qq(V,h){const X=T(h),H=V.length;if(X==="hex"&&H%2!==0)throw new A("encoding",h,`is invalid for data of length ${H}`)}function Zq(V,h="Port",X=!0){if(typeof V!=="number"&&typeof V!=="string"||typeof V==="string"&&i(V).length===0||+V!==+V>>>0||V>65535||V===0&&!X)throw new p(h,V,X);return V|0}var Vq=D((V,h)=>{if(V!==void 0&&(V===null||typeof V!=="object"||!("aborted"in V)))throw new P(h,"AbortSignal",V)}),Xq=D((V,h)=>{if(typeof V!=="function")throw new P(h,"Function",V)}),Bq=D((V,h)=>{if(typeof V!=="function"||C(V))throw new P(h,"Function",V)}),Jq=D((V,h)=>{if(V!==void 0)throw new P(h,"undefined",V)});M.exports={isInt32:$,isUint32:s,parseFileMode:N,validateArray:b,validateBoolean:E,validateBuffer:r,validateEncoding:Qq,validateFunction:Xq,validateInt32:u,validateInteger:m,validateNumber:w,validateObject:W,validateOneOf:S,validatePlainFunction:Bq,validatePort:Zq,validateSignalName:a,validateString:z,validateUint32:J,validateUndefined:Jq,validateAbortSignal:Vq}}}),Iq=$q({"node_modules/readable-stream/lib/internal/streams/utils.js"(t,M){var{Symbol:B,SymbolAsyncIterator:F,SymbolIterator:y}=Wq(),I=B("kDestroyed"),j=B("kIsErrored"),R=B("kIsReadable"),x=B("kIsDisturbed");function g(J,z=!1){var w;return!!(J&&typeof J.pipe==="function"&&typeof J.on==="function"&&(!z||typeof J.pause==="function"&&typeof J.resume==="function")&&(!J._writableState||((w=J._readableState)===null||w===void 0?void 0:w.readable)!==!1)&&(!J._writableState||J._readableState))}function f(J){var z;return!!(J&&typeof J.write==="function"&&typeof J.on==="function"&&(!J._readableState||((z=J._writableState)===null||z===void 0?void 0:z.writable)!==!1))}function c(J){return!!(J&&typeof J.pipe==="function"&&J._readableState&&typeof J.on==="function"&&typeof J.write==="function")}function _(J){return J&&(J._readableState||J._writableState||typeof J.write==="function"&&typeof J.on==="function"||typeof J.pipe==="function"&&typeof J.on==="function")}function i(J,z){if(J==null)return!1;if(z===!0)return typeof J[F]==="function";if(z===!1)return typeof J[y]==="function";return typeof J[F]==="function"||typeof J[y]==="function"}function D(J){if(!_(J))return null;const{_writableState:z,_readableState:w}=J,S=z||w;return!!(J.destroyed||J[I]||S!==null&&S!==void 0&&S.destroyed)}function p(J){if(!f(J))return null;if(J.writableEnded===!0)return!0;const z=J._writableState;if(z!==null&&z!==void 0&&z.errored)return!1;if(typeof(z===null||z===void 0?void 0:z.ended)!=="boolean")return null;return z.ended}function P(J,z){if(!f(J))return null;if(J.writableFinished===!0)return!0;const w=J._writableState;if(w!==null&&w!==void 0&&w.errored)return!1;if(typeof(w===null||w===void 0?void 0:w.finished)!=="boolean")return null;return!!(w.finished||z===!1&&w.ended===!0&&w.length===0)}function A(J){if(!g(J))return null;if(J.readableEnded===!0)return!0;const z=J._readableState;if(!z||z.errored)return!1;if(typeof(z===null||z===void 0?void 0:z.ended)!=="boolean")return null;return z.ended}function K(J,z){if(!g(J))return null;const w=J._readableState;if(w!==null&&w!==void 0&&w.errored)return!1;if(typeof(w===null||w===void 0?void 0:w.endEmitted)!=="boolean")return null;return!!(w.endEmitted||z===!1&&w.ended===!0&&w.length===0)}function U(J){if(J&&J[R]!=null)return J[R];if(typeof(J===null||J===void 0?void 0:J.readable)!=="boolean")return null;if(D(J))return!1;return g(J)&&J.readable&&!K(J)}function T(J){if(typeof(J===null||J===void 0?void 0:J.writable)!=="boolean")return null;if(D(J))return!1;return f(J)&&J.writable&&!p(J)}function C(J,z){if(!_(J))return null;if(D(J))return!0;if((z===null||z===void 0?void 0:z.readable)!==!1&&U(J))return!1;if((z===null||z===void 0?void 0:z.writable)!==!1&&T(J))return!1;return!0}function qq(J){var z,w;if(!_(J))return null;if(J.writableErrored)return J.writableErrored;return(z=(w=J._writableState)===null||w===void 0?void 0:w.errored)!==null&&z!==void 0?z:null}function o(J){var z,w;if(!_(J))return null;if(J.readableErrored)return J.readableErrored;return(z=(w=J._readableState)===null||w===void 0?void 0:w.errored)!==null&&z!==void 0?z:null}function $(J){if(!_(J))return null;if(typeof J.closed==="boolean")return J.closed;const{_writableState:z,_readableState:w}=J;if(typeof(z===null||z===void 0?void 0:z.closed)==="boolean"||typeof(w===null||w===void 0?void 0:w.closed)==="boolean")return(z===null||z===void 0?void 0:z.closed)||(w===null||w===void 0?void 0:w.closed);if(typeof J._closed==="boolean"&&s(J))return J._closed;return null}function s(J){return typeof J._closed==="boolean"&&typeof J._defaultKeepAlive==="boolean"&&typeof J._removedConnection==="boolean"&&typeof J._removedContLen==="boolean"}function Y(J){return typeof J._sent100==="boolean"&&s(J)}function Z(J){var z;return typeof J._consuming==="boolean"&&typeof J._dumped==="boolean"&&((z=J.req)===null||z===void 0?void 0:z.upgradeOrConnect)===void 0}function N(J){if(!_(J))return null;const{_writableState:z,_readableState:w}=J,S=z||w;return!S&&Y(J)||!!(S&&S.autoDestroy&&S.emitClose&&S.closed===!1)}function m(J){var z;return!!(J&&((z=J[x])!==null&&z!==void 0?z:J.readableDidRead||J.readableAborted))}function u(J){var z,w,S,E,W,b,a,r,Qq,Zq;return!!(J&&((z=(w=(S=(E=(W=(b=J[j])!==null&&b!==void 0?b:J.readableErrored)!==null&&W!==void 0?W:J.writableErrored)!==null&&E!==void 0?E:(a=J._readableState)===null||a===void 0?void 0:a.errorEmitted)!==null&&S!==void 0?S:(r=J._writableState)===null||r===void 0?void 0:r.errorEmitted)!==null&&w!==void 0?w:(Qq=J._readableState)===null||Qq===void 0?void 0:Qq.errored)!==null&&z!==void 0?z:(Zq=J._writableState)===null||Zq===void 0?void 0:Zq.errored))}M.exports={kDestroyed:I,isDisturbed:m,kIsDisturbed:x,isErrored:u,kIsErrored:j,isReadable:U,kIsReadable:R,isClosed:$,isDestroyed:D,isDuplexNodeStream:c,isFinished:C,isIterable:i,isReadableNodeStream:g,isReadableEnded:A,isReadableFinished:K,isReadableErrored:o,isNodeStream:_,isWritable:T,isWritableNodeStream:f,isWritableEnded:p,isWritableFinished:P,isWritableErrored:qq,isServerRequest:Z,isServerResponse:Y,willEmitClose:N}}}),jq=$q({"node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(t,M){var{AbortError:B,codes:F}=Mq(),{ERR_INVALID_ARG_TYPE:y,ERR_STREAM_PREMATURE_CLOSE:I}=F,{once:j}=Eq(),{validateAbortSignal:R,validateFunction:x,validateObject:g}=Cq(),{Promise:f}=Wq(),{isClosed:c,isReadable:_,isReadableNodeStream:i,isReadableFinished:D,isReadableErrored:p,isWritable:P,isWritableNodeStream:A,isWritableFinished:K,isWritableErrored:U,isNodeStream:T,willEmitClose:C}=Iq();function qq(Y){return Y.setHeader&&typeof Y.abort==="function"}var o=()=>{};function $(Y,Z,N){var m,u;if(arguments.length===2)N=Z,Z={};else if(Z==null)Z={};else g(Z,"options");x(N,"callback"),R(Z.signal,"options.signal"),N=j(N);const J=(m=Z.readable)!==null&&m!==void 0?m:i(Y),z=(u=Z.writable)!==null&&u!==void 0?u:A(Y);if(!T(Y))throw new y("stream","Stream",Y);const{_writableState:w,_readableState:S}=Y,E=()=>{if(!Y.writable)a()};let W=C(Y)&&i(Y)===J&&A(Y)===z,b=K(Y,!1);const a=()=>{if(b=!0,Y.destroyed)W=!1;if(W&&(!Y.readable||J))return;if(!J||r)N.call(Y)};let r=D(Y,!1);const Qq=()=>{if(r=!0,Y.destroyed)W=!1;if(W&&(!Y.writable||z))return;if(!z||b)N.call(Y)},Zq=(V)=>{N.call(Y,V)};let Vq=c(Y);const Xq=()=>{Vq=!0;const V=U(Y)||p(Y);if(V&&typeof V!=="boolean")return N.call(Y,V);if(J&&!r&&i(Y,!0)){if(!D(Y,!1))return N.call(Y,new I)}if(z&&!b){if(!K(Y,!1))return N.call(Y,new I)}N.call(Y)},Bq=()=>{Y.req.on("finish",a)};if(qq(Y)){if(Y.on("complete",a),!W)Y.on("abort",Xq);if(Y.req)Bq();else Y.on("request",Bq)}else if(z&&!w)Y.on("end",E),Y.on("close",E);if(!W&&typeof Y.aborted==="boolean")Y.on("aborted",Xq);if(Y.on("end",Qq),Y.on("finish",a),Z.error!==!1)Y.on("error",Zq);if(Y.on("close",Xq),Vq)Hq(Xq);else if(w!==null&&w!==void 0&&w.errorEmitted||S!==null&&S!==void 0&&S.errorEmitted){if(!W)Hq(Xq)}else if(!J&&(!W||_(Y))&&(b||P(Y)===!1))Hq(Xq);else if(!z&&(!W||P(Y))&&(r||_(Y)===!1))Hq(Xq);else if(S&&Y.req&&Y.aborted)Hq(Xq);const Jq=()=>{if(N=o,Y.removeListener("aborted",Xq),Y.removeListener("complete",a),Y.removeListener("abort",Xq),Y.removeListener("request",Bq),Y.req)Y.req.removeListener("finish",a);Y.removeListener("end",E),Y.removeListener("close",E),Y.removeListener("finish",a),Y.removeListener("end",Qq),Y.removeListener("error",Zq),Y.removeListener("close",Xq)};if(Z.signal&&!Vq){const V=()=>{const h=N;Jq(),h.call(Y,new B(void 0,{cause:Z.signal.reason}))};if(Z.signal.aborted)Hq(V);else{const h=N;N=j((...X)=>{Z.signal.removeEventListener("abort",V),h.apply(Y,X)}),Z.signal.addEventListener("abort",V)}}return Jq}function s(Y,Z){return new f((N,m)=>{$(Y,Z,(u)=>{if(u)m(u);else N()})})}M.exports=$,M.exports.finished=s}}),HQ=$q({"node_modules/readable-stream/lib/internal/streams/operators.js"(t,M){var{codes:{ERR_INVALID_ARG_TYPE:B,ERR_MISSING_ARGS:F,ERR_OUT_OF_RANGE:y},AbortError:I}=Mq(),{validateAbortSignal:j,validateInteger:R,validateObject:x}=Cq(),g=Wq().Symbol("kWeak"),{finished:f}=jq(),{ArrayPrototypePush:c,MathFloor:_,Number:i,NumberIsNaN:D,Promise:p,PromiseReject:P,PromisePrototypeCatch:A,Symbol:K}=Wq(),U=K("kEmpty"),T=K("kEof");function C(E,W){if(typeof E!=="function")throw new B("fn",["Function","AsyncFunction"],E);if(W!=null)x(W,"options");if((W===null||W===void 0?void 0:W.signal)!=null)j(W.signal,"options.signal");let b=1;if((W===null||W===void 0?void 0:W.concurrency)!=null)b=_(W.concurrency);return R(b,"concurrency",1),async function*a(){var r,Qq;const Zq=new AbortController,Vq=this,Xq=[],Bq=Zq.signal,Jq={signal:Bq},V=()=>Zq.abort();if(W!==null&&W!==void 0&&(r=W.signal)!==null&&r!==void 0&&r.aborted)V();W===null||W===void 0||(Qq=W.signal)===null||Qq===void 0||Qq.addEventListener("abort",V);let h,X,H=!1;function L(){H=!0}async function l(){try{for await(let q of Vq){var k;if(H)return;if(Bq.aborted)throw new I;try{q=E(q,Jq)}catch(Q){q=P(Q)}if(q===U)continue;if(typeof((k=q)===null||k===void 0?void 0:k.catch)==="function")q.catch(L);if(Xq.push(q),h)h(),h=null;if(!H&&Xq.length&&Xq.length>=b)await new p((Q)=>{X=Q})}Xq.push(T)}catch(q){const Q=P(q);A(Q,L),Xq.push(Q)}finally{var e;if(H=!0,h)h(),h=null;W===null||W===void 0||(e=W.signal)===null||e===void 0||e.removeEventListener("abort",V)}}l();try{while(!0){while(Xq.length>0){const k=await Xq[0];if(k===T)return;if(Bq.aborted)throw new I;if(k!==U)yield k;if(Xq.shift(),X)X(),X=null}await new p((k)=>{h=k})}}finally{if(Zq.abort(),H=!0,X)X(),X=null}}.call(this)}function qq(E=void 0){if(E!=null)x(E,"options");if((E===null||E===void 0?void 0:E.signal)!=null)j(E.signal,"options.signal");return async function*W(){let b=0;for await(let r of this){var a;if(E!==null&&E!==void 0&&(a=E.signal)!==null&&a!==void 0&&a.aborted)throw new I({cause:E.signal.reason});yield[b++,r]}}.call(this)}async function o(E,W=void 0){for await(let b of Z.call(this,E,W))return!0;return!1}async function $(E,W=void 0){if(typeof E!=="function")throw new B("fn",["Function","AsyncFunction"],E);return!await o.call(this,async(...b)=>{return!await E(...b)},W)}async function s(E,W){for await(let b of Z.call(this,E,W))return b;return}async function Y(E,W){if(typeof E!=="function")throw new B("fn",["Function","AsyncFunction"],E);async function b(a,r){return await E(a,r),U}for await(let a of C.call(this,b,W));}function Z(E,W){if(typeof E!=="function")throw new B("fn",["Function","AsyncFunction"],E);async function b(a,r){if(await E(a,r))return a;return U}return C.call(this,b,W)}var N=class extends F{constructor(){super("reduce");this.message="Reduce of an empty stream requires an initial value"}};async function m(E,W,b){var a;if(typeof E!=="function")throw new B("reducer",["Function","AsyncFunction"],E);if(b!=null)x(b,"options");if((b===null||b===void 0?void 0:b.signal)!=null)j(b.signal,"options.signal");let r=arguments.length>1;if(b!==null&&b!==void 0&&(a=b.signal)!==null&&a!==void 0&&a.aborted){const Bq=new I(void 0,{cause:b.signal.reason});throw this.once("error",()=>{}),await f(this.destroy(Bq)),Bq}const Qq=new AbortController,Zq=Qq.signal;if(b!==null&&b!==void 0&&b.signal){const Bq={once:!0,[g]:this};b.signal.addEventListener("abort",()=>Qq.abort(),Bq)}let Vq=!1;try{for await(let Bq of this){var Xq;if(Vq=!0,b!==null&&b!==void 0&&(Xq=b.signal)!==null&&Xq!==void 0&&Xq.aborted)throw new I;if(!r)W=Bq,r=!0;else W=await E(W,Bq,{signal:Zq})}if(!Vq&&!r)throw new N}finally{Qq.abort()}return W}async function u(E){if(E!=null)x(E,"options");if((E===null||E===void 0?void 0:E.signal)!=null)j(E.signal,"options.signal");const W=[];for await(let a of this){var b;if(E!==null&&E!==void 0&&(b=E.signal)!==null&&b!==void 0&&b.aborted)throw new I(void 0,{cause:E.signal.reason});c(W,a)}return W}function J(E,W){const b=C.call(this,E,W);return async function*a(){for await(let r of b)yield*r}.call(this)}function z(E){if(E=i(E),D(E))return 0;if(E<0)throw new y("number",">= 0",E);return E}function w(E,W=void 0){if(W!=null)x(W,"options");if((W===null||W===void 0?void 0:W.signal)!=null)j(W.signal,"options.signal");return E=z(E),async function*b(){var a;if(W!==null&&W!==void 0&&(a=W.signal)!==null&&a!==void 0&&a.aborted)throw new I;for await(let Qq of this){var r;if(W!==null&&W!==void 0&&(r=W.signal)!==null&&r!==void 0&&r.aborted)throw new I;if(E--<=0)yield Qq}}.call(this)}function S(E,W=void 0){if(W!=null)x(W,"options");if((W===null||W===void 0?void 0:W.signal)!=null)j(W.signal,"options.signal");return E=z(E),async function*b(){var a;if(W!==null&&W!==void 0&&(a=W.signal)!==null&&a!==void 0&&a.aborted)throw new I;for await(let Qq of this){var r;if(W!==null&&W!==void 0&&(r=W.signal)!==null&&r!==void 0&&r.aborted)throw new I;if(E-- >0)yield Qq;else return}}.call(this)}M.exports.streamReturningOperators={asIndexedPairs:qq,drop:w,filter:Z,flatMap:J,map:C,take:S},M.exports.promiseReturningOperators={every:$,forEach:Y,reduce:m,toArray:u,some:o,find:s}}}),Pq=$q({"node_modules/readable-stream/lib/internal/streams/destroy.js"(t,M){var{aggregateTwoErrors:B,codes:{ERR_MULTIPLE_CALLBACK:F},AbortError:y}=Mq(),{Symbol:I}=Wq(),{kDestroyed:j,isDestroyed:R,isFinished:x,isServerRequest:g}=Iq(),f="#kDestroy",c="#kConstruct";function _(Z,N,m){if(Z){if(Z.stack,N&&!N.errored)N.errored=Z;if(m&&!m.errored)m.errored=Z}}function i(Z,N){const m=this._readableState,u=this._writableState,J=u||m;if(u&&u.destroyed||m&&m.destroyed){if(typeof N==="function")N();return this}if(_(Z,u,m),u)u.destroyed=!0;if(m)m.destroyed=!0;if(!J.constructed)this.once(f,(z)=>{D(this,B(z,Z),N)});else D(this,Z,N);return this}function D(Z,N,m){let u=!1;function J(z){if(u)return;u=!0;const{_readableState:w,_writableState:S}=Z;if(_(z,S,w),S)S.closed=!0;if(w)w.closed=!0;if(typeof m==="function")m(z);if(z)Hq(p,Z,z);else Hq(P,Z)}try{Z._destroy(N||null,J)}catch(z){J(z)}}function p(Z,N){A(Z,N),P(Z)}function P(Z){const{_readableState:N,_writableState:m}=Z;if(m)m.closeEmitted=!0;if(N)N.closeEmitted=!0;if(m&&m.emitClose||N&&N.emitClose)Z.emit("close")}function A(Z,N){const m=Z?._readableState,u=Z?._writableState;if(u?.errorEmitted||m?.errorEmitted)return;if(u)u.errorEmitted=!0;if(m)m.errorEmitted=!0;Z?.emit?.("error",N)}function K(){const Z=this._readableState,N=this._writableState;if(Z)Z.constructed=!0,Z.closed=!1,Z.closeEmitted=!1,Z.destroyed=!1,Z.errored=null,Z.errorEmitted=!1,Z.reading=!1,Z.ended=Z.readable===!1,Z.endEmitted=Z.readable===!1;if(N)N.constructed=!0,N.destroyed=!1,N.closed=!1,N.closeEmitted=!1,N.errored=null,N.errorEmitted=!1,N.finalCalled=!1,N.prefinished=!1,N.ended=N.writable===!1,N.ending=N.writable===!1,N.finished=N.writable===!1}function U(Z,N,m){const u=Z?._readableState,J=Z?._writableState;if(J&&J.destroyed||u&&u.destroyed)return this;if(u&&u.autoDestroy||J&&J.autoDestroy)Z.destroy(N);else if(N){if(Error.captureStackTrace(N),J&&!J.errored)J.errored=N;if(u&&!u.errored)u.errored=N;if(m)Hq(A,Z,N);else A(Z,N)}}function T(Z,N){if(typeof Z._construct!=="function")return;const{_readableState:m,_writableState:u}=Z;if(m)m.constructed=!1;if(u)u.constructed=!1;if(Z.once(c,N),Z.listenerCount(c)>1)return;Hq(C,Z)}function C(Z){let N=!1;function m(u){if(N){U(Z,u!==null&&u!==void 0?u:new F);return}N=!0;const{_readableState:J,_writableState:z}=Z,w=z||J;if(J)J.constructed=!0;if(z)z.constructed=!0;if(w.destroyed)Z.emit(f,u);else if(u)U(Z,u,!0);else Hq(qq,Z)}try{Z._construct(m)}catch(u){m(u)}}function qq(Z){Z.emit(c)}function o(Z){return Z&&Z.setHeader&&typeof Z.abort==="function"}function $(Z){Z.emit("close")}function s(Z,N){Z.emit("error",N),Hq($,Z)}function Y(Z,N){if(!Z||R(Z))return;if(!N&&!x(Z))N=new y;if(g(Z))Z.socket=null,Z.destroy(N);else if(o(Z))Z.abort();else if(o(Z.req))Z.req.abort();else if(typeof Z.destroy==="function")Z.destroy(N);else if(typeof Z.close==="function")Z.close();else if(N)Hq(s,Z);else Hq($,Z);if(!Z.destroyed)Z[j]=!0}M.exports={construct:T,destroyer:Y,destroy:i,undestroy:K,errorOrDestroy:U}}}),Sq=$q({"node_modules/readable-stream/lib/internal/streams/legacy.js"(t,M){var{ArrayIsArray:B,ObjectSetPrototypeOf:F}=Wq();function y(j){if(!(this instanceof y))return new y(j);Tq.call(this,j)}F(y.prototype,Tq.prototype),F(y,Tq),y.prototype.pipe=function(j,R){const x=this;function g(P){if(j.writable&&j.write(P)===!1&&x.pause)x.pause()}x.on("data",g);function f(){if(x.readable&&x.resume)x.resume()}if(j.on("drain",f),!j._isStdio&&(!R||R.end!==!1))x.on("end",_),x.on("close",i);let c=!1;function _(){if(c)return;c=!0,j.end()}function i(){if(c)return;if(c=!0,typeof j.destroy==="function")j.destroy()}function D(P){if(p(),Tq.listenerCount(this,"error")===0)this.emit("error",P)}I(x,"error",D),I(j,"error",D);function p(){x.removeListener("data",g),j.removeListener("drain",f),x.removeListener("end",_),x.removeListener("close",i),x.removeListener("error",D),j.removeListener("error",D),x.removeListener("end",p),x.removeListener("close",p),j.removeListener("close",p)}return x.on("end",p),x.on("close",p),j.on("close",p),j.emit("pipe",x),j};function I(j,R,x){if(typeof j.prependListener==="function")return j.prependListener(R,x);if(!j._events||!j._events[R])j.on(R,x);else if(B(j._events[R]))j._events[R].unshift(x);else j._events[R]=[x,j._events[R]]}M.exports={Stream:y,prependListener:I}}}),gq=$q({"node_modules/readable-stream/lib/internal/streams/add-abort-signal.js"(t,M){var{AbortError:B,codes:F}=Mq(),y=jq(),{ERR_INVALID_ARG_TYPE:I}=F,j=(x,g)=>{if(typeof x!=="object"||!("aborted"in x))throw new I(g,"AbortSignal",x)};function R(x){return!!(x&&typeof x.pipe==="function")}M.exports.addAbortSignal=function x(g,f){if(j(g,"signal"),!R(f))throw new I("stream","stream.Stream",f);return M.exports.addAbortSignalNoValidate(g,f)},M.exports.addAbortSignalNoValidate=function(x,g){if(typeof x!=="object"||!("aborted"in x))return g;const f=()=>{g.destroy(new B(void 0,{cause:x.reason}))};if(x.aborted)f();else x.addEventListener("abort",f),y(g,()=>x.removeEventListener("abort",f));return g}}}),KQ=$q({"node_modules/readable-stream/lib/internal/streams/state.js"(t,M){var{MathFloor:B,NumberIsInteger:F}=Wq(),{ERR_INVALID_ARG_VALUE:y}=Mq().codes;function I(x,g,f){return x.highWaterMark!=null?x.highWaterMark:g?x[f]:null}function j(x){return x?16:16384}function R(x,g,f,c){const _=I(g,c,f);if(_!=null){if(!F(_)||_<0){const i=c?`options.${f}`:"options.highWaterMark";throw new y(i,_)}return B(_)}return j(x.objectMode)}M.exports={getHighWaterMark:R,getDefaultHighWaterMark:j}}}),pq=$q({"node_modules/readable-stream/lib/internal/streams/from.js"(t,M){var{PromisePrototypeThen:B,SymbolAsyncIterator:F,SymbolIterator:y}=Wq(),{ERR_INVALID_ARG_TYPE:I,ERR_STREAM_NULL_VALUES:j}=Mq().codes;function R(x,g,f){let c;if(typeof g==="string"||g instanceof Buffer)return new x({objectMode:!0,...f,read(){this.push(g),this.push(null)}});let _;if(g&&g[F])_=!0,c=g[F]();else if(g&&g[y])_=!1,c=g[y]();else throw new I("iterable",["Iterable"],g);const i=new x({objectMode:!0,highWaterMark:1,...f});let D=!1;i._read=function(){if(!D)D=!0,P()},i._destroy=function(A,K){B(p(A),()=>Hq(K,A),(U)=>Hq(K,U||A))};async function p(A){const K=A!==void 0&&A!==null,U=typeof c.throw==="function";if(K&&U){const{value:T,done:C}=await c.throw(A);if(await T,C)return}if(typeof c.return==="function"){const{value:T}=await c.return();await T}}async function P(){for(;;){try{const{value:A,done:K}=_?await c.next():c.next();if(K)i.push(null);else{const U=A&&typeof A.then==="function"?await A:A;if(U===null)throw D=!1,new j;else if(i.push(U))continue;else D=!1}}catch(A){i.destroy(A)}break}}return i}M.exports=R}}),uq,bq,Dq=$q({"node_modules/readable-stream/lib/internal/streams/readable.js"(t,M){var{ArrayPrototypeIndexOf:B,NumberIsInteger:F,NumberIsNaN:y,NumberParseInt:I,ObjectDefineProperties:j,ObjectKeys:R,ObjectSetPrototypeOf:x,Promise:g,SafeSet:f,SymbolAsyncIterator:c,Symbol:_}=Wq(),i=globalThis[Symbol.for("Bun.lazy")]("bun:stream").ReadableState,{Stream:D,prependListener:p}=Sq();function P(q){if(!(this instanceof P))return new P(q);const Q=this instanceof Lq();if(this._readableState=new i(q,this,Q),q){const{read:O,destroy:G,construct:v,signal:Kq}=q;if(typeof O==="function")this._read=O;if(typeof G==="function")this._destroy=G;if(typeof v==="function")this._construct=v;if(Kq&&!Q)U(Kq,this)}D.call(this,q),Z.construct(this,()=>{if(this._readableState.needReadable)s(this,this._readableState)})}x(P.prototype,D.prototype),x(P,D),P.prototype.on=function(q,Q){const O=D.prototype.on.call(this,q,Q),G=this._readableState;if(q==="data")if(G.readableListening=this.listenerCount("readable")>0,G.flowing!==!1)n&&d("in flowing mode!",this.__id),this.resume();else n&&d("in readable mode!",this.__id);else if(q==="readable"){if(n&&d("readable listener added!",this.__id),!G.endEmitted&&!G.readableListening){if(G.readableListening=G.needReadable=!0,G.flowing=!1,G.emittedReadable=!1,n&&d("on readable - state.length, reading, emittedReadable",G.length,G.reading,G.emittedReadable,this.__id),G.length)Y(this,G);else if(!G.reading)Hq(Jq,this)}else if(G.endEmitted)n&&d("end already emitted...",this.__id)}return O};class A extends P{#q;#Q;#X;#H;constructor(q,Q){const{objectMode:O,highWaterMark:G,encoding:v,signal:Kq}=q;super({objectMode:O,highWaterMark:G,encoding:v,signal:Kq});this.#X=[],this.#q=void 0,this.#H=Q,this.#Q=!1}#J(){var q=this.#X,Q=0,O=q.length;for(;Q<O;Q++){const G=q[Q];if(q[Q]=void 0,!this.push(G,void 0))return this.#X=q.slice(Q+1),!0}if(O>0)this.#X=[];return!1}#K(q){q.releaseLock(),this.#q=void 0,this.#Q=!0,this.push(null);return}async _read(){n&&d("ReadableFromWeb _read()",this.__id);var q=this.#H,Q=this.#q;if(q)Q=this.#q=q.getReader(),this.#H=void 0;else if(this.#J())return;var O;try{do{var G=!1,v;const Kq=Q.readMany();if(Oq(Kq)){if({done:G,value:v}=await Kq,this.#Q){this.#X.push(...v);return}}else({done:G,value:v}=Kq);if(G){this.#K(Q);return}if(!this.push(v[0])){this.#X=v.slice(1);return}for(let Yq=1,_q=v.length;Yq<_q;Yq++)if(!this.push(v[Yq])){this.#X=v.slice(Yq+1);return}}while(!this.#Q)}catch(Kq){O=Kq}finally{if(O)throw O}}_destroy(q,Q){if(!this.#Q){var O=this.#q;if(O)this.#q=void 0,O.cancel(q).finally(()=>{this.#Q=!0,Q(q)});return}try{Q(q)}catch(G){globalThis.reportError(G)}}}bq=A;function K(q,Q={}){if(!qQ(q))throw new m("readableStream","ReadableStream",q);S(Q,"options");const{highWaterMark:O,encoding:G,objectMode:v=!1,signal:Kq}=Q;if(G!==void 0&&!Buffer.isEncoding(G))throw new JQ(G,"options.encoding");return QQ(v,"options.objectMode"),UQ(P,q,Q)||new A({highWaterMark:O,encoding:G,objectMode:v,signal:Kq},q)}M.exports=P,uq=K;var{addAbortSignal:U}=gq(),T=jq();const{maybeReadMore:C,resume:qq,emitReadable:o,onEofChunk:$}=globalThis[Symbol.for("Bun.lazy")]("bun:stream");function s(q,Q){process.nextTick(C,q,Q)}function Y(q,Q){n&&d("NativeReadable - emitReadable",q.__id),o(q,Q)}var Z=Pq(),{aggregateTwoErrors:N,codes:{ERR_INVALID_ARG_TYPE:m,ERR_METHOD_NOT_IMPLEMENTED:u,ERR_OUT_OF_RANGE:J,ERR_STREAM_PUSH_AFTER_EOF:z,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:w}}=Mq(),{validateObject:S}=Cq(),E=pq(),W=()=>{},{errorOrDestroy:b}=Z;P.prototype.destroy=Z.destroy,P.prototype._undestroy=Z.undestroy,P.prototype._destroy=function(q,Q){Q(q)},P.prototype[Tq.captureRejectionSymbol]=function(q){this.destroy(q)},P.prototype.push=function(q,Q){return a(this,q,Q,!1)},P.prototype.unshift=function(q,Q){return a(this,q,Q,!0)};function a(q,Q,O,G){n&&d("readableAddChunk",Q,q.__id);const v=q._readableState;let Kq;if(!v.objectMode){if(typeof Q==="string"){if(O=O||v.defaultEncoding,v.encoding!==O)if(G&&v.encoding)Q=Buffer.from(Q,O).toString(v.encoding);else Q=Buffer.from(Q,O),O=""}else if(Q instanceof Buffer)O="";else if(D._isUint8Array(Q)){if(G||!v.decoder)Q=D._uint8ArrayToBuffer(Q);O=""}else if(Q!=null)Kq=new m("chunk",["string","Buffer","Uint8Array"],Q)}if(Kq)b(q,Kq);else if(Q===null)v.reading=!1,$(q,v);else if(v.objectMode||Q&&Q.length>0)if(G)if(v.endEmitted)b(q,new w);else if(v.destroyed||v.errored)return!1;else r(q,v,Q,!0);else if(v.ended)b(q,new z);else if(v.destroyed||v.errored)return!1;else if(v.reading=!1,v.decoder&&!O)if(Q=v.decoder.write(Q),v.objectMode||Q.length!==0)r(q,v,Q,!1);else s(q,v);else r(q,v,Q,!1);else if(!G)v.reading=!1,s(q,v);return!v.ended&&(v.length<v.highWaterMark||v.length===0)}function r(q,Q,O,G){if(n&&d("adding chunk",q.__id),n&&d("chunk",O.toString(),q.__id),Q.flowing&&Q.length===0&&!Q.sync&&q.listenerCount("data")>0){if(Q.multiAwaitDrain)Q.awaitDrainWriters.clear();else Q.awaitDrainWriters=null;Q.dataEmitted=!0,q.emit("data",O)}else{if(Q.length+=Q.objectMode?1:O.length,G)Q.buffer.unshift(O);else Q.buffer.push(O);if(n&&d("needReadable @ addChunk",Q.needReadable,q.__id),Q.needReadable)Y(q,Q)}s(q,Q)}P.prototype.isPaused=function(){const q=this._readableState;return q.paused===!0||q.flowing===!1},P.prototype.setEncoding=function(q){const Q=new rq(q);this._readableState.decoder=Q,this._readableState.encoding=this._readableState.decoder.encoding;const O=this._readableState.buffer;let G="";for(let v=O.length;v>0;v--)G+=Q.write(O.shift());if(G!=="")O.push(G);return this._readableState.length=G.length,this};var Qq=1073741824;function Zq(q){if(q>Qq)throw new J("size","<= 1GiB",q);else q--,q|=q>>>1,q|=q>>>2,q|=q>>>4,q|=q>>>8,q|=q>>>16,q++;return q}function Vq(q,Q){if(q<=0||Q.length===0&&Q.ended)return 0;if(Q.objectMode)return 1;if(y(q)){if(Q.flowing&&Q.length)return Q.buffer.first().length;return Q.length}if(q<=Q.length)return q;return Q.ended?Q.length:0}P.prototype.read=function(q){if(n&&d("read - n =",q,this.__id),!F(q))q=I(q,10);const Q=this._readableState,O=q;if(q>Q.highWaterMark)Q.highWaterMark=Zq(q);if(q!==0)Q.emittedReadable=!1;if(q===0&&Q.needReadable&&((Q.highWaterMark!==0?Q.length>=Q.highWaterMark:Q.length>0)||Q.ended)){if(n&&d("read: emitReadable or endReadable",Q.length,Q.ended,this.__id),Q.length===0&&Q.ended)H(this);else Y(this,Q);return null}if(q=Vq(q,Q),q===0&&Q.ended){if(n&&d("read: calling endReadable if length 0 -- length, state.ended",Q.length,Q.ended,this.__id),Q.length===0)H(this);return null}let G=Q.needReadable;if(n&&d("need readable",G,this.__id),Q.length===0||Q.length-q<Q.highWaterMark)G=!0,n&&d("length less than watermark",G,this.__id);if(Q.ended||Q.reading||Q.destroyed||Q.errored||!Q.constructed)n&&d("state.constructed?",Q.constructed,this.__id),G=!1,n&&d("reading, ended or constructing",G,this.__id);else if(G){if(n&&d("do read",this.__id),Q.reading=!0,Q.sync=!0,Q.length===0)Q.needReadable=!0;try{var v=this._read(Q.highWaterMark);if(Oq(v)){n&&d("async _read",this.__id);const Yq=Bun.peek(v);if(n&&d("peeked promise",Yq,this.__id),Yq!==v)v=Yq}if(Oq(v)&&v?.then&&sq(v.then))n&&d("async _read result.then setup",this.__id),v.then(W,function(Yq){b(this,Yq)})}catch(Yq){b(this,Yq)}if(Q.sync=!1,!Q.reading)q=Vq(O,Q)}n&&d("n @ fromList",q,this.__id);let Kq;if(q>0)Kq=X(q,Q);else Kq=null;if(n&&d("ret @ read",Kq,this.__id),Kq===null)Q.needReadable=Q.length<=Q.highWaterMark,n&&d("state.length while ret = null",Q.length,this.__id),q=0;else if(Q.length-=q,Q.multiAwaitDrain)Q.awaitDrainWriters.clear();else Q.awaitDrainWriters=null;if(Q.length===0){if(!Q.ended)Q.needReadable=!0;if(O!==q&&Q.ended)H(this)}if(Kq!==null&&!Q.errorEmitted&&!Q.closeEmitted)Q.dataEmitted=!0,this.emit("data",Kq);return Kq},P.prototype._read=function(q){throw new u("_read()")},P.prototype.pipe=function(q,Q){const O=this,G=this._readableState;if(G.pipes.length===1){if(!G.multiAwaitDrain)G.multiAwaitDrain=!0,G.awaitDrainWriters=new f(G.awaitDrainWriters?[G.awaitDrainWriters]:[])}G.pipes.push(q),n&&d("pipe count=%d opts=%j",G.pipes.length,Q,O.__id);const Kq=(!Q||Q.end!==!1)&&q!==process.stdout&&q!==process.stderr?_q:xq;if(G.endEmitted)Hq(Kq);else O.once("end",Kq);q.on("unpipe",Yq);function Yq(Aq,Fq){if(n&&d("onunpipe",O.__id),Aq===O){if(Fq&&Fq.hasUnpiped===!1)Fq.hasUnpiped=!0,oq()}}function _q(){n&&d("onend",O.__id),q.end()}let Nq,kq=!1;function oq(){if(n&&d("cleanup",O.__id),q.removeListener("close",vq),q.removeListener("finish",Rq),Nq)q.removeListener("drain",Nq);if(q.removeListener("error",wq),q.removeListener("unpipe",Yq),O.removeListener("end",_q),O.removeListener("end",xq),O.removeListener("data",hq),kq=!0,Nq&&G.awaitDrainWriters&&(!q._writableState||q._writableState.needDrain))Nq()}function yq(){if(!kq){if(G.pipes.length===1&&G.pipes[0]===q)n&&d("false write response, pause",0,O.__id),G.awaitDrainWriters=q,G.multiAwaitDrain=!1;else if(G.pipes.length>1&&G.pipes.includes(q))n&&d("false write response, pause",G.awaitDrainWriters.size,O.__id),G.awaitDrainWriters.add(q);O.pause()}if(!Nq)Nq=Xq(O,q),q.on("drain",Nq)}O.on("data",hq);function hq(Aq){n&&d("ondata",O.__id);const Fq=q.write(Aq);if(n&&d("dest.write",Fq,O.__id),Fq===!1)yq()}function wq(Aq){if(d("onerror",Aq),xq(),q.removeListener("error",wq),q.listenerCount("error")===0){const Fq=q._writableState||q._readableState;if(Fq&&!Fq.errorEmitted)b(q,Aq);else q.emit("error",Aq)}}p(q,"error",wq);function vq(){q.removeListener("finish",Rq),xq()}q.once("close",vq);function Rq(){d("onfinish"),q.removeListener("close",vq),xq()}q.once("finish",Rq);function xq(){d("unpipe"),O.unpipe(q)}if(q.emit("pipe",O),q.writableNeedDrain===!0){if(G.flowing)yq()}else if(!G.flowing)d("pipe resume"),O.resume();return q};function Xq(q,Q){return function O(){const G=q._readableState;if(G.awaitDrainWriters===Q)d("pipeOnDrain",1),G.awaitDrainWriters=null;else if(G.multiAwaitDrain)d("pipeOnDrain",G.awaitDrainWriters.size),G.awaitDrainWriters.delete(Q);if((!G.awaitDrainWriters||G.awaitDrainWriters.size===0)&&q.listenerCount("data"))q.resume()}}P.prototype.unpipe=function(q){const Q=this._readableState,O={hasUnpiped:!1};if(Q.pipes.length===0)return this;if(!q){const v=Q.pipes;Q.pipes=[],this.pause();for(let Kq=0;Kq<v.length;Kq++)v[Kq].emit("unpipe",this,{hasUnpiped:!1});return this}const G=B(Q.pipes,q);if(G===-1)return this;if(Q.pipes.splice(G,1),Q.pipes.length===0)this.pause();return q.emit("unpipe",this,O),this},P.prototype.addListener=P.prototype.on,P.prototype.removeListener=function(q,Q){const O=D.prototype.removeListener.call(this,q,Q);if(q==="readable")Hq(Bq,this);return O},P.prototype.off=P.prototype.removeListener,P.prototype.removeAllListeners=function(q){const Q=D.prototype.removeAllListeners.apply(this,arguments);if(q==="readable"||q===void 0)Hq(Bq,this);return Q};function Bq(q){const Q=q._readableState;if(Q.readableListening=q.listenerCount("readable")>0,Q.resumeScheduled&&Q.paused===!1)Q.flowing=!0;else if(q.listenerCount("data")>0)q.resume();else if(!Q.readableListening)Q.flowing=null}function Jq(q){n&&d("on readable nextTick, calling read(0)",q.__id),q.read(0)}P.prototype.resume=function(){const q=this._readableState;if(!q.flowing)n&&d("resume",this.__id),q.flowing=!q.readableListening,qq(this,q);return q.paused=!1,this},P.prototype.pause=function(){if(n&&d("call pause flowing=%j",this._readableState.flowing,this.__id),this._readableState.flowing!==!1)n&&d("pause",this.__id),this._readableState.flowing=!1,this.emit("pause");return this._readableState.paused=!0,this},P.prototype.wrap=function(q){let Q=!1;q.on("data",(G)=>{if(!this.push(G)&&q.pause)Q=!0,q.pause()}),q.on("end",()=>{this.push(null)}),q.on("error",(G)=>{b(this,G)}),q.on("close",()=>{this.destroy()}),q.on("destroy",()=>{this.destroy()}),this._read=()=>{if(Q&&q.resume)Q=!1,q.resume()};const O=R(q);for(let G=1;G<O.length;G++){const v=O[G];if(this[v]===void 0&&typeof q[v]==="function")this[v]=q[v].bind(q)}return this},P.prototype[c]=function(){return V(this)},P.prototype.iterator=function(q){if(q!==void 0)S(q,"options");return V(this,q)};function V(q,Q){if(typeof q.read!=="function")q=P.wrap(q,{objectMode:!0});const O=h(q,Q);return O.stream=q,O}async function*h(q,Q){let O=W;function G(Yq){if(this===q)O(),O=W;else O=Yq}q.on("readable",G);let v;const Kq=T(q,{writable:!1},(Yq)=>{v=Yq?N(v,Yq):null,O(),O=W});try{while(!0){const Yq=q.destroyed?null:q.read();if(Yq!==null)yield Yq;else if(v)throw v;else if(v===null)return;else await new g(G)}}catch(Yq){throw v=N(v,Yq),v}finally{if((v||(Q===null||Q===void 0?void 0:Q.destroyOnReturn)!==!1)&&(v===void 0||q._readableState.autoDestroy))Z.destroyer(q,null);else q.off("readable",G),Kq()}}j(P.prototype,{readable:{get(){const q=this._readableState;return!!q&&q.readable!==!1&&!q.destroyed&&!q.errorEmitted&&!q.endEmitted},set(q){if(this._readableState)this._readableState.readable=!!q}},readableDidRead:{enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{enumerable:!1,get:function(){return this._readableState.flowing},set:function(q){if(this._readableState)this._readableState.flowing=q}},readableLength:{enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{get(){return this._readableState?this._readableState.closed:!1}},destroyed:{enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(q){if(!this._readableState)return;this._readableState.destroyed=q}},readableEnded:{enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),P._fromList=X;function X(q,Q){if(Q.length===0)return null;let O;if(Q.objectMode)O=Q.buffer.shift();else if(!q||q>=Q.length){if(Q.decoder)O=Q.buffer.join("");else if(Q.buffer.length===1)O=Q.buffer.first();else O=Q.buffer.concat(Q.length);Q.buffer.clear()}else O=Q.buffer.consume(q,Q.decoder);return O}function H(q){const Q=q._readableState;if(n&&d("endEmitted @ endReadable",Q.endEmitted,q.__id),!Q.endEmitted)Q.ended=!0,Hq(L,Q,q)}function L(q,Q){if(n&&d("endReadableNT -- endEmitted, state.length",q.endEmitted,q.length,Q.__id),!q.errored&&!q.closeEmitted&&!q.endEmitted&&q.length===0){if(q.endEmitted=!0,Q.emit("end"),n&&d("end emitted @ endReadableNT",Q.__id),Q.writable&&Q.allowHalfOpen===!1)Hq(l,Q);else if(q.autoDestroy){const O=Q._writableState;if(!O||O.autoDestroy&&(O.finished||O.writable===!1))Q.destroy()}}}function l(q){if(q.writable&&!q.writableEnded&&!q.destroyed)q.end()}P.from=function(q,Q){return E(P,q,Q)};var k={newStreamReadableFromReadableStream:K};function e(){if(k===void 0)k={};return k}P.fromWeb=function(q,Q){return e().newStreamReadableFromReadableStream(q,Q)},P.toWeb=function(q){return e().newReadableStreamFromStreamReadable(q)},P.wrap=function(q,Q){var O,G;return new P({objectMode:(O=(G=q.readableObjectMode)!==null&&G!==void 0?G:q.objectMode)!==null&&O!==void 0?O:!0,...Q,destroy(v,Kq){Z.destroyer(q,v),Kq(v)}}).wrap(q)}}}),mq=$q({"node_modules/readable-stream/lib/internal/streams/writable.js"(t,M){var{ArrayPrototypeSlice:B,Error:F,FunctionPrototypeSymbolHasInstance:y,ObjectDefineProperty:I,ObjectDefineProperties:j,ObjectSetPrototypeOf:R,StringPrototypeToLowerCase:x,Symbol:g,SymbolHasInstance:f}=Wq(),c=Sq().Stream,_=Pq(),{addAbortSignal:i}=gq(),{getHighWaterMark:D,getDefaultHighWaterMark:p}=KQ(),{ERR_INVALID_ARG_TYPE:P,ERR_METHOD_NOT_IMPLEMENTED:A,ERR_MULTIPLE_CALLBACK:K,ERR_STREAM_CANNOT_PIPE:U,ERR_STREAM_DESTROYED:T,ERR_STREAM_ALREADY_FINISHED:C,ERR_STREAM_NULL_VALUES:qq,ERR_STREAM_WRITE_AFTER_END:o,ERR_UNKNOWN_ENCODING:$}=Mq().codes,{errorOrDestroy:s}=_;function Y(X={}){const H=this instanceof Lq();if(!H&&!y(Y,this))return new Y(X);if(this._writableState=new m(X,this,H),X){if(typeof X.write==="function")this._write=X.write;if(typeof X.writev==="function")this._writev=X.writev;if(typeof X.destroy==="function")this._destroy=X.destroy;if(typeof X.final==="function")this._final=X.final;if(typeof X.construct==="function")this._construct=X.construct;if(X.signal)i(X.signal,this)}c.call(this,X),_.construct(this,()=>{const L=this._writableState;if(!L.writing)r(this,L);Xq(this,L)})}R(Y.prototype,c.prototype),R(Y,c),M.exports=Y;function Z(){}var N=g("kOnFinished");function m(X,H,L){if(typeof L!=="boolean")L=H instanceof Lq();if(this.objectMode=!!(X&&X.objectMode),L)this.objectMode=this.objectMode||!!(X&&X.writableObjectMode);this.highWaterMark=X?D(this,X,"writableHighWaterMark",L):p(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;const l=!!(X&&X.decodeStrings===!1);this.decodeStrings=!l,this.defaultEncoding=X&&X.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=E.bind(void 0,H),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,u(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!X||X.emitClose!==!1,this.autoDestroy=!X||X.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[N]=[]}function u(X){X.buffered=[],X.bufferedIndex=0,X.allBuffers=!0,X.allNoop=!0}m.prototype.getBuffer=function X(){return B(this.buffered,this.bufferedIndex)},I(m.prototype,"bufferedRequestCount",{get(){return this.buffered.length-this.bufferedIndex}}),I(Y,f,{value:function(X){if(y(this,X))return!0;if(this!==Y)return!1;return X&&X._writableState instanceof m}}),Y.prototype.pipe=function(){s(this,new U)};function J(X,H,L,l){const k=X._writableState;if(typeof L==="function")l=L,L=k.defaultEncoding;else{if(!L)L=k.defaultEncoding;else if(L!=="buffer"&&!Buffer.isEncoding(L))throw new $(L);if(typeof l!=="function")l=Z}if(H===null)throw new qq;else if(!k.objectMode)if(typeof H==="string"){if(k.decodeStrings!==!1)H=Buffer.from(H,L),L="buffer"}else if(H instanceof Buffer)L="buffer";else if(c._isUint8Array(H))H=c._uint8ArrayToBuffer(H),L="buffer";else throw new P("chunk",["string","Buffer","Uint8Array"],H);let e;if(k.ending)e=new o;else if(k.destroyed)e=new T("write");if(e)return Hq(l,e),s(X,e,!0),e;return k.pendingcb++,z(X,k,H,L,l)}Y.prototype.write=function(X,H,L){return J(this,X,H,L)===!0},Y.prototype.cork=function(){this._writableState.corked++},Y.prototype.uncork=function(){const X=this._writableState;if(X.corked){if(X.corked--,!X.writing)r(this,X)}},Y.prototype.setDefaultEncoding=function X(H){if(typeof H==="string")H=x(H);if(!Buffer.isEncoding(H))throw new $(H);return this._writableState.defaultEncoding=H,this};function z(X,H,L,l,k){const e=H.objectMode?1:L.length;H.length+=e;const q=H.length<H.highWaterMark;if(!q)H.needDrain=!0;if(H.writing||H.corked||H.errored||!H.constructed){if(H.buffered.push({chunk:L,encoding:l,callback:k}),H.allBuffers&&l!=="buffer")H.allBuffers=!1;if(H.allNoop&&k!==Z)H.allNoop=!1}else H.writelen=e,H.writecb=k,H.writing=!0,H.sync=!0,X._write(L,l,H.onwrite),H.sync=!1;return q&&!H.errored&&!H.destroyed}function w(X,H,L,l,k,e,q){if(H.writelen=l,H.writecb=q,H.writing=!0,H.sync=!0,H.destroyed)H.onwrite(new T("write"));else if(L)X._writev(k,H.onwrite);else X._write(k,e,H.onwrite);H.sync=!1}function S(X,H,L,l){--H.pendingcb,l(L),a(H),s(X,L)}function E(X,H){const L=X._writableState,l=L.sync,k=L.writecb;if(typeof k!=="function"){s(X,new K);return}if(L.writing=!1,L.writecb=null,L.length-=L.writelen,L.writelen=0,H){if(Error.captureStackTrace(H),!L.errored)L.errored=H;if(X._readableState&&!X._readableState.errored)X._readableState.errored=H;if(l)Hq(S,X,L,H,k);else S(X,L,H,k)}else{if(L.buffered.length>L.bufferedIndex)r(X,L);if(l)if(L.afterWriteTickInfo!==null&&L.afterWriteTickInfo.cb===k)L.afterWriteTickInfo.count++;else L.afterWriteTickInfo={count:1,cb:k,stream:X,state:L},Hq(W,L.afterWriteTickInfo);else b(X,L,1,k)}}function W({stream:X,state:H,count:L,cb:l}){return H.afterWriteTickInfo=null,b(X,H,L,l)}function b(X,H,L,l){if(!H.ending&&!X.destroyed&&H.length===0&&H.needDrain)H.needDrain=!1,X.emit("drain");while(L-- >0)H.pendingcb--,l();if(H.destroyed)a(H);Xq(X,H)}function a(X){if(X.writing)return;for(let k=X.bufferedIndex;k<X.buffered.length;++k){var H;const{chunk:e,callback:q}=X.buffered[k],Q=X.objectMode?1:e.length;X.length-=Q,q((H=X.errored)!==null&&H!==void 0?H:new T("write"))}const L=X[N].splice(0);for(let k=0;k<L.length;k++){var l;L[k]((l=X.errored)!==null&&l!==void 0?l:new T("end"))}u(X)}function r(X,H){if(H.corked||H.bufferProcessing||H.destroyed||!H.constructed)return;const{buffered:L,bufferedIndex:l,objectMode:k}=H,e=L.length-l;if(!e)return;let q=l;if(H.bufferProcessing=!0,e>1&&X._writev){H.pendingcb-=e-1;const Q=H.allNoop?Z:(G)=>{for(let v=q;v<L.length;++v)L[v].callback(G)},O=H.allNoop&&q===0?L:B(L,q);O.allBuffers=H.allBuffers,w(X,H,!0,H.length,O,"",Q),u(H)}else{do{const{chunk:Q,encoding:O,callback:G}=L[q];L[q++]=null;const v=k?1:Q.length;w(X,H,!1,v,Q,O,G)}while(q<L.length&&!H.writing);if(q===L.length)u(H);else if(q>256)L.splice(0,q),H.bufferedIndex=0;else H.bufferedIndex=q}H.bufferProcessing=!1}Y.prototype._write=function(X,H,L){if(this._writev)this._writev([{chunk:X,encoding:H}],L);else throw new A("_write()")},Y.prototype._writev=null,Y.prototype.end=function(X,H,L,l=!1){const k=this._writableState;if(n&&d("end",k,this.__id),typeof X==="function")L=X,X=null,H=null;else if(typeof H==="function")L=H,H=null;let e;if(X!==null&&X!==void 0){let q;if(!l)q=J(this,X,H);else q=this.write(X,H);if(q instanceof F)e=q}if(k.corked)k.corked=1,this.uncork();if(e)this.emit("error",e);else if(!k.errored&&!k.ending)k.ending=!0,Xq(this,k,!0),k.ended=!0;else if(k.finished)e=new C("end");else if(k.destroyed)e=new T("end");if(typeof L==="function")if(e||k.finished)Hq(L,e);else k[N].push(L);return this};function Qq(X,H){var L=X.ending&&!X.destroyed&&X.constructed&&X.length===0&&!X.errored&&X.buffered.length===0&&!X.finished&&!X.writing&&!X.errorEmitted&&!X.closeEmitted;return d("needFinish",L,H),L}function Zq(X,H){let L=!1;function l(k){if(L){s(X,k!==null&&k!==void 0?k:K());return}if(L=!0,H.pendingcb--,k){const e=H[N].splice(0);for(let q=0;q<e.length;q++)e[q](k);s(X,k,H.sync)}else if(Qq(H))H.prefinished=!0,X.emit("prefinish"),H.pendingcb++,Hq(Bq,X,H)}H.sync=!0,H.pendingcb++;try{X._final(l)}catch(k){l(k)}H.sync=!1}function Vq(X,H){if(!H.prefinished&&!H.finalCalled)if(typeof X._final==="function"&&!H.destroyed)H.finalCalled=!0,Zq(X,H);else H.prefinished=!0,X.emit("prefinish")}function Xq(X,H,L){if(n&&d("finishMaybe -- state, sync",H,L,X.__id),!Qq(H,X.__id))return;if(Vq(X,H),H.pendingcb===0){if(L)H.pendingcb++,Hq((l,k)=>{if(Qq(k))Bq(l,k);else k.pendingcb--},X,H);else if(Qq(H))H.pendingcb++,Bq(X,H)}}function Bq(X,H){H.pendingcb--,H.finished=!0;const L=H[N].splice(0);for(let l=0;l<L.length;l++)L[l]();if(X.emit("finish"),H.autoDestroy){const l=X._readableState;if(!l||l.autoDestroy&&(l.endEmitted||l.readable===!1))X.destroy()}}j(Y.prototype,{closed:{get(){return this._writableState?this._writableState.closed:!1}},destroyed:{get(){return this._writableState?this._writableState.destroyed:!1},set(X){if(this._writableState)this._writableState.destroyed=X}},writable:{get(){const X=this._writableState;return!!X&&X.writable!==!1&&!X.destroyed&&!X.errored&&!X.ending&&!X.ended},set(X){if(this._writableState)this._writableState.writable=!!X}},writableFinished:{get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{get(){const X=this._writableState;if(!X)return!1;return!X.destroyed&&!X.ending&&X.needDrain}},writableHighWaterMark:{get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{get(){return this._writableState?this._writableState.corked:0}},writableLength:{get(){return this._writableState&&this._writableState.length}},errored:{enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var Jq=_.destroy;Y.prototype.destroy=function(X,H){const L=this._writableState;if(!L.destroyed&&(L.bufferedIndex<L.buffered.length||L[N].length))Hq(a,L);return Jq.call(this,X,H),this},Y.prototype._undestroy=_.undestroy,Y.prototype._destroy=function(X,H){H(X)},Y.prototype[Tq.captureRejectionSymbol]=function(X){this.destroy(X)};var V;function h(){if(V===void 0)V={};return V}Y.fromWeb=function(X,H){return h().newStreamWritableFromWritableStream(X,H)},Y.toWeb=function(X){return h().newWritableStreamFromStreamWritable(X)}}}),ZQ=$q({"node_modules/readable-stream/lib/internal/streams/duplexify.js"(t,M){var{isReadable:B,isWritable:F,isIterable:y,isNodeStream:I,isReadableNodeStream:j,isWritableNodeStream:R,isDuplexNodeStream:x}=Iq(),g=jq(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:c,ERR_INVALID_RETURN_VALUE:_}}=Mq(),{destroyer:i}=Pq(),D=Lq(),p=Dq(),{createDeferredPromise:P}=Eq(),A=pq(),K=typeof Blob!=="undefined"?function o($){return $ instanceof Blob}:function o($){return!1},{FunctionPrototypeCall:U}=Wq();class T extends D{constructor(o){super(o);if((o===null||o===void 0?void 0:o.readable)===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if((o===null||o===void 0?void 0:o.writable)===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}}M.exports=function o($,s){if(x($))return $;if(j($))return qq({readable:$});if(R($))return qq({writable:$});if(I($))return qq({writable:!1,readable:!1});if(typeof $==="function"){const{value:Z,write:N,final:m,destroy:u}=C($);if(y(Z))return A(T,Z,{objectMode:!0,write:N,final:m,destroy:u});const J=Z===null||Z===void 0?void 0:Z.then;if(typeof J==="function"){let z;const w=U(J,Z,(S)=>{if(S!=null)throw new _("nully","body",S)},(S)=>{i(z,S)});return z=new T({objectMode:!0,readable:!1,write:N,final(S){m(async()=>{try{await w,Hq(S,null)}catch(E){Hq(S,E)}})},destroy:u})}throw new _("Iterable, AsyncIterable or AsyncFunction",s,Z)}if(K($))return o($.arrayBuffer());if(y($))return A(T,$,{objectMode:!0,writable:!1});if(typeof($===null||$===void 0?void 0:$.writable)==="object"||typeof($===null||$===void 0?void 0:$.readable)==="object"){const Z=$!==null&&$!==void 0&&$.readable?j($===null||$===void 0?void 0:$.readable)?$===null||$===void 0?void 0:$.readable:o($.readable):void 0,N=$!==null&&$!==void 0&&$.writable?R($===null||$===void 0?void 0:$.writable)?$===null||$===void 0?void 0:$.writable:o($.writable):void 0;return qq({readable:Z,writable:N})}const Y=$===null||$===void 0?void 0:$.then;if(typeof Y==="function"){let Z;return U(Y,$,(N)=>{if(N!=null)Z.push(N);Z.push(null)},(N)=>{i(Z,N)}),Z=new T({objectMode:!0,writable:!1,read(){}})}throw new c(s,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],$)};function C(o){let{promise:$,resolve:s}=P();const Y=new AbortController,Z=Y.signal;return{value:o(async function*(){while(!0){const m=$;$=null;const{chunk:u,done:J,cb:z}=await m;if(Hq(z),J)return;if(Z.aborted)throw new f(void 0,{cause:Z.reason});({promise:$,resolve:s}=P()),yield u}}(),{signal:Z}),write(m,u,J){const z=s;s=null,z({chunk:m,done:!1,cb:J})},final(m){const u=s;s=null,u({done:!0,cb:m})},destroy(m,u){Y.abort(),u(m)}}}function qq(o){const $=o.readable&&typeof o.readable.read!=="function"?p.wrap(o.readable):o.readable,s=o.writable;let Y=!!B($),Z=!!F(s),N,m,u,J,z;function w(S){const E=J;if(J=null,E)E(S);else if(S)z.destroy(S);else if(!Y&&!Z)z.destroy()}if(z=new T({readableObjectMode:!!($!==null&&$!==void 0&&$.readableObjectMode),writableObjectMode:!!(s!==null&&s!==void 0&&s.writableObjectMode),readable:Y,writable:Z}),Z)g(s,(S)=>{if(Z=!1,S)i($,S);w(S)}),z._write=function(S,E,W){if(s.write(S,E))W();else N=W},z._final=function(S){s.end(),m=S},s.on("drain",function(){if(N){const S=N;N=null,S()}}),s.on("finish",function(){if(m){const S=m;m=null,S()}});if(Y)g($,(S)=>{if(Y=!1,S)i($,S);w(S)}),$.on("readable",function(){if(u){const S=u;u=null,S()}}),$.on("end",function(){z.push(null)}),z._read=function(){while(!0){const S=$.read();if(S===null){u=z._read;return}if(!z.push(S))return}};return z._destroy=function(S,E){if(!S&&J!==null)S=new f;if(u=null,N=null,m=null,J===null)E(S);else J=E,i(s,S),i($,S)},z}}}),Lq=$q({"node_modules/readable-stream/lib/internal/streams/duplex.js"(t,M){var{ObjectDefineProperties:B,ObjectGetOwnPropertyDescriptor:F,ObjectKeys:y,ObjectSetPrototypeOf:I}=Wq(),j=Dq();function R(_){if(!(this instanceof R))return new R(_);if(j.call(this,_),Gq.call(this,_),_){if(this.allowHalfOpen=_.allowHalfOpen!==!1,_.readable===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if(_.writable===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}else this.allowHalfOpen=!0}M.exports=R,I(R.prototype,j.prototype),I(R,j);for(var x in Gq.prototype)if(!R.prototype[x])R.prototype[x]=Gq.prototype[x];B(R.prototype,{writable:F(Gq.prototype,"writable"),writableHighWaterMark:F(Gq.prototype,"writableHighWaterMark"),writableObjectMode:F(Gq.prototype,"writableObjectMode"),writableBuffer:F(Gq.prototype,"writableBuffer"),writableLength:F(Gq.prototype,"writableLength"),writableFinished:F(Gq.prototype,"writableFinished"),writableCorked:F(Gq.prototype,"writableCorked"),writableEnded:F(Gq.prototype,"writableEnded"),writableNeedDrain:F(Gq.prototype,"writableNeedDrain"),destroyed:{get(){if(this._readableState===void 0||this._writableState===void 0)return!1;return this._readableState.destroyed&&this._writableState.destroyed},set(_){if(this._readableState&&this._writableState)this._readableState.destroyed=_,this._writableState.destroyed=_}}});var g;function f(){if(g===void 0)g={};return g}R.fromWeb=function(_,i){return f().newStreamDuplexFromReadableWritablePair(_,i)},R.toWeb=function(_){return f().newReadableWritablePairFromDuplex(_)};var c;R.from=function(_){if(!c)c=ZQ();return c(_,"body")}}}),cq=$q({"node_modules/readable-stream/lib/internal/streams/transform.js"(t,M){var{ObjectSetPrototypeOf:B,Symbol:F}=Wq(),{ERR_METHOD_NOT_IMPLEMENTED:y}=Mq().codes,I=Lq();function j(f){if(!(this instanceof j))return new j(f);if(I.call(this,f),this._readableState.sync=!1,this[R]=null,f){if(typeof f.transform==="function")this._transform=f.transform;if(typeof f.flush==="function")this._flush=f.flush}this.on("prefinish",g.bind(this))}B(j.prototype,I.prototype),B(j,I),M.exports=j;var R=F("kCallback");function x(f){if(typeof this._flush==="function"&&!this.destroyed)this._flush((c,_)=>{if(c){if(f)f(c);else this.destroy(c);return}if(_!=null)this.push(_);if(this.push(null),f)f()});else if(this.push(null),f)f()}function g(){if(this._final!==x)x.call(this)}j.prototype._final=x,j.prototype._transform=function(f,c,_){throw new y("_transform()")},j.prototype._write=function(f,c,_){const i=this._readableState,D=this._writableState,p=i.length;this._transform(f,c,(P,A)=>{if(P){_(P);return}if(A!=null)this.push(A);if(D.ended||p===i.length||i.length<i.highWaterMark||i.highWaterMark===0||i.length===0)_();else this[R]=_})},j.prototype._read=function(){if(this[R]){const f=this[R];this[R]=null,f()}}}}),dq=$q({"node_modules/readable-stream/lib/internal/streams/passthrough.js"(t,M){var{ObjectSetPrototypeOf:B}=Wq(),F=cq();function y(I){if(!(this instanceof y))return new y(I);F.call(this,I)}B(y.prototype,F.prototype),B(y,F),y.prototype._transform=function(I,j,R){R(null,I)},M.exports=y}}),fq=$q({"node_modules/readable-stream/lib/internal/streams/pipeline.js"(t,M){var{ArrayIsArray:B,Promise:F,SymbolAsyncIterator:y}=Wq(),I=jq(),{once:j}=Eq(),R=Pq(),x=Lq(),{aggregateTwoErrors:g,codes:{ERR_INVALID_ARG_TYPE:f,ERR_INVALID_RETURN_VALUE:c,ERR_MISSING_ARGS:_,ERR_STREAM_DESTROYED:i},AbortError:D}=Mq(),{validateFunction:p,validateAbortSignal:P}=Cq(),{isIterable:A,isReadable:K,isReadableNodeStream:U,isNodeStream:T}=Iq(),C,qq;function o(J,z,w){let S=!1;J.on("close",()=>{S=!0});const E=I(J,{readable:z,writable:w},(W)=>{S=!W});return{destroy:(W)=>{if(S)return;S=!0,R.destroyer(J,W||new i("pipe"))},cleanup:E}}function $(J){return p(J[J.length-1],"streams[stream.length - 1]"),J.pop()}function s(J){if(A(J))return J;else if(U(J))return Y(J);throw new f("val",["Readable","Iterable","AsyncIterable"],J)}async function*Y(J){if(!qq)qq=Dq();yield*qq.prototype[y].call(J)}async function Z(J,z,w,{end:S}){let E,W=null;const b=(Qq)=>{if(Qq)E=Qq;if(W){const Zq=W;W=null,Zq()}},a=()=>new F((Qq,Zq)=>{if(E)Zq(E);else W=()=>{if(E)Zq(E);else Qq()}});z.on("drain",b);const r=I(z,{readable:!1},b);try{if(z.writableNeedDrain)await a();for await(let Qq of J)if(!z.write(Qq))await a();if(S)z.end();await a(),w()}catch(Qq){w(E!==Qq?g(E,Qq):Qq)}finally{r(),z.off("drain",b)}}function N(...J){return m(J,j($(J)))}function m(J,z,w){if(J.length===1&&B(J[0]))J=J[0];if(J.length<2)throw new _("streams");const S=new AbortController,E=S.signal,W=w===null||w===void 0?void 0:w.signal,b=[];P(W,"options.signal");function a(){Bq(new D)}W===null||W===void 0||W.addEventListener("abort",a);let r,Qq;const Zq=[];let Vq=0;function Xq(h){Bq(h,--Vq===0)}function Bq(h,X){if(h&&(!r||r.code==="ERR_STREAM_PREMATURE_CLOSE"))r=h;if(!r&&!X)return;while(Zq.length)Zq.shift()(r);if(W===null||W===void 0||W.removeEventListener("abort",a),S.abort(),X){if(!r)b.forEach((H)=>H());Hq(z,r,Qq)}}let Jq;for(let h=0;h<J.length;h++){const X=J[h],H=h<J.length-1,L=h>0,l=H||(w===null||w===void 0?void 0:w.end)!==!1,k=h===J.length-1;if(T(X)){let e=function(q){if(q&&q.name!=="AbortError"&&q.code!=="ERR_STREAM_PREMATURE_CLOSE")Xq(q)};if(l){const{destroy:q,cleanup:Q}=o(X,H,L);if(Zq.push(q),K(X)&&k)b.push(Q)}if(X.on("error",e),K(X)&&k)b.push(()=>{X.removeListener("error",e)})}if(h===0)if(typeof X==="function"){if(Jq=X({signal:E}),!A(Jq))throw new c("Iterable, AsyncIterable or Stream","source",Jq)}else if(A(X)||U(X))Jq=X;else Jq=x.from(X);else if(typeof X==="function")if(Jq=s(Jq),Jq=X(Jq,{signal:E}),H){if(!A(Jq,!0))throw new c("AsyncIterable",`transform[${h-1}]`,Jq)}else{var V;if(!C)C=dq();const e=new C({objectMode:!0}),q=(V=Jq)===null||V===void 0?void 0:V.then;if(typeof q==="function")Vq++,q.call(Jq,(G)=>{if(Qq=G,G!=null)e.write(G);if(l)e.end();Hq(Xq)},(G)=>{e.destroy(G),Hq(Xq,G)});else if(A(Jq,!0))Vq++,Z(Jq,e,Xq,{end:l});else throw new c("AsyncIterable or Promise","destination",Jq);Jq=e;const{destroy:Q,cleanup:O}=o(Jq,!1,!0);if(Zq.push(Q),k)b.push(O)}else if(T(X)){if(U(Jq)){Vq+=2;const e=u(Jq,X,Xq,{end:l});if(K(X)&&k)b.push(e)}else if(A(Jq))Vq++,Z(Jq,X,Xq,{end:l});else throw new f("val",["Readable","Iterable","AsyncIterable"],Jq);Jq=X}else Jq=x.from(X)}if(E!==null&&E!==void 0&&E.aborted||W!==null&&W!==void 0&&W.aborted)Hq(a);return Jq}function u(J,z,w,{end:S}){if(J.pipe(z,{end:S}),S)J.once("end",()=>z.end());else w();return I(J,{readable:!0,writable:!1},(E)=>{const W=J._readableState;if(E&&E.code==="ERR_STREAM_PREMATURE_CLOSE"&&W&&W.ended&&!W.errored&&!W.errorEmitted)J.once("end",w).once("error",w);else w(E)}),I(z,{readable:!1,writable:!0},w)}M.exports={pipelineImpl:m,pipeline:N}}}),BQ=$q({"node_modules/readable-stream/lib/internal/streams/compose.js"(t,M){var{pipeline:B}=fq(),F=Lq(),{destroyer:y}=Pq(),{isNodeStream:I,isReadable:j,isWritable:R}=Iq(),{AbortError:x,codes:{ERR_INVALID_ARG_VALUE:g,ERR_MISSING_ARGS:f}}=Mq();M.exports=function c(..._){if(_.length===0)throw new f("streams");if(_.length===1)return F.from(_[0]);const i=[..._];if(typeof _[0]==="function")_[0]=F.from(_[0]);if(typeof _[_.length-1]==="function"){const $=_.length-1;_[$]=F.from(_[$])}for(let $=0;$<_.length;++$){if(!I(_[$]))continue;if($<_.length-1&&!j(_[$]))throw new g(`streams[${$}]`,i[$],"must be readable");if($>0&&!R(_[$]))throw new g(`streams[${$}]`,i[$],"must be writable")}let D,p,P,A,K;function U($){const s=A;if(A=null,s)s($);else if($)K.destroy($);else if(!o&&!qq)K.destroy()}const T=_[0],C=B(_,U),qq=!!R(T),o=!!j(C);if(K=new F({writableObjectMode:!!(T!==null&&T!==void 0&&T.writableObjectMode),readableObjectMode:!!(C!==null&&C!==void 0&&C.writableObjectMode),writable:qq,readable:o}),qq)K._write=function($,s,Y){if(T.write($,s))Y();else D=Y},K._final=function($){T.end(),p=$},T.on("drain",function(){if(D){const $=D;D=null,$()}}),C.on("finish",function(){if(p){const $=p;p=null,$()}});if(o)C.on("readable",function(){if(P){const $=P;P=null,$()}}),C.on("end",function(){K.push(null)}),K._read=function(){while(!0){const $=C.read();if($===null){P=K._read;return}if(!K.push($))return}};return K._destroy=function($,s){if(!$&&A!==null)$=new x;if(P=null,D=null,p=null,A===null)s($);else A=s,y(C,$)},K}}}),lq=$q({"node_modules/readable-stream/lib/stream/promises.js"(t,M){var{ArrayPrototypePop:B,Promise:F}=Wq(),{isIterable:y,isNodeStream:I}=Iq(),{pipelineImpl:j}=fq(),{finished:R}=jq();function x(...g){return new F((f,c)=>{let _,i;const D=g[g.length-1];if(D&&typeof D==="object"&&!I(D)&&!y(D)){const p=B(g);_=p.signal,i=p.end}j(g,(p,P)=>{if(p)c(p);else f(P)},{signal:_,end:i})})}M.exports={finished:R,pipeline:x}}}),YQ=$q({"node_modules/readable-stream/lib/stream.js"(t,M){var{ObjectDefineProperty:B,ObjectKeys:F,ReflectApply:y}=Wq(),{promisify:{custom:I}}=Eq(),{streamReturningOperators:j,promiseReturningOperators:R}=HQ(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:x}}=Mq(),g=BQ(),{pipeline:f}=fq(),{destroyer:c}=Pq(),_=jq(),i=lq(),D=Iq(),p=M.exports=Sq().Stream;p.isDisturbed=D.isDisturbed,p.isErrored=D.isErrored,p.isWritable=D.isWritable,p.isReadable=D.isReadable,p.Readable=Dq();for(let A of F(j)){let K=function(...T){if(new.target)throw x();return p.Readable.from(y(U,this,T))};const U=j[A];B(K,"name",{value:U.name}),B(K,"length",{value:U.length}),B(p.Readable.prototype,A,{value:K,enumerable:!1,configurable:!0,writable:!0})}for(let A of F(R)){let K=function(...T){if(new.target)throw x();return y(U,this,T)};const U=R[A];B(K,"name",{value:U.name}),B(K,"length",{value:U.length}),B(p.Readable.prototype,A,{value:K,enumerable:!1,configurable:!0,writable:!0})}p.Writable=mq(),p.Duplex=Lq(),p.Transform=cq(),p.PassThrough=dq(),p.pipeline=f;var{addAbortSignal:P}=gq();p.addAbortSignal=P,p.finished=_,p.destroy=c,p.compose=g,B(p,"promises",{configurable:!0,enumerable:!0,get(){return i}}),B(f,I,{enumerable:!0,get(){return i.pipeline}}),B(_,I,{enumerable:!0,get(){return i.finished}}),p.Stream=p,p._isUint8Array=function A(K){return K instanceof Uint8Array},p._uint8ArrayToBuffer=function A(K){return new Buffer(K.buffer,K.byteOffset,K.byteLength)}}}),$Q=$q({"node_modules/readable-stream/lib/ours/index.js"(t,M){const B=YQ(),F=lq(),y=B.Readable.destroy;M.exports=B,M.exports._uint8ArrayToBuffer=B._uint8ArrayToBuffer,M.exports._isUint8Array=B._isUint8Array,M.exports.isDisturbed=B.isDisturbed,M.exports.isErrored=B.isErrored,M.exports.isWritable=B.isWritable,M.exports.isReadable=B.isReadable,M.exports.Readable=B.Readable,M.exports.Writable=B.Writable,M.exports.Duplex=B.Duplex,M.exports.Transform=B.Transform,M.exports.PassThrough=B.PassThrough,M.exports.addAbortSignal=B.addAbortSignal,M.exports.finished=B.finished,M.exports.destroy=B.destroy,M.exports.destroy=y,M.exports.pipeline=B.pipeline,M.exports.compose=B.compose,M.exports._getNativeReadableStreamPrototype=iq,M.exports.NativeWritable=nq,Uq.defineProperty(B,"promises",{configurable:!0,enumerable:!0,get(){return F}}),M.exports.Stream=B.Stream,M.exports.default=M.exports}}),VQ={0:void 0,1:void 0,2:void 0,3:void 0,4:void 0,5:void 0},Gq=mq(),nq=class t extends Gq{#q;#Q;#X=!0;_construct;_destroy;_final;constructor(M,B={}){super(B);this._construct=this.#H,this._destroy=this.#K,this._final=this.#Z,this.#q=M}#H(M){this._writableState.constructed=!0,this.constructed=!0,M()}#J(){if(typeof this.#q==="object")if(typeof this.#q.write==="function")this.#Q=this.#q;else throw new Error("Invalid FileSink");else this.#Q=Bun.file(this.#q).writer()}write(M,B,F,y=this.#X){if(!y)return this.#X=!1,super.write(M,B,F);if(!this.#Q)this.#J();var I=this.#Q,j=I.write(M);if(Oq(j))return j.then(()=>{this.emit("drain"),I.flush(!0)}),!1;if(I.flush(!0),F)F(null,M.byteLength);return!0}end(M,B,F,y=this.#X){return super.end(M,B,F,y)}#K(M,B){if(this._writableState.destroyed=!0,B)B(M)}#Z(M){if(this.#Q)this.#Q.end();if(M)M()}ref(){if(!this.#Q)this.#J();this.#Q.ref()}unref(){if(!this.#Q)return;this.#Q.unref()}},zq=$Q();zq[Symbol.for("CommonJS")]=0;zq[Symbol.for("::bunternal::")]={_ReadableFromWeb:uq,_ReadableFromWebForUndici:bq};var lQ=zq,TQ=zq._uint8ArrayToBuffer,PQ=zq._isUint8Array,xQ=zq.isDisturbed,OQ=zq.isErrored,_Q=zq.isWritable,CQ=zq.isReadable,DQ=zq.Readable,Gq=zq.Writable,wQ=zq.Duplex,vQ=zq.Transform,RQ=zq.PassThrough,SQ=zq.addAbortSignal,gQ=zq.finished,fQ=zq.destroy,kQ=zq.pipeline,yQ=zq.compose,WQ=zq.Stream,hQ=zq.eos=jq,pQ=zq._getNativeReadableStreamPrototype,nq=zq.NativeWritable,uQ=WQ.promises;export{uQ as promises,kQ as pipeline,_Q as isWritable,CQ as isReadable,OQ as isErrored,xQ as isDisturbed,gQ as finished,hQ as eos,fQ as destroy,lQ as default,yQ as compose,SQ as addAbortSignal,TQ as _uint8ArrayToBuffer,PQ as _isUint8Array,pQ as _getNativeReadableStreamPrototype,Gq as Writable,vQ as Transform,WQ as Stream,DQ as Readable,RQ as PassThrough,nq as NativeWritable,wQ as Duplex}; +import{EventEmitter as Iq} from"bun:events_native";import{StringDecoder as aq} from"node:string_decoder";var tq=function(a){return typeof a==="object"&&a!==null&&a instanceof ReadableStream},eq=function(a,j){if(typeof a!=="boolean")throw new qQ(j,"boolean",a)};var qQ=function(a,j,B){return new Error(`The argument '${a}' is invalid. Received '${B}' for type '${j}'`)},QQ=function(a,j,B){return new Error(`The value '${j}' is invalid for argument '${a}'. Reason: ${B}`)},YQ=function(a,j){var[B,G,y,A,M,R,P]=globalThis[Symbol.for("Bun.lazy")](a),g=[!1],k=function(E,I,Z,U){if(I>0){const T=Z.subarray(0,I),_=Z.subarray(I);if(T.byteLength>0)E.push(T);if(U)E.push(null);return _.byteLength>0?_:void 0}if(U)E.push(null);return Z},c=function(E,I,Z,U){if(I.byteLength>0)E.push(I);if(U)E.push(null);return Z},O=process.env.BUN_DISABLE_DYNAMIC_CHUNK_SIZE!=="1";const l=new FinalizationRegistry((E)=>E&&M(E)),D=512;var p=class E extends j{#q;#Q=1;#X=!1;#H=void 0;#J;#K=!1;#Z=!O;#B;constructor(I,Z={}){super(Z);if(typeof Z.highWaterMark==="number")this.#J=Z.highWaterMark;else this.#J=262144;this.#q=I,this.#X=!1,this.#H=void 0,this.#K=!1,this.#B={},l.register(this,this.#q,this.#B)}_read(I){if(this.#K)return;var Z=this.#q;if(Z===0){this.push(null);return}if(!this.#X)this.#$(Z);return this.#V(this.#z(I),Z)}#$(I){this.#X=!0;const Z=G(I,this.#J);if(typeof Z==="number"&&Z>1)this.#Z=!0,this.#J=Math.min(this.#J,Z);if(P){const U=P(I);if((U?.byteLength??0)>0)this.push(U)}}#z(I=this.#J){var Z=this.#H;if(Z?.byteLength??0<D){var U=I>D?I:D;this.#H=Z=new Buffer(U)}return Z}push(I,Z){return super.push(...arguments)}#Y(I,Z,U){if(typeof I==="number"){if(I>=this.#J&&!this.#Z&&!U)this.#J*=2,this.#Z=!0;return k(this,I,Z,U)}else if(typeof I==="boolean")return this.push(null),Z?.byteLength??0>0?Z:void 0;else if(ArrayBuffer.isView(I)){if(I.byteLength>=this.#J&&!this.#Z&&!U)this.#J*=2,this.#Z=!0;return c(this,I,Z,U)}else throw new Error("Invalid result from pull")}#V(I,Z){g[0]=!1;var U=B(Z,I,g);if(xq(U))return this.#K=!0,U.then((T)=>{this.#K=!1,this.#H=this.#Y(T,I,g[0])},(T)=>{errorOrDestroy(this,T)});else this.#H=this.#Y(U,I,g[0])}_destroy(I,Z){var U=this.#q;if(U===0){Z(I);return}if(l.unregister(this.#B),this.#q=0,R)R(U,!1);y(U,I),Z(I)}ref(){var I=this.#q;if(I===0)return;if(this.#Q++===0)R(I,!0)}unref(){var I=this.#q;if(I===0)return;if(this.#Q--===1)R(I,!1)}};if(!R)p.prototype.ref=void 0,p.prototype.unref=void 0;return p},lq=function(a,j){return $Q[a]||=YQ(a,j)},zQ=function(a,j,B){if(!(j&&typeof j==="object"&&j instanceof ReadableStream))return;const G=sq(j);if(!G){Gq("no native readable stream");return}const{stream:y,data:A}=G;return new(lq(A,a))(y,B)};var Gq=()=>{},{isPromise:xq,isCallable:oq,direct:sq,Object:zq}=globalThis[Symbol.for("Bun.lazy")]("primordials"),GQ=zq.create,MQ=zq.defineProperty,FQ=zq.getOwnPropertyDescriptor,rq=zq.getOwnPropertyNames,LQ=zq.getPrototypeOf,jQ=zq.prototype.hasOwnProperty,NQ=zq.setPrototypeOf,Bq=(a,j)=>function B(){return j||(0,a[rq(a)[0]])((j={exports:{}}).exports,j),j.exports};var Xq=process.nextTick;var AQ=Array.isArray,Vq=Bq({"node_modules/readable-stream/lib/ours/primordials.js"(a,j){j.exports={ArrayIsArray(B){return Array.isArray(B)},ArrayPrototypeIncludes(B,G){return B.includes(G)},ArrayPrototypeIndexOf(B,G){return B.indexOf(G)},ArrayPrototypeJoin(B,G){return B.join(G)},ArrayPrototypeMap(B,G){return B.map(G)},ArrayPrototypePop(B,G){return B.pop(G)},ArrayPrototypePush(B,G){return B.push(G)},ArrayPrototypeSlice(B,G,y){return B.slice(G,y)},Error,FunctionPrototypeCall(B,G,...y){return B.call(G,...y)},FunctionPrototypeSymbolHasInstance(B,G){return Function.prototype[Symbol.hasInstance].call(B,G)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(B,G){return zq.defineProperties(B,G)},ObjectDefineProperty(B,G,y){return zq.defineProperty(B,G,y)},ObjectGetOwnPropertyDescriptor(B,G){return zq.getOwnPropertyDescriptor(B,G)},ObjectKeys(B){return zq.keys(B)},ObjectSetPrototypeOf(B,G){return zq.setPrototypeOf(B,G)},Promise,PromisePrototypeCatch(B,G){return B.catch(G)},PromisePrototypeThen(B,G,y){return B.then(G,y)},PromiseReject(B){return Promise.reject(B)},ReflectApply:Reflect.apply,RegExpPrototypeTest(B,G){return B.test(G)},SafeSet:Set,String,StringPrototypeSlice(B,G,y){return B.slice(G,y)},StringPrototypeToLowerCase(B){return B.toLowerCase()},StringPrototypeToUpperCase(B){return B.toUpperCase()},StringPrototypeTrim(B){return B.trim()},Symbol,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,TypedArrayPrototypeSet(B,G,y){return B.set(G,y)},Uint8Array}}}),Aq=Bq({"node_modules/readable-stream/lib/ours/util.js"(a,j){var B=zq.getPrototypeOf(async function(){}).constructor,G=typeof Blob!=="undefined"?function A(M){return M instanceof Blob}:function A(M){return!1},y=class extends Error{constructor(A){if(!Array.isArray(A))throw new TypeError(`Expected input to be an Array, got ${typeof A}`);let M="";for(let R=0;R<A.length;R++)M+=` ${A[R].stack} +`;super(M);this.name="AggregateError",this.errors=A}};j.exports={AggregateError:y,once(A){let M=!1;return function(...R){if(M)return;M=!0,A.apply(this,R)}},createDeferredPromise:function(){let A,M;return{promise:new Promise((P,g)=>{A=P,M=g}),resolve:A,reject:M}},promisify(A){return new Promise((M,R)=>{A((P,...g)=>{if(P)return R(P);return M(...g)})})},debuglog(){return function(){}},format(A,...M){return A.replace(/%([sdifj])/g,function(...[R,P]){const g=M.shift();if(P==="f")return g.toFixed(6);else if(P==="j")return JSON.stringify(g);else if(P==="s"&&typeof g==="object")return`${g.constructor!==zq?g.constructor.name:""} {}`.trim();else return g.toString()})},inspect(A){switch(typeof A){case"string":if(A.includes("'")){if(!A.includes('"'))return`"${A}"`;else if(!A.includes("`")&&!A.includes("${"))return`\`${A}\``}return`'${A}'`;case"number":if(isNaN(A))return"NaN";else if(zq.is(A,-0))return String(A);return A;case"bigint":return`${String(A)}n`;case"boolean":case"undefined":return String(A);case"object":return"{}"}},types:{isAsyncFunction(A){return A instanceof B},isArrayBufferView(A){return ArrayBuffer.isView(A)}},isBlob:G},j.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}}),Wq=Bq({"node_modules/readable-stream/lib/ours/errors.js"(a,j){var{format:B,inspect:G,AggregateError:y}=Aq(),A=globalThis.AggregateError||y,M=Symbol("kIsNodeError"),R=["string","function","number","object","Function","Object","boolean","bigint","symbol"],P=/^([A-Z][a-z0-9]*)+$/,g="__node_internal_",k={};function c(Z,U){if(!Z)throw new k.ERR_INTERNAL_ASSERTION(U)}function O(Z){let U="",T=Z.length;const _=Z[0]==="-"?1:0;for(;T>=_+4;T-=3)U=`_${Z.slice(T-3,T)}${U}`;return`${Z.slice(0,T)}${U}`}function l(Z,U,T){if(typeof U==="function")return c(U.length<=T.length,`Code: ${Z}; The provided arguments length (${T.length}) does not match the required ones (${U.length}).`),U(...T);const _=(U.match(/%[dfijoOs]/g)||[]).length;if(c(_===T.length,`Code: ${Z}; The provided arguments length (${T.length}) does not match the required ones (${_}).`),T.length===0)return U;return B(U,...T)}function D(Z,U,T){if(!T)T=Error;class _ extends T{constructor(...t){super(l(Z,U,t))}toString(){return`${this.name} [${Z}]: ${this.message}`}}zq.defineProperties(_.prototype,{name:{value:T.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${Z}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),_.prototype.code=Z,_.prototype[M]=!0,k[Z]=_}function p(Z){const U=g+Z.name;return zq.defineProperty(Z,"name",{value:U}),Z}function E(Z,U){if(Z&&U&&Z!==U){if(Array.isArray(U.errors))return U.errors.push(Z),U;const T=new A([U,Z],U.message);return T.code=U.code,T}return Z||U}var I=class extends Error{constructor(Z="The operation was aborted",U=void 0){if(U!==void 0&&typeof U!=="object")throw new k.ERR_INVALID_ARG_TYPE("options","Object",U);super(Z,U);this.code="ABORT_ERR",this.name="AbortError"}};D("ERR_ASSERTION","%s",Error),D("ERR_INVALID_ARG_TYPE",(Z,U,T)=>{if(c(typeof Z==="string","'name' must be a string"),!Array.isArray(U))U=[U];let _="The ";if(Z.endsWith(" argument"))_+=`${Z} `;else _+=`"${Z}" ${Z.includes(".")?"property":"argument"} `;_+="must be ";const t=[],i=[],$=[];for(let Y of U)if(c(typeof Y==="string","All expected entries have to be of type string"),R.includes(Y))t.push(Y.toLowerCase());else if(P.test(Y))i.push(Y);else c(Y!=="object",'The value "object" should be written as "Object"'),$.push(Y);if(i.length>0){const Y=t.indexOf("object");if(Y!==-1)t.splice(t,Y,1),i.push("Object")}if(t.length>0){switch(t.length){case 1:_+=`of type ${t[0]}`;break;case 2:_+=`one of type ${t[0]} or ${t[1]}`;break;default:{const Y=t.pop();_+=`one of type ${t.join(", ")}, or ${Y}`}}if(i.length>0||$.length>0)_+=" or "}if(i.length>0){switch(i.length){case 1:_+=`an instance of ${i[0]}`;break;case 2:_+=`an instance of ${i[0]} or ${i[1]}`;break;default:{const Y=i.pop();_+=`an instance of ${i.join(", ")}, or ${Y}`}}if($.length>0)_+=" or "}switch($.length){case 0:break;case 1:if($[0].toLowerCase()!==$[0])_+="an ";_+=`${$[0]}`;break;case 2:_+=`one of ${$[0]} or ${$[1]}`;break;default:{const Y=$.pop();_+=`one of ${$.join(", ")}, or ${Y}`}}if(T==null)_+=`. Received ${T}`;else if(typeof T==="function"&&T.name)_+=`. Received function ${T.name}`;else if(typeof T==="object"){var n;if((n=T.constructor)!==null&&n!==void 0&&n.name)_+=`. Received an instance of ${T.constructor.name}`;else{const Y=G(T,{depth:-1});_+=`. Received ${Y}`}}else{let Y=G(T,{colors:!1});if(Y.length>25)Y=`${Y.slice(0,25)}...`;_+=`. Received type ${typeof T} (${Y})`}return _},TypeError),D("ERR_INVALID_ARG_VALUE",(Z,U,T="is invalid")=>{let _=G(U);if(_.length>128)_=_.slice(0,128)+"...";return`The ${Z.includes(".")?"property":"argument"} '${Z}' ${T}. Received ${_}`},TypeError),D("ERR_INVALID_RETURN_VALUE",(Z,U,T)=>{var _;const t=T!==null&&T!==void 0&&(_=T.constructor)!==null&&_!==void 0&&_.name?`instance of ${T.constructor.name}`:`type ${typeof T}`;return`Expected ${Z} to be returned from the "${U}" function but got ${t}.`},TypeError),D("ERR_MISSING_ARGS",(...Z)=>{c(Z.length>0,"At least one arg needs to be specified");let U;const T=Z.length;switch(Z=(Array.isArray(Z)?Z:[Z]).map((_)=>`"${_}"`).join(" or "),T){case 1:U+=`The ${Z[0]} argument`;break;case 2:U+=`The ${Z[0]} and ${Z[1]} arguments`;break;default:{const _=Z.pop();U+=`The ${Z.join(", ")}, and ${_} arguments`}break}return`${U} must be specified`},TypeError),D("ERR_OUT_OF_RANGE",(Z,U,T)=>{c(U,'Missing "range" argument');let _;if(Number.isInteger(T)&&Math.abs(T)>4294967296)_=O(String(T));else if(typeof T==="bigint"){if(_=String(T),T>2n**32n||T<-(2n**32n))_=O(_);_+="n"}else _=G(T);return`The value of "${Z}" is out of range. It must be ${U}. Received ${_}`},RangeError),D("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),D("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),D("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),D("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),D("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),D("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),D("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),D("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),D("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),D("ERR_STREAM_WRITE_AFTER_END","write after end",Error),D("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),j.exports={AbortError:I,aggregateTwoErrors:p(E),hideStackFrames:p,codes:k}}}),Cq=Bq({"node_modules/readable-stream/lib/internal/validators.js"(a,j){var{ArrayIsArray:B,ArrayPrototypeIncludes:G,ArrayPrototypeJoin:y,ArrayPrototypeMap:A,NumberIsInteger:M,NumberMAX_SAFE_INTEGER:R,NumberMIN_SAFE_INTEGER:P,NumberParseInt:g,RegExpPrototypeTest:k,String:c,StringPrototypeToUpperCase:O,StringPrototypeTrim:l}=Vq(),{hideStackFrames:D,codes:{ERR_SOCKET_BAD_PORT:p,ERR_INVALID_ARG_TYPE:E,ERR_INVALID_ARG_VALUE:I,ERR_OUT_OF_RANGE:Z,ERR_UNKNOWN_SIGNAL:U}}=Wq(),{normalizeEncoding:T}=Aq(),{isAsyncFunction:_,isArrayBufferView:t}=Aq().types,i={};function $(V){return V===(V|0)}function n(V){return V===V>>>0}var Y=/^[0-7]+$/,K="must be a 32-bit unsigned integer or an octal string";function F(V,h,Q){if(typeof V==="undefined")V=Q;if(typeof V==="string"){if(!k(Y,V))throw new I(h,V,K);V=g(V,8)}return u(V,h,0,4294967295),V}var m=D((V,h,Q=P,H=R)=>{if(typeof V!=="number")throw new E(h,"number",V);if(!M(V))throw new Z(h,"an integer",V);if(V<Q||V>H)throw new Z(h,`>= ${Q} && <= ${H}`,V)}),u=D((V,h,Q=-2147483648,H=2147483647)=>{if(typeof V!=="number")throw new E(h,"number",V);if(!$(V)){if(!M(V))throw new Z(h,"an integer",V);throw new Z(h,`>= ${Q} && <= ${H}`,V)}if(V<Q||V>H)throw new Z(h,`>= ${Q} && <= ${H}`,V)}),J=D((V,h,Q)=>{if(typeof V!=="number")throw new E(h,"number",V);if(!n(V)){if(!M(V))throw new Z(h,"an integer",V);throw new Z(h,`>= ${Q?1:0} && < 4294967296`,V)}if(Q&&V===0)throw new Z(h,">= 1 && < 4294967296",V)});function z(V,h){if(typeof V!=="string")throw new E(h,"string",V)}function w(V,h){if(typeof V!=="number")throw new E(h,"number",V)}var S=D((V,h,Q)=>{if(!G(Q,V)){const L="must be one of: "+y(A(Q,(d)=>typeof d==="string"?`'${d}'`:c(d)),", ");throw new I(h,V,L)}});function N(V,h){if(typeof V!=="boolean")throw new E(h,"boolean",V)}var W=D((V,h,Q)=>{const H=Q==null,L=H?!1:Q.allowArray,d=H?!1:Q.allowFunction;if(!(H?!1:Q.nullable)&&V===null||!L&&B(V)||typeof V!=="object"&&(!d||typeof V!=="function"))throw new E(h,"Object",V)}),b=D((V,h,Q=0)=>{if(!B(V))throw new E(h,"Array",V);if(V.length<Q){const H=`must be longer than ${Q}`;throw new I(h,V,H)}});function o(V,h="signal"){if(z(V,h),i[V]===void 0){if(i[O(V)]!==void 0)throw new U(V+" (signals must use all capital letters)");throw new U(V)}}var s=D((V,h="buffer")=>{if(!t(V))throw new E(h,["Buffer","TypedArray","DataView"],V)});function e(V,h){const Q=T(h),H=V.length;if(Q==="hex"&&H%2!==0)throw new I("encoding",h,`is invalid for data of length ${H}`)}function Hq(V,h="Port",Q=!0){if(typeof V!=="number"&&typeof V!=="string"||typeof V==="string"&&l(V).length===0||+V!==+V>>>0||V>65535||V===0&&!Q)throw new p(h,V,Q);return V|0}var $q=D((V,h)=>{if(V!==void 0&&(V===null||typeof V!=="object"||!("aborted"in V)))throw new E(h,"AbortSignal",V)}),qq=D((V,h)=>{if(typeof V!=="function")throw new E(h,"Function",V)}),Kq=D((V,h)=>{if(typeof V!=="function"||_(V))throw new E(h,"Function",V)}),Qq=D((V,h)=>{if(V!==void 0)throw new E(h,"undefined",V)});j.exports={isInt32:$,isUint32:n,parseFileMode:F,validateArray:b,validateBoolean:N,validateBuffer:s,validateEncoding:e,validateFunction:qq,validateInt32:u,validateInteger:m,validateNumber:w,validateObject:W,validateOneOf:S,validatePlainFunction:Kq,validatePort:Hq,validateSignalName:o,validateString:z,validateUint32:J,validateUndefined:Qq,validateAbortSignal:$q}}}),Eq=Bq({"node_modules/readable-stream/lib/internal/streams/utils.js"(a,j){var{Symbol:B,SymbolAsyncIterator:G,SymbolIterator:y}=Vq(),A=B("kDestroyed"),M=B("kIsErrored"),R=B("kIsReadable"),P=B("kIsDisturbed");function g(J,z=!1){var w;return!!(J&&typeof J.pipe==="function"&&typeof J.on==="function"&&(!z||typeof J.pause==="function"&&typeof J.resume==="function")&&(!J._writableState||((w=J._readableState)===null||w===void 0?void 0:w.readable)!==!1)&&(!J._writableState||J._readableState))}function k(J){var z;return!!(J&&typeof J.write==="function"&&typeof J.on==="function"&&(!J._readableState||((z=J._writableState)===null||z===void 0?void 0:z.writable)!==!1))}function c(J){return!!(J&&typeof J.pipe==="function"&&J._readableState&&typeof J.on==="function"&&typeof J.write==="function")}function O(J){return J&&(J._readableState||J._writableState||typeof J.write==="function"&&typeof J.on==="function"||typeof J.pipe==="function"&&typeof J.on==="function")}function l(J,z){if(J==null)return!1;if(z===!0)return typeof J[G]==="function";if(z===!1)return typeof J[y]==="function";return typeof J[G]==="function"||typeof J[y]==="function"}function D(J){if(!O(J))return null;const{_writableState:z,_readableState:w}=J,S=z||w;return!!(J.destroyed||J[A]||S!==null&&S!==void 0&&S.destroyed)}function p(J){if(!k(J))return null;if(J.writableEnded===!0)return!0;const z=J._writableState;if(z!==null&&z!==void 0&&z.errored)return!1;if(typeof(z===null||z===void 0?void 0:z.ended)!=="boolean")return null;return z.ended}function E(J,z){if(!k(J))return null;if(J.writableFinished===!0)return!0;const w=J._writableState;if(w!==null&&w!==void 0&&w.errored)return!1;if(typeof(w===null||w===void 0?void 0:w.finished)!=="boolean")return null;return!!(w.finished||z===!1&&w.ended===!0&&w.length===0)}function I(J){if(!g(J))return null;if(J.readableEnded===!0)return!0;const z=J._readableState;if(!z||z.errored)return!1;if(typeof(z===null||z===void 0?void 0:z.ended)!=="boolean")return null;return z.ended}function Z(J,z){if(!g(J))return null;const w=J._readableState;if(w!==null&&w!==void 0&&w.errored)return!1;if(typeof(w===null||w===void 0?void 0:w.endEmitted)!=="boolean")return null;return!!(w.endEmitted||z===!1&&w.ended===!0&&w.length===0)}function U(J){if(J&&J[R]!=null)return J[R];if(typeof(J===null||J===void 0?void 0:J.readable)!=="boolean")return null;if(D(J))return!1;return g(J)&&J.readable&&!Z(J)}function T(J){if(typeof(J===null||J===void 0?void 0:J.writable)!=="boolean")return null;if(D(J))return!1;return k(J)&&J.writable&&!p(J)}function _(J,z){if(!O(J))return null;if(D(J))return!0;if((z===null||z===void 0?void 0:z.readable)!==!1&&U(J))return!1;if((z===null||z===void 0?void 0:z.writable)!==!1&&T(J))return!1;return!0}function t(J){var z,w;if(!O(J))return null;if(J.writableErrored)return J.writableErrored;return(z=(w=J._writableState)===null||w===void 0?void 0:w.errored)!==null&&z!==void 0?z:null}function i(J){var z,w;if(!O(J))return null;if(J.readableErrored)return J.readableErrored;return(z=(w=J._readableState)===null||w===void 0?void 0:w.errored)!==null&&z!==void 0?z:null}function $(J){if(!O(J))return null;if(typeof J.closed==="boolean")return J.closed;const{_writableState:z,_readableState:w}=J;if(typeof(z===null||z===void 0?void 0:z.closed)==="boolean"||typeof(w===null||w===void 0?void 0:w.closed)==="boolean")return(z===null||z===void 0?void 0:z.closed)||(w===null||w===void 0?void 0:w.closed);if(typeof J._closed==="boolean"&&n(J))return J._closed;return null}function n(J){return typeof J._closed==="boolean"&&typeof J._defaultKeepAlive==="boolean"&&typeof J._removedConnection==="boolean"&&typeof J._removedContLen==="boolean"}function Y(J){return typeof J._sent100==="boolean"&&n(J)}function K(J){var z;return typeof J._consuming==="boolean"&&typeof J._dumped==="boolean"&&((z=J.req)===null||z===void 0?void 0:z.upgradeOrConnect)===void 0}function F(J){if(!O(J))return null;const{_writableState:z,_readableState:w}=J,S=z||w;return!S&&Y(J)||!!(S&&S.autoDestroy&&S.emitClose&&S.closed===!1)}function m(J){var z;return!!(J&&((z=J[P])!==null&&z!==void 0?z:J.readableDidRead||J.readableAborted))}function u(J){var z,w,S,N,W,b,o,s,e,Hq;return!!(J&&((z=(w=(S=(N=(W=(b=J[M])!==null&&b!==void 0?b:J.readableErrored)!==null&&W!==void 0?W:J.writableErrored)!==null&&N!==void 0?N:(o=J._readableState)===null||o===void 0?void 0:o.errorEmitted)!==null&&S!==void 0?S:(s=J._writableState)===null||s===void 0?void 0:s.errorEmitted)!==null&&w!==void 0?w:(e=J._readableState)===null||e===void 0?void 0:e.errored)!==null&&z!==void 0?z:(Hq=J._writableState)===null||Hq===void 0?void 0:Hq.errored))}j.exports={kDestroyed:A,isDisturbed:m,kIsDisturbed:P,isErrored:u,kIsErrored:M,isReadable:U,kIsReadable:R,isClosed:$,isDestroyed:D,isDuplexNodeStream:c,isFinished:_,isIterable:l,isReadableNodeStream:g,isReadableEnded:I,isReadableFinished:Z,isReadableErrored:i,isNodeStream:O,isWritable:T,isWritableNodeStream:k,isWritableEnded:p,isWritableFinished:E,isWritableErrored:t,isServerRequest:K,isServerResponse:Y,willEmitClose:F}}}),Fq=Bq({"node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(a,j){var{AbortError:B,codes:G}=Wq(),{ERR_INVALID_ARG_TYPE:y,ERR_STREAM_PREMATURE_CLOSE:A}=G,{once:M}=Aq(),{validateAbortSignal:R,validateFunction:P,validateObject:g}=Cq(),{Promise:k}=Vq(),{isClosed:c,isReadable:O,isReadableNodeStream:l,isReadableFinished:D,isReadableErrored:p,isWritable:E,isWritableNodeStream:I,isWritableFinished:Z,isWritableErrored:U,isNodeStream:T,willEmitClose:_}=Eq();function t(Y){return Y.setHeader&&typeof Y.abort==="function"}var i=()=>{};function $(Y,K,F){var m,u;if(arguments.length===2)F=K,K={};else if(K==null)K={};else g(K,"options");P(F,"callback"),R(K.signal,"options.signal"),F=M(F);const J=(m=K.readable)!==null&&m!==void 0?m:l(Y),z=(u=K.writable)!==null&&u!==void 0?u:I(Y);if(!T(Y))throw new y("stream","Stream",Y);const{_writableState:w,_readableState:S}=Y,N=()=>{if(!Y.writable)o()};let W=_(Y)&&l(Y)===J&&I(Y)===z,b=Z(Y,!1);const o=()=>{if(b=!0,Y.destroyed)W=!1;if(W&&(!Y.readable||J))return;if(!J||s)F.call(Y)};let s=D(Y,!1);const e=()=>{if(s=!0,Y.destroyed)W=!1;if(W&&(!Y.writable||z))return;if(!z||b)F.call(Y)},Hq=(V)=>{F.call(Y,V)};let $q=c(Y);const qq=()=>{$q=!0;const V=U(Y)||p(Y);if(V&&typeof V!=="boolean")return F.call(Y,V);if(J&&!s&&l(Y,!0)){if(!D(Y,!1))return F.call(Y,new A)}if(z&&!b){if(!Z(Y,!1))return F.call(Y,new A)}F.call(Y)},Kq=()=>{Y.req.on("finish",o)};if(t(Y)){if(Y.on("complete",o),!W)Y.on("abort",qq);if(Y.req)Kq();else Y.on("request",Kq)}else if(z&&!w)Y.on("end",N),Y.on("close",N);if(!W&&typeof Y.aborted==="boolean")Y.on("aborted",qq);if(Y.on("end",e),Y.on("finish",o),K.error!==!1)Y.on("error",Hq);if(Y.on("close",qq),$q)Xq(qq);else if(w!==null&&w!==void 0&&w.errorEmitted||S!==null&&S!==void 0&&S.errorEmitted){if(!W)Xq(qq)}else if(!J&&(!W||O(Y))&&(b||E(Y)===!1))Xq(qq);else if(!z&&(!W||E(Y))&&(s||O(Y)===!1))Xq(qq);else if(S&&Y.req&&Y.aborted)Xq(qq);const Qq=()=>{if(F=i,Y.removeListener("aborted",qq),Y.removeListener("complete",o),Y.removeListener("abort",qq),Y.removeListener("request",Kq),Y.req)Y.req.removeListener("finish",o);Y.removeListener("end",N),Y.removeListener("close",N),Y.removeListener("finish",o),Y.removeListener("end",e),Y.removeListener("error",Hq),Y.removeListener("close",qq)};if(K.signal&&!$q){const V=()=>{const h=F;Qq(),h.call(Y,new B(void 0,{cause:K.signal.reason}))};if(K.signal.aborted)Xq(V);else{const h=F;F=M((...Q)=>{K.signal.removeEventListener("abort",V),h.apply(Y,Q)}),K.signal.addEventListener("abort",V)}}return Qq}function n(Y,K){return new k((F,m)=>{$(Y,K,(u)=>{if(u)m(u);else F()})})}j.exports=$,j.exports.finished=n}}),XQ=Bq({"node_modules/readable-stream/lib/internal/streams/operators.js"(a,j){var{codes:{ERR_INVALID_ARG_TYPE:B,ERR_MISSING_ARGS:G,ERR_OUT_OF_RANGE:y},AbortError:A}=Wq(),{validateAbortSignal:M,validateInteger:R,validateObject:P}=Cq(),g=Vq().Symbol("kWeak"),{finished:k}=Fq(),{ArrayPrototypePush:c,MathFloor:O,Number:l,NumberIsNaN:D,Promise:p,PromiseReject:E,PromisePrototypeCatch:I,Symbol:Z}=Vq(),U=Z("kEmpty"),T=Z("kEof");function _(N,W){if(typeof N!=="function")throw new B("fn",["Function","AsyncFunction"],N);if(W!=null)P(W,"options");if((W===null||W===void 0?void 0:W.signal)!=null)M(W.signal,"options.signal");let b=1;if((W===null||W===void 0?void 0:W.concurrency)!=null)b=O(W.concurrency);return R(b,"concurrency",1),async function*o(){var s,e;const Hq=new AbortController,$q=this,qq=[],Kq=Hq.signal,Qq={signal:Kq},V=()=>Hq.abort();if(W!==null&&W!==void 0&&(s=W.signal)!==null&&s!==void 0&&s.aborted)V();W===null||W===void 0||(e=W.signal)===null||e===void 0||e.addEventListener("abort",V);let h,Q,H=!1;function L(){H=!0}async function d(){try{for await(let q of $q){var f;if(H)return;if(Kq.aborted)throw new A;try{q=N(q,Qq)}catch(X){q=E(X)}if(q===U)continue;if(typeof((f=q)===null||f===void 0?void 0:f.catch)==="function")q.catch(L);if(qq.push(q),h)h(),h=null;if(!H&&qq.length&&qq.length>=b)await new p((X)=>{Q=X})}qq.push(T)}catch(q){const X=E(q);I(X,L),qq.push(X)}finally{var r;if(H=!0,h)h(),h=null;W===null||W===void 0||(r=W.signal)===null||r===void 0||r.removeEventListener("abort",V)}}d();try{while(!0){while(qq.length>0){const f=await qq[0];if(f===T)return;if(Kq.aborted)throw new A;if(f!==U)yield f;if(qq.shift(),Q)Q(),Q=null}await new p((f)=>{h=f})}}finally{if(Hq.abort(),H=!0,Q)Q(),Q=null}}.call(this)}function t(N=void 0){if(N!=null)P(N,"options");if((N===null||N===void 0?void 0:N.signal)!=null)M(N.signal,"options.signal");return async function*W(){let b=0;for await(let s of this){var o;if(N!==null&&N!==void 0&&(o=N.signal)!==null&&o!==void 0&&o.aborted)throw new A({cause:N.signal.reason});yield[b++,s]}}.call(this)}async function i(N,W=void 0){for await(let b of K.call(this,N,W))return!0;return!1}async function $(N,W=void 0){if(typeof N!=="function")throw new B("fn",["Function","AsyncFunction"],N);return!await i.call(this,async(...b)=>{return!await N(...b)},W)}async function n(N,W){for await(let b of K.call(this,N,W))return b;return}async function Y(N,W){if(typeof N!=="function")throw new B("fn",["Function","AsyncFunction"],N);async function b(o,s){return await N(o,s),U}for await(let o of _.call(this,b,W));}function K(N,W){if(typeof N!=="function")throw new B("fn",["Function","AsyncFunction"],N);async function b(o,s){if(await N(o,s))return o;return U}return _.call(this,b,W)}var F=class extends G{constructor(){super("reduce");this.message="Reduce of an empty stream requires an initial value"}};async function m(N,W,b){var o;if(typeof N!=="function")throw new B("reducer",["Function","AsyncFunction"],N);if(b!=null)P(b,"options");if((b===null||b===void 0?void 0:b.signal)!=null)M(b.signal,"options.signal");let s=arguments.length>1;if(b!==null&&b!==void 0&&(o=b.signal)!==null&&o!==void 0&&o.aborted){const Kq=new A(void 0,{cause:b.signal.reason});throw this.once("error",()=>{}),await k(this.destroy(Kq)),Kq}const e=new AbortController,Hq=e.signal;if(b!==null&&b!==void 0&&b.signal){const Kq={once:!0,[g]:this};b.signal.addEventListener("abort",()=>e.abort(),Kq)}let $q=!1;try{for await(let Kq of this){var qq;if($q=!0,b!==null&&b!==void 0&&(qq=b.signal)!==null&&qq!==void 0&&qq.aborted)throw new A;if(!s)W=Kq,s=!0;else W=await N(W,Kq,{signal:Hq})}if(!$q&&!s)throw new F}finally{e.abort()}return W}async function u(N){if(N!=null)P(N,"options");if((N===null||N===void 0?void 0:N.signal)!=null)M(N.signal,"options.signal");const W=[];for await(let o of this){var b;if(N!==null&&N!==void 0&&(b=N.signal)!==null&&b!==void 0&&b.aborted)throw new A(void 0,{cause:N.signal.reason});c(W,o)}return W}function J(N,W){const b=_.call(this,N,W);return async function*o(){for await(let s of b)yield*s}.call(this)}function z(N){if(N=l(N),D(N))return 0;if(N<0)throw new y("number",">= 0",N);return N}function w(N,W=void 0){if(W!=null)P(W,"options");if((W===null||W===void 0?void 0:W.signal)!=null)M(W.signal,"options.signal");return N=z(N),async function*b(){var o;if(W!==null&&W!==void 0&&(o=W.signal)!==null&&o!==void 0&&o.aborted)throw new A;for await(let e of this){var s;if(W!==null&&W!==void 0&&(s=W.signal)!==null&&s!==void 0&&s.aborted)throw new A;if(N--<=0)yield e}}.call(this)}function S(N,W=void 0){if(W!=null)P(W,"options");if((W===null||W===void 0?void 0:W.signal)!=null)M(W.signal,"options.signal");return N=z(N),async function*b(){var o;if(W!==null&&W!==void 0&&(o=W.signal)!==null&&o!==void 0&&o.aborted)throw new A;for await(let e of this){var s;if(W!==null&&W!==void 0&&(s=W.signal)!==null&&s!==void 0&&s.aborted)throw new A;if(N-- >0)yield e;else return}}.call(this)}j.exports.streamReturningOperators={asIndexedPairs:t,drop:w,filter:K,flatMap:J,map:_,take:S},j.exports.promiseReturningOperators={every:$,forEach:Y,reduce:m,toArray:u,some:i,find:n}}}),Tq=Bq({"node_modules/readable-stream/lib/internal/streams/destroy.js"(a,j){var{aggregateTwoErrors:B,codes:{ERR_MULTIPLE_CALLBACK:G},AbortError:y}=Wq(),{Symbol:A}=Vq(),{kDestroyed:M,isDestroyed:R,isFinished:P,isServerRequest:g}=Eq(),k="#kDestroy",c="#kConstruct";function O(K,F,m){if(K){if(K.stack,F&&!F.errored)F.errored=K;if(m&&!m.errored)m.errored=K}}function l(K,F){const m=this._readableState,u=this._writableState,J=u||m;if(u&&u.destroyed||m&&m.destroyed){if(typeof F==="function")F();return this}if(O(K,u,m),u)u.destroyed=!0;if(m)m.destroyed=!0;if(!J.constructed)this.once(k,(z)=>{D(this,B(z,K),F)});else D(this,K,F);return this}function D(K,F,m){let u=!1;function J(z){if(u)return;u=!0;const{_readableState:w,_writableState:S}=K;if(O(z,S,w),S)S.closed=!0;if(w)w.closed=!0;if(typeof m==="function")m(z);if(z)Xq(p,K,z);else Xq(E,K)}try{K._destroy(F||null,J)}catch(z){J(z)}}function p(K,F){I(K,F),E(K)}function E(K){const{_readableState:F,_writableState:m}=K;if(m)m.closeEmitted=!0;if(F)F.closeEmitted=!0;if(m&&m.emitClose||F&&F.emitClose)K.emit("close")}function I(K,F){const m=K?._readableState,u=K?._writableState;if(u?.errorEmitted||m?.errorEmitted)return;if(u)u.errorEmitted=!0;if(m)m.errorEmitted=!0;K?.emit?.("error",F)}function Z(){const K=this._readableState,F=this._writableState;if(K)K.constructed=!0,K.closed=!1,K.closeEmitted=!1,K.destroyed=!1,K.errored=null,K.errorEmitted=!1,K.reading=!1,K.ended=K.readable===!1,K.endEmitted=K.readable===!1;if(F)F.constructed=!0,F.destroyed=!1,F.closed=!1,F.closeEmitted=!1,F.errored=null,F.errorEmitted=!1,F.finalCalled=!1,F.prefinished=!1,F.ended=F.writable===!1,F.ending=F.writable===!1,F.finished=F.writable===!1}function U(K,F,m){const u=K?._readableState,J=K?._writableState;if(J&&J.destroyed||u&&u.destroyed)return this;if(u&&u.autoDestroy||J&&J.autoDestroy)K.destroy(F);else if(F){if(Error.captureStackTrace(F),J&&!J.errored)J.errored=F;if(u&&!u.errored)u.errored=F;if(m)Xq(I,K,F);else I(K,F)}}function T(K,F){if(typeof K._construct!=="function")return;const{_readableState:m,_writableState:u}=K;if(m)m.constructed=!1;if(u)u.constructed=!1;if(K.once(c,F),K.listenerCount(c)>1)return;Xq(_,K)}function _(K){let F=!1;function m(u){if(F){U(K,u!==null&&u!==void 0?u:new G);return}F=!0;const{_readableState:J,_writableState:z}=K,w=z||J;if(J)J.constructed=!0;if(z)z.constructed=!0;if(w.destroyed)K.emit(k,u);else if(u)U(K,u,!0);else Xq(t,K)}try{K._construct(m)}catch(u){m(u)}}function t(K){K.emit(c)}function i(K){return K&&K.setHeader&&typeof K.abort==="function"}function $(K){K.emit("close")}function n(K,F){K.emit("error",F),Xq($,K)}function Y(K,F){if(!K||R(K))return;if(!F&&!P(K))F=new y;if(g(K))K.socket=null,K.destroy(F);else if(i(K))K.abort();else if(i(K.req))K.req.abort();else if(typeof K.destroy==="function")K.destroy(F);else if(typeof K.close==="function")K.close();else if(F)Xq(n,K);else Xq($,K);if(!K.destroyed)K[M]=!0}j.exports={construct:T,destroyer:Y,destroy:l,undestroy:Z,errorOrDestroy:U}}}),Rq=Bq({"node_modules/readable-stream/lib/internal/streams/legacy.js"(a,j){var{ArrayIsArray:B,ObjectSetPrototypeOf:G}=Vq();function y(M){if(!(this instanceof y))return new y(M);Iq.call(this,M)}G(y.prototype,Iq.prototype),G(y,Iq),y.prototype.pipe=function(M,R){const P=this;function g(E){if(M.writable&&M.write(E)===!1&&P.pause)P.pause()}P.on("data",g);function k(){if(P.readable&&P.resume)P.resume()}if(M.on("drain",k),!M._isStdio&&(!R||R.end!==!1))P.on("end",O),P.on("close",l);let c=!1;function O(){if(c)return;c=!0,M.end()}function l(){if(c)return;if(c=!0,typeof M.destroy==="function")M.destroy()}function D(E){if(p(),Iq.listenerCount(this,"error")===0)this.emit("error",E)}A(P,"error",D),A(M,"error",D);function p(){P.removeListener("data",g),M.removeListener("drain",k),P.removeListener("end",O),P.removeListener("close",l),P.removeListener("error",D),M.removeListener("error",D),P.removeListener("end",p),P.removeListener("close",p),M.removeListener("close",p)}return P.on("end",p),P.on("close",p),M.on("close",p),M.emit("pipe",P),M};function A(M,R,P){if(typeof M.prependListener==="function")return M.prependListener(R,P);if(!M._events||!M._events[R])M.on(R,P);else if(B(M._events[R]))M._events[R].unshift(P);else M._events[R]=[P,M._events[R]]}j.exports={Stream:y,prependListener:A}}}),Sq=Bq({"node_modules/readable-stream/lib/internal/streams/add-abort-signal.js"(a,j){var{AbortError:B,codes:G}=Wq(),y=Fq(),{ERR_INVALID_ARG_TYPE:A}=G,M=(P,g)=>{if(typeof P!=="object"||!("aborted"in P))throw new A(g,"AbortSignal",P)};function R(P){return!!(P&&typeof P.pipe==="function")}j.exports.addAbortSignal=function P(g,k){if(M(g,"signal"),!R(k))throw new A("stream","stream.Stream",k);return j.exports.addAbortSignalNoValidate(g,k)},j.exports.addAbortSignalNoValidate=function(P,g){if(typeof P!=="object"||!("aborted"in P))return g;const k=()=>{g.destroy(new B(void 0,{cause:P.reason}))};if(P.aborted)k();else P.addEventListener("abort",k),y(g,()=>P.removeEventListener("abort",k));return g}}}),JQ=Bq({"node_modules/readable-stream/lib/internal/streams/state.js"(a,j){var{MathFloor:B,NumberIsInteger:G}=Vq(),{ERR_INVALID_ARG_VALUE:y}=Wq().codes;function A(P,g,k){return P.highWaterMark!=null?P.highWaterMark:g?P[k]:null}function M(P){return P?16:16384}function R(P,g,k,c){const O=A(g,c,k);if(O!=null){if(!G(O)||O<0){const l=c?`options.${k}`:"options.highWaterMark";throw new y(l,O)}return B(O)}return M(P.objectMode)}j.exports={getHighWaterMark:R,getDefaultHighWaterMark:M}}}),hq=Bq({"node_modules/readable-stream/lib/internal/streams/from.js"(a,j){var{PromisePrototypeThen:B,SymbolAsyncIterator:G,SymbolIterator:y}=Vq(),{ERR_INVALID_ARG_TYPE:A,ERR_STREAM_NULL_VALUES:M}=Wq().codes;function R(P,g,k){let c;if(typeof g==="string"||g instanceof Buffer)return new P({objectMode:!0,...k,read(){this.push(g),this.push(null)}});let O;if(g&&g[G])O=!0,c=g[G]();else if(g&&g[y])O=!1,c=g[y]();else throw new A("iterable",["Iterable"],g);const l=new P({objectMode:!0,highWaterMark:1,...k});let D=!1;l._read=function(){if(!D)D=!0,E()},l._destroy=function(I,Z){B(p(I),()=>Xq(Z,I),(U)=>Xq(Z,U||I))};async function p(I){const Z=I!==void 0&&I!==null,U=typeof c.throw==="function";if(Z&&U){const{value:T,done:_}=await c.throw(I);if(await T,_)return}if(typeof c.return==="function"){const{value:T}=await c.return();await T}}async function E(){for(;;){try{const{value:I,done:Z}=O?await c.next():c.next();if(Z)l.push(null);else{const U=I&&typeof I.then==="function"?await I:I;if(U===null)throw D=!1,new M;else if(l.push(U))continue;else D=!1}}catch(I){l.destroy(I)}break}}return l}j.exports=R}}),pq,uq,_q=Bq({"node_modules/readable-stream/lib/internal/streams/readable.js"(a,j){var{ArrayPrototypeIndexOf:B,NumberIsInteger:G,NumberIsNaN:y,NumberParseInt:A,ObjectDefineProperties:M,ObjectKeys:R,ObjectSetPrototypeOf:P,Promise:g,SafeSet:k,SymbolAsyncIterator:c,Symbol:O}=Vq(),l=globalThis[Symbol.for("Bun.lazy")]("bun:stream").ReadableState,{Stream:D,prependListener:p}=Rq();function E(q){if(!(this instanceof E))return new E(q);const X=this instanceof Mq();if(this._readableState=new l(q,this,X),q){const{read:C,destroy:x,construct:v,signal:Jq}=q;if(typeof C==="function")this._read=C;if(typeof x==="function")this._destroy=x;if(typeof v==="function")this._construct=v;if(Jq&&!X)U(Jq,this)}D.call(this,q),K.construct(this,()=>{if(this._readableState.needReadable)n(this,this._readableState)})}P(E.prototype,D.prototype),P(E,D),E.prototype.on=function(q,X){const C=D.prototype.on.call(this,q,X),x=this._readableState;if(q==="data"){if(x.readableListening=this.listenerCount("readable")>0,x.flowing!==!1)this.resume()}else if(q==="readable"){if(!x.endEmitted&&!x.readableListening){if(x.readableListening=x.needReadable=!0,x.flowing=!1,x.emittedReadable=!1,x.length)Y(this,x);else if(!x.reading)Xq(Qq,this)}else if(x.endEmitted);}return C};class I extends E{#q;#Q;#X;#H;constructor(q,X){const{objectMode:C,highWaterMark:x,encoding:v,signal:Jq}=q;super({objectMode:C,highWaterMark:x,encoding:v,signal:Jq});this.#X=[],this.#q=void 0,this.#H=X,this.#Q=!1}#J(){var q=this.#X,X=0,C=q.length;for(;X<C;X++){const x=q[X];if(q[X]=void 0,!this.push(x,void 0))return this.#X=q.slice(X+1),!0}if(C>0)this.#X=[];return!1}#K(q){q.releaseLock(),this.#q=void 0,this.#Q=!0,this.push(null);return}async _read(){var q=this.#H,X=this.#q;if(q)X=this.#q=q.getReader(),this.#H=void 0;else if(this.#J())return;var C;try{do{var x=!1,v;const Jq=X.readMany();if(xq(Jq)){if({done:x,value:v}=await Jq,this.#Q){this.#X.push(...v);return}}else({done:x,value:v}=Jq);if(x){this.#K(X);return}if(!this.push(v[0])){this.#X=v.slice(1);return}for(let Zq=1,Oq=v.length;Zq<Oq;Zq++)if(!this.push(v[Zq])){this.#X=v.slice(Zq+1);return}}while(!this.#Q)}catch(Jq){C=Jq}finally{if(C)throw C}}_destroy(q,X){if(!this.#Q){var C=this.#q;if(C)this.#q=void 0,C.cancel(q).finally(()=>{this.#Q=!0,X(q)});return}try{X(q)}catch(x){globalThis.reportError(x)}}}uq=I;function Z(q,X={}){if(!tq(q))throw new m("readableStream","ReadableStream",q);S(X,"options");const{highWaterMark:C,encoding:x,objectMode:v=!1,signal:Jq}=X;if(x!==void 0&&!Buffer.isEncoding(x))throw new QQ(x,"options.encoding");return eq(v,"options.objectMode"),zQ(E,q,X)||new I({highWaterMark:C,encoding:x,objectMode:v,signal:Jq},q)}j.exports=E,pq=Z;var{addAbortSignal:U}=Sq(),T=Fq();const{maybeReadMore:_,resume:t,emitReadable:i,onEofChunk:$}=globalThis[Symbol.for("Bun.lazy")]("bun:stream");function n(q,X){process.nextTick(_,q,X)}function Y(q,X){i(q,X)}var K=Tq(),{aggregateTwoErrors:F,codes:{ERR_INVALID_ARG_TYPE:m,ERR_METHOD_NOT_IMPLEMENTED:u,ERR_OUT_OF_RANGE:J,ERR_STREAM_PUSH_AFTER_EOF:z,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:w}}=Wq(),{validateObject:S}=Cq(),N=hq(),W=()=>{},{errorOrDestroy:b}=K;E.prototype.destroy=K.destroy,E.prototype._undestroy=K.undestroy,E.prototype._destroy=function(q,X){X(q)},E.prototype[Iq.captureRejectionSymbol]=function(q){this.destroy(q)},E.prototype.push=function(q,X){return o(this,q,X,!1)},E.prototype.unshift=function(q,X){return o(this,q,X,!0)};function o(q,X,C,x){const v=q._readableState;let Jq;if(!v.objectMode){if(typeof X==="string"){if(C=C||v.defaultEncoding,v.encoding!==C)if(x&&v.encoding)X=Buffer.from(X,C).toString(v.encoding);else X=Buffer.from(X,C),C=""}else if(X instanceof Buffer)C="";else if(D._isUint8Array(X)){if(x||!v.decoder)X=D._uint8ArrayToBuffer(X);C=""}else if(X!=null)Jq=new m("chunk",["string","Buffer","Uint8Array"],X)}if(Jq)b(q,Jq);else if(X===null)v.reading=!1,$(q,v);else if(v.objectMode||X&&X.length>0)if(x)if(v.endEmitted)b(q,new w);else if(v.destroyed||v.errored)return!1;else s(q,v,X,!0);else if(v.ended)b(q,new z);else if(v.destroyed||v.errored)return!1;else if(v.reading=!1,v.decoder&&!C)if(X=v.decoder.write(X),v.objectMode||X.length!==0)s(q,v,X,!1);else n(q,v);else s(q,v,X,!1);else if(!x)v.reading=!1,n(q,v);return!v.ended&&(v.length<v.highWaterMark||v.length===0)}function s(q,X,C,x){if(X.flowing&&X.length===0&&!X.sync&&q.listenerCount("data")>0){if(X.multiAwaitDrain)X.awaitDrainWriters.clear();else X.awaitDrainWriters=null;X.dataEmitted=!0,q.emit("data",C)}else{if(X.length+=X.objectMode?1:C.length,x)X.buffer.unshift(C);else X.buffer.push(C);if(X.needReadable)Y(q,X)}n(q,X)}E.prototype.isPaused=function(){const q=this._readableState;return q.paused===!0||q.flowing===!1},E.prototype.setEncoding=function(q){const X=new aq(q);this._readableState.decoder=X,this._readableState.encoding=this._readableState.decoder.encoding;const C=this._readableState.buffer;let x="";for(let v=C.length;v>0;v--)x+=X.write(C.shift());if(x!=="")C.push(x);return this._readableState.length=x.length,this};var e=1073741824;function Hq(q){if(q>e)throw new J("size","<= 1GiB",q);else q--,q|=q>>>1,q|=q>>>2,q|=q>>>4,q|=q>>>8,q|=q>>>16,q++;return q}function $q(q,X){if(q<=0||X.length===0&&X.ended)return 0;if(X.objectMode)return 1;if(y(q)){if(X.flowing&&X.length)return X.buffer.first().length;return X.length}if(q<=X.length)return q;return X.ended?X.length:0}E.prototype.read=function(q){if(!G(q))q=A(q,10);const X=this._readableState,C=q;if(q>X.highWaterMark)X.highWaterMark=Hq(q);if(q!==0)X.emittedReadable=!1;if(q===0&&X.needReadable&&((X.highWaterMark!==0?X.length>=X.highWaterMark:X.length>0)||X.ended)){if(X.length===0&&X.ended)H(this);else Y(this,X);return null}if(q=$q(q,X),q===0&&X.ended){if(X.length===0)H(this);return null}let x=X.needReadable;if(X.length===0||X.length-q<X.highWaterMark)x=!0;if(X.ended||X.reading||X.destroyed||X.errored||!X.constructed)x=!1;else if(x){if(X.reading=!0,X.sync=!0,X.length===0)X.needReadable=!0;try{var v=this._read(X.highWaterMark);if(xq(v)){const Zq=Bun.peek(v);if(Zq!==v)v=Zq}if(xq(v)&&v?.then&&oq(v.then))v.then(W,function(Zq){b(this,Zq)})}catch(Zq){b(this,Zq)}if(X.sync=!1,!X.reading)q=$q(C,X)}let Jq;if(q>0)Jq=Q(q,X);else Jq=null;if(Jq===null)X.needReadable=X.length<=X.highWaterMark,q=0;else if(X.length-=q,X.multiAwaitDrain)X.awaitDrainWriters.clear();else X.awaitDrainWriters=null;if(X.length===0){if(!X.ended)X.needReadable=!0;if(C!==q&&X.ended)H(this)}if(Jq!==null&&!X.errorEmitted&&!X.closeEmitted)X.dataEmitted=!0,this.emit("data",Jq);return Jq},E.prototype._read=function(q){throw new u("_read()")},E.prototype.pipe=function(q,X){const C=this,x=this._readableState;if(x.pipes.length===1){if(!x.multiAwaitDrain)x.multiAwaitDrain=!0,x.awaitDrainWriters=new k(x.awaitDrainWriters?[x.awaitDrainWriters]:[])}x.pipes.push(q);const Jq=(!X||X.end!==!1)&&q!==process.stdout&&q!==process.stderr?Oq:Pq;if(x.endEmitted)Xq(Jq);else C.once("end",Jq);q.on("unpipe",Zq);function Zq(jq,Nq){if(jq===C){if(Nq&&Nq.hasUnpiped===!1)Nq.hasUnpiped=!0,nq()}}function Oq(){q.end()}let Lq,kq=!1;function nq(){if(q.removeListener("close",wq),q.removeListener("finish",vq),Lq)q.removeListener("drain",Lq);if(q.removeListener("error",Dq),q.removeListener("unpipe",Zq),C.removeListener("end",Oq),C.removeListener("end",Pq),C.removeListener("data",yq),kq=!0,Lq&&x.awaitDrainWriters&&(!q._writableState||q._writableState.needDrain))Lq()}function fq(){if(!kq){if(x.pipes.length===1&&x.pipes[0]===q)x.awaitDrainWriters=q,x.multiAwaitDrain=!1;else if(x.pipes.length>1&&x.pipes.includes(q))x.awaitDrainWriters.add(q);C.pause()}if(!Lq)Lq=qq(C,q),q.on("drain",Lq)}C.on("data",yq);function yq(jq){if(q.write(jq)===!1)fq()}function Dq(jq){if(Gq("onerror",jq),Pq(),q.removeListener("error",Dq),q.listenerCount("error")===0){const Nq=q._writableState||q._readableState;if(Nq&&!Nq.errorEmitted)b(q,jq);else q.emit("error",jq)}}p(q,"error",Dq);function wq(){q.removeListener("finish",vq),Pq()}q.once("close",wq);function vq(){Gq("onfinish"),q.removeListener("close",wq),Pq()}q.once("finish",vq);function Pq(){Gq("unpipe"),C.unpipe(q)}if(q.emit("pipe",C),q.writableNeedDrain===!0){if(x.flowing)fq()}else if(!x.flowing)Gq("pipe resume"),C.resume();return q};function qq(q,X){return function C(){const x=q._readableState;if(x.awaitDrainWriters===X)Gq("pipeOnDrain",1),x.awaitDrainWriters=null;else if(x.multiAwaitDrain)Gq("pipeOnDrain",x.awaitDrainWriters.size),x.awaitDrainWriters.delete(X);if((!x.awaitDrainWriters||x.awaitDrainWriters.size===0)&&q.listenerCount("data"))q.resume()}}E.prototype.unpipe=function(q){const X=this._readableState,C={hasUnpiped:!1};if(X.pipes.length===0)return this;if(!q){const v=X.pipes;X.pipes=[],this.pause();for(let Jq=0;Jq<v.length;Jq++)v[Jq].emit("unpipe",this,{hasUnpiped:!1});return this}const x=B(X.pipes,q);if(x===-1)return this;if(X.pipes.splice(x,1),X.pipes.length===0)this.pause();return q.emit("unpipe",this,C),this},E.prototype.addListener=E.prototype.on,E.prototype.removeListener=function(q,X){const C=D.prototype.removeListener.call(this,q,X);if(q==="readable")Xq(Kq,this);return C},E.prototype.off=E.prototype.removeListener,E.prototype.removeAllListeners=function(q){const X=D.prototype.removeAllListeners.apply(this,arguments);if(q==="readable"||q===void 0)Xq(Kq,this);return X};function Kq(q){const X=q._readableState;if(X.readableListening=q.listenerCount("readable")>0,X.resumeScheduled&&X.paused===!1)X.flowing=!0;else if(q.listenerCount("data")>0)q.resume();else if(!X.readableListening)X.flowing=null}function Qq(q){q.read(0)}E.prototype.resume=function(){const q=this._readableState;if(!q.flowing)q.flowing=!q.readableListening,t(this,q);return q.paused=!1,this},E.prototype.pause=function(){if(this._readableState.flowing!==!1)this._readableState.flowing=!1,this.emit("pause");return this._readableState.paused=!0,this},E.prototype.wrap=function(q){let X=!1;q.on("data",(x)=>{if(!this.push(x)&&q.pause)X=!0,q.pause()}),q.on("end",()=>{this.push(null)}),q.on("error",(x)=>{b(this,x)}),q.on("close",()=>{this.destroy()}),q.on("destroy",()=>{this.destroy()}),this._read=()=>{if(X&&q.resume)X=!1,q.resume()};const C=R(q);for(let x=1;x<C.length;x++){const v=C[x];if(this[v]===void 0&&typeof q[v]==="function")this[v]=q[v].bind(q)}return this},E.prototype[c]=function(){return V(this)},E.prototype.iterator=function(q){if(q!==void 0)S(q,"options");return V(this,q)};function V(q,X){if(typeof q.read!=="function")q=E.wrap(q,{objectMode:!0});const C=h(q,X);return C.stream=q,C}async function*h(q,X){let C=W;function x(Zq){if(this===q)C(),C=W;else C=Zq}q.on("readable",x);let v;const Jq=T(q,{writable:!1},(Zq)=>{v=Zq?F(v,Zq):null,C(),C=W});try{while(!0){const Zq=q.destroyed?null:q.read();if(Zq!==null)yield Zq;else if(v)throw v;else if(v===null)return;else await new g(x)}}catch(Zq){throw v=F(v,Zq),v}finally{if((v||(X===null||X===void 0?void 0:X.destroyOnReturn)!==!1)&&(v===void 0||q._readableState.autoDestroy))K.destroyer(q,null);else q.off("readable",x),Jq()}}M(E.prototype,{readable:{get(){const q=this._readableState;return!!q&&q.readable!==!1&&!q.destroyed&&!q.errorEmitted&&!q.endEmitted},set(q){if(this._readableState)this._readableState.readable=!!q}},readableDidRead:{enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{enumerable:!1,get:function(){return this._readableState.flowing},set:function(q){if(this._readableState)this._readableState.flowing=q}},readableLength:{enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{get(){return this._readableState?this._readableState.closed:!1}},destroyed:{enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(q){if(!this._readableState)return;this._readableState.destroyed=q}},readableEnded:{enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),E._fromList=Q;function Q(q,X){if(X.length===0)return null;let C;if(X.objectMode)C=X.buffer.shift();else if(!q||q>=X.length){if(X.decoder)C=X.buffer.join("");else if(X.buffer.length===1)C=X.buffer.first();else C=X.buffer.concat(X.length);X.buffer.clear()}else C=X.buffer.consume(q,X.decoder);return C}function H(q){const X=q._readableState;if(!X.endEmitted)X.ended=!0,Xq(L,X,q)}function L(q,X){if(!q.errored&&!q.closeEmitted&&!q.endEmitted&&q.length===0){if(q.endEmitted=!0,X.emit("end"),X.writable&&X.allowHalfOpen===!1)Xq(d,X);else if(q.autoDestroy){const C=X._writableState;if(!C||C.autoDestroy&&(C.finished||C.writable===!1))X.destroy()}}}function d(q){if(q.writable&&!q.writableEnded&&!q.destroyed)q.end()}E.from=function(q,X){return N(E,q,X)};var f={newStreamReadableFromReadableStream:Z};function r(){if(f===void 0)f={};return f}E.fromWeb=function(q,X){return r().newStreamReadableFromReadableStream(q,X)},E.toWeb=function(q){return r().newReadableStreamFromStreamReadable(q)},E.wrap=function(q,X){var C,x;return new E({objectMode:(C=(x=q.readableObjectMode)!==null&&x!==void 0?x:q.objectMode)!==null&&C!==void 0?C:!0,...X,destroy(v,Jq){K.destroyer(q,v),Jq(v)}}).wrap(q)}}}),bq=Bq({"node_modules/readable-stream/lib/internal/streams/writable.js"(a,j){var{ArrayPrototypeSlice:B,Error:G,FunctionPrototypeSymbolHasInstance:y,ObjectDefineProperty:A,ObjectDefineProperties:M,ObjectSetPrototypeOf:R,StringPrototypeToLowerCase:P,Symbol:g,SymbolHasInstance:k}=Vq(),c=Rq().Stream,O=Tq(),{addAbortSignal:l}=Sq(),{getHighWaterMark:D,getDefaultHighWaterMark:p}=JQ(),{ERR_INVALID_ARG_TYPE:E,ERR_METHOD_NOT_IMPLEMENTED:I,ERR_MULTIPLE_CALLBACK:Z,ERR_STREAM_CANNOT_PIPE:U,ERR_STREAM_DESTROYED:T,ERR_STREAM_ALREADY_FINISHED:_,ERR_STREAM_NULL_VALUES:t,ERR_STREAM_WRITE_AFTER_END:i,ERR_UNKNOWN_ENCODING:$}=Wq().codes,{errorOrDestroy:n}=O;function Y(Q={}){const H=this instanceof Mq();if(!H&&!y(Y,this))return new Y(Q);if(this._writableState=new m(Q,this,H),Q){if(typeof Q.write==="function")this._write=Q.write;if(typeof Q.writev==="function")this._writev=Q.writev;if(typeof Q.destroy==="function")this._destroy=Q.destroy;if(typeof Q.final==="function")this._final=Q.final;if(typeof Q.construct==="function")this._construct=Q.construct;if(Q.signal)l(Q.signal,this)}c.call(this,Q),O.construct(this,()=>{const L=this._writableState;if(!L.writing)s(this,L);qq(this,L)})}R(Y.prototype,c.prototype),R(Y,c),j.exports=Y;function K(){}var F=g("kOnFinished");function m(Q,H,L){if(typeof L!=="boolean")L=H instanceof Mq();if(this.objectMode=!!(Q&&Q.objectMode),L)this.objectMode=this.objectMode||!!(Q&&Q.writableObjectMode);this.highWaterMark=Q?D(this,Q,"writableHighWaterMark",L):p(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;const d=!!(Q&&Q.decodeStrings===!1);this.decodeStrings=!d,this.defaultEncoding=Q&&Q.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=N.bind(void 0,H),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,u(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!Q||Q.emitClose!==!1,this.autoDestroy=!Q||Q.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[F]=[]}function u(Q){Q.buffered=[],Q.bufferedIndex=0,Q.allBuffers=!0,Q.allNoop=!0}m.prototype.getBuffer=function Q(){return B(this.buffered,this.bufferedIndex)},A(m.prototype,"bufferedRequestCount",{get(){return this.buffered.length-this.bufferedIndex}}),A(Y,k,{value:function(Q){if(y(this,Q))return!0;if(this!==Y)return!1;return Q&&Q._writableState instanceof m}}),Y.prototype.pipe=function(){n(this,new U)};function J(Q,H,L,d){const f=Q._writableState;if(typeof L==="function")d=L,L=f.defaultEncoding;else{if(!L)L=f.defaultEncoding;else if(L!=="buffer"&&!Buffer.isEncoding(L))throw new $(L);if(typeof d!=="function")d=K}if(H===null)throw new t;else if(!f.objectMode)if(typeof H==="string"){if(f.decodeStrings!==!1)H=Buffer.from(H,L),L="buffer"}else if(H instanceof Buffer)L="buffer";else if(c._isUint8Array(H))H=c._uint8ArrayToBuffer(H),L="buffer";else throw new E("chunk",["string","Buffer","Uint8Array"],H);let r;if(f.ending)r=new i;else if(f.destroyed)r=new T("write");if(r)return Xq(d,r),n(Q,r,!0),r;return f.pendingcb++,z(Q,f,H,L,d)}Y.prototype.write=function(Q,H,L){return J(this,Q,H,L)===!0},Y.prototype.cork=function(){this._writableState.corked++},Y.prototype.uncork=function(){const Q=this._writableState;if(Q.corked){if(Q.corked--,!Q.writing)s(this,Q)}},Y.prototype.setDefaultEncoding=function Q(H){if(typeof H==="string")H=P(H);if(!Buffer.isEncoding(H))throw new $(H);return this._writableState.defaultEncoding=H,this};function z(Q,H,L,d,f){const r=H.objectMode?1:L.length;H.length+=r;const q=H.length<H.highWaterMark;if(!q)H.needDrain=!0;if(H.writing||H.corked||H.errored||!H.constructed){if(H.buffered.push({chunk:L,encoding:d,callback:f}),H.allBuffers&&d!=="buffer")H.allBuffers=!1;if(H.allNoop&&f!==K)H.allNoop=!1}else H.writelen=r,H.writecb=f,H.writing=!0,H.sync=!0,Q._write(L,d,H.onwrite),H.sync=!1;return q&&!H.errored&&!H.destroyed}function w(Q,H,L,d,f,r,q){if(H.writelen=d,H.writecb=q,H.writing=!0,H.sync=!0,H.destroyed)H.onwrite(new T("write"));else if(L)Q._writev(f,H.onwrite);else Q._write(f,r,H.onwrite);H.sync=!1}function S(Q,H,L,d){--H.pendingcb,d(L),o(H),n(Q,L)}function N(Q,H){const L=Q._writableState,d=L.sync,f=L.writecb;if(typeof f!=="function"){n(Q,new Z);return}if(L.writing=!1,L.writecb=null,L.length-=L.writelen,L.writelen=0,H){if(Error.captureStackTrace(H),!L.errored)L.errored=H;if(Q._readableState&&!Q._readableState.errored)Q._readableState.errored=H;if(d)Xq(S,Q,L,H,f);else S(Q,L,H,f)}else{if(L.buffered.length>L.bufferedIndex)s(Q,L);if(d)if(L.afterWriteTickInfo!==null&&L.afterWriteTickInfo.cb===f)L.afterWriteTickInfo.count++;else L.afterWriteTickInfo={count:1,cb:f,stream:Q,state:L},Xq(W,L.afterWriteTickInfo);else b(Q,L,1,f)}}function W({stream:Q,state:H,count:L,cb:d}){return H.afterWriteTickInfo=null,b(Q,H,L,d)}function b(Q,H,L,d){if(!H.ending&&!Q.destroyed&&H.length===0&&H.needDrain)H.needDrain=!1,Q.emit("drain");while(L-- >0)H.pendingcb--,d();if(H.destroyed)o(H);qq(Q,H)}function o(Q){if(Q.writing)return;for(let f=Q.bufferedIndex;f<Q.buffered.length;++f){var H;const{chunk:r,callback:q}=Q.buffered[f],X=Q.objectMode?1:r.length;Q.length-=X,q((H=Q.errored)!==null&&H!==void 0?H:new T("write"))}const L=Q[F].splice(0);for(let f=0;f<L.length;f++){var d;L[f]((d=Q.errored)!==null&&d!==void 0?d:new T("end"))}u(Q)}function s(Q,H){if(H.corked||H.bufferProcessing||H.destroyed||!H.constructed)return;const{buffered:L,bufferedIndex:d,objectMode:f}=H,r=L.length-d;if(!r)return;let q=d;if(H.bufferProcessing=!0,r>1&&Q._writev){H.pendingcb-=r-1;const X=H.allNoop?K:(x)=>{for(let v=q;v<L.length;++v)L[v].callback(x)},C=H.allNoop&&q===0?L:B(L,q);C.allBuffers=H.allBuffers,w(Q,H,!0,H.length,C,"",X),u(H)}else{do{const{chunk:X,encoding:C,callback:x}=L[q];L[q++]=null;const v=f?1:X.length;w(Q,H,!1,v,X,C,x)}while(q<L.length&&!H.writing);if(q===L.length)u(H);else if(q>256)L.splice(0,q),H.bufferedIndex=0;else H.bufferedIndex=q}H.bufferProcessing=!1}Y.prototype._write=function(Q,H,L){if(this._writev)this._writev([{chunk:Q,encoding:H}],L);else throw new I("_write()")},Y.prototype._writev=null,Y.prototype.end=function(Q,H,L,d=!1){const f=this._writableState;if(typeof Q==="function")L=Q,Q=null,H=null;else if(typeof H==="function")L=H,H=null;let r;if(Q!==null&&Q!==void 0){let q;if(!d)q=J(this,Q,H);else q=this.write(Q,H);if(q instanceof G)r=q}if(f.corked)f.corked=1,this.uncork();if(r)this.emit("error",r);else if(!f.errored&&!f.ending)f.ending=!0,qq(this,f,!0),f.ended=!0;else if(f.finished)r=new _("end");else if(f.destroyed)r=new T("end");if(typeof L==="function")if(r||f.finished)Xq(L,r);else f[F].push(L);return this};function e(Q,H){var L=Q.ending&&!Q.destroyed&&Q.constructed&&Q.length===0&&!Q.errored&&Q.buffered.length===0&&!Q.finished&&!Q.writing&&!Q.errorEmitted&&!Q.closeEmitted;return Gq("needFinish",L,H),L}function Hq(Q,H){let L=!1;function d(f){if(L){n(Q,f!==null&&f!==void 0?f:Z());return}if(L=!0,H.pendingcb--,f){const r=H[F].splice(0);for(let q=0;q<r.length;q++)r[q](f);n(Q,f,H.sync)}else if(e(H))H.prefinished=!0,Q.emit("prefinish"),H.pendingcb++,Xq(Kq,Q,H)}H.sync=!0,H.pendingcb++;try{Q._final(d)}catch(f){d(f)}H.sync=!1}function $q(Q,H){if(!H.prefinished&&!H.finalCalled)if(typeof Q._final==="function"&&!H.destroyed)H.finalCalled=!0,Hq(Q,H);else H.prefinished=!0,Q.emit("prefinish")}function qq(Q,H,L){if(!e(H,Q.__id))return;if($q(Q,H),H.pendingcb===0){if(L)H.pendingcb++,Xq((d,f)=>{if(e(f))Kq(d,f);else f.pendingcb--},Q,H);else if(e(H))H.pendingcb++,Kq(Q,H)}}function Kq(Q,H){H.pendingcb--,H.finished=!0;const L=H[F].splice(0);for(let d=0;d<L.length;d++)L[d]();if(Q.emit("finish"),H.autoDestroy){const d=Q._readableState;if(!d||d.autoDestroy&&(d.endEmitted||d.readable===!1))Q.destroy()}}M(Y.prototype,{closed:{get(){return this._writableState?this._writableState.closed:!1}},destroyed:{get(){return this._writableState?this._writableState.destroyed:!1},set(Q){if(this._writableState)this._writableState.destroyed=Q}},writable:{get(){const Q=this._writableState;return!!Q&&Q.writable!==!1&&!Q.destroyed&&!Q.errored&&!Q.ending&&!Q.ended},set(Q){if(this._writableState)this._writableState.writable=!!Q}},writableFinished:{get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{get(){const Q=this._writableState;if(!Q)return!1;return!Q.destroyed&&!Q.ending&&Q.needDrain}},writableHighWaterMark:{get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{get(){return this._writableState?this._writableState.corked:0}},writableLength:{get(){return this._writableState&&this._writableState.length}},errored:{enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var Qq=O.destroy;Y.prototype.destroy=function(Q,H){const L=this._writableState;if(!L.destroyed&&(L.bufferedIndex<L.buffered.length||L[F].length))Xq(o,L);return Qq.call(this,Q,H),this},Y.prototype._undestroy=O.undestroy,Y.prototype._destroy=function(Q,H){H(Q)},Y.prototype[Iq.captureRejectionSymbol]=function(Q){this.destroy(Q)};var V;function h(){if(V===void 0)V={};return V}Y.fromWeb=function(Q,H){return h().newStreamWritableFromWritableStream(Q,H)},Y.toWeb=function(Q){return h().newWritableStreamFromStreamWritable(Q)}}}),HQ=Bq({"node_modules/readable-stream/lib/internal/streams/duplexify.js"(a,j){var{isReadable:B,isWritable:G,isIterable:y,isNodeStream:A,isReadableNodeStream:M,isWritableNodeStream:R,isDuplexNodeStream:P}=Eq(),g=Fq(),{AbortError:k,codes:{ERR_INVALID_ARG_TYPE:c,ERR_INVALID_RETURN_VALUE:O}}=Wq(),{destroyer:l}=Tq(),D=Mq(),p=_q(),{createDeferredPromise:E}=Aq(),I=hq(),Z=typeof Blob!=="undefined"?function i($){return $ instanceof Blob}:function i($){return!1},{FunctionPrototypeCall:U}=Vq();class T extends D{constructor(i){super(i);if((i===null||i===void 0?void 0:i.readable)===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if((i===null||i===void 0?void 0:i.writable)===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}}j.exports=function i($,n){if(P($))return $;if(M($))return t({readable:$});if(R($))return t({writable:$});if(A($))return t({writable:!1,readable:!1});if(typeof $==="function"){const{value:K,write:F,final:m,destroy:u}=_($);if(y(K))return I(T,K,{objectMode:!0,write:F,final:m,destroy:u});const J=K===null||K===void 0?void 0:K.then;if(typeof J==="function"){let z;const w=U(J,K,(S)=>{if(S!=null)throw new O("nully","body",S)},(S)=>{l(z,S)});return z=new T({objectMode:!0,readable:!1,write:F,final(S){m(async()=>{try{await w,Xq(S,null)}catch(N){Xq(S,N)}})},destroy:u})}throw new O("Iterable, AsyncIterable or AsyncFunction",n,K)}if(Z($))return i($.arrayBuffer());if(y($))return I(T,$,{objectMode:!0,writable:!1});if(typeof($===null||$===void 0?void 0:$.writable)==="object"||typeof($===null||$===void 0?void 0:$.readable)==="object"){const K=$!==null&&$!==void 0&&$.readable?M($===null||$===void 0?void 0:$.readable)?$===null||$===void 0?void 0:$.readable:i($.readable):void 0,F=$!==null&&$!==void 0&&$.writable?R($===null||$===void 0?void 0:$.writable)?$===null||$===void 0?void 0:$.writable:i($.writable):void 0;return t({readable:K,writable:F})}const Y=$===null||$===void 0?void 0:$.then;if(typeof Y==="function"){let K;return U(Y,$,(F)=>{if(F!=null)K.push(F);K.push(null)},(F)=>{l(K,F)}),K=new T({objectMode:!0,writable:!1,read(){}})}throw new c(n,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],$)};function _(i){let{promise:$,resolve:n}=E();const Y=new AbortController,K=Y.signal;return{value:i(async function*(){while(!0){const m=$;$=null;const{chunk:u,done:J,cb:z}=await m;if(Xq(z),J)return;if(K.aborted)throw new k(void 0,{cause:K.reason});({promise:$,resolve:n}=E()),yield u}}(),{signal:K}),write(m,u,J){const z=n;n=null,z({chunk:m,done:!1,cb:J})},final(m){const u=n;n=null,u({done:!0,cb:m})},destroy(m,u){Y.abort(),u(m)}}}function t(i){const $=i.readable&&typeof i.readable.read!=="function"?p.wrap(i.readable):i.readable,n=i.writable;let Y=!!B($),K=!!G(n),F,m,u,J,z;function w(S){const N=J;if(J=null,N)N(S);else if(S)z.destroy(S);else if(!Y&&!K)z.destroy()}if(z=new T({readableObjectMode:!!($!==null&&$!==void 0&&$.readableObjectMode),writableObjectMode:!!(n!==null&&n!==void 0&&n.writableObjectMode),readable:Y,writable:K}),K)g(n,(S)=>{if(K=!1,S)l($,S);w(S)}),z._write=function(S,N,W){if(n.write(S,N))W();else F=W},z._final=function(S){n.end(),m=S},n.on("drain",function(){if(F){const S=F;F=null,S()}}),n.on("finish",function(){if(m){const S=m;m=null,S()}});if(Y)g($,(S)=>{if(Y=!1,S)l($,S);w(S)}),$.on("readable",function(){if(u){const S=u;u=null,S()}}),$.on("end",function(){z.push(null)}),z._read=function(){while(!0){const S=$.read();if(S===null){u=z._read;return}if(!z.push(S))return}};return z._destroy=function(S,N){if(!S&&J!==null)S=new k;if(u=null,F=null,m=null,J===null)N(S);else J=N,l(n,S),l($,S)},z}}}),Mq=Bq({"node_modules/readable-stream/lib/internal/streams/duplex.js"(a,j){var{ObjectDefineProperties:B,ObjectGetOwnPropertyDescriptor:G,ObjectKeys:y,ObjectSetPrototypeOf:A}=Vq(),M=_q();function R(O){if(!(this instanceof R))return new R(O);if(M.call(this,O),Uq.call(this,O),O){if(this.allowHalfOpen=O.allowHalfOpen!==!1,O.readable===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if(O.writable===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}else this.allowHalfOpen=!0}j.exports=R,A(R.prototype,M.prototype),A(R,M);for(var P in Uq.prototype)if(!R.prototype[P])R.prototype[P]=Uq.prototype[P];B(R.prototype,{writable:G(Uq.prototype,"writable"),writableHighWaterMark:G(Uq.prototype,"writableHighWaterMark"),writableObjectMode:G(Uq.prototype,"writableObjectMode"),writableBuffer:G(Uq.prototype,"writableBuffer"),writableLength:G(Uq.prototype,"writableLength"),writableFinished:G(Uq.prototype,"writableFinished"),writableCorked:G(Uq.prototype,"writableCorked"),writableEnded:G(Uq.prototype,"writableEnded"),writableNeedDrain:G(Uq.prototype,"writableNeedDrain"),destroyed:{get(){if(this._readableState===void 0||this._writableState===void 0)return!1;return this._readableState.destroyed&&this._writableState.destroyed},set(O){if(this._readableState&&this._writableState)this._readableState.destroyed=O,this._writableState.destroyed=O}}});var g;function k(){if(g===void 0)g={};return g}R.fromWeb=function(O,l){return k().newStreamDuplexFromReadableWritablePair(O,l)},R.toWeb=function(O){return k().newReadableWritablePairFromDuplex(O)};var c;R.from=function(O){if(!c)c=HQ();return c(O,"body")}}}),mq=Bq({"node_modules/readable-stream/lib/internal/streams/transform.js"(a,j){var{ObjectSetPrototypeOf:B,Symbol:G}=Vq(),{ERR_METHOD_NOT_IMPLEMENTED:y}=Wq().codes,A=Mq();function M(k){if(!(this instanceof M))return new M(k);if(A.call(this,k),this._readableState.sync=!1,this[R]=null,k){if(typeof k.transform==="function")this._transform=k.transform;if(typeof k.flush==="function")this._flush=k.flush}this.on("prefinish",g.bind(this))}B(M.prototype,A.prototype),B(M,A),j.exports=M;var R=G("kCallback");function P(k){if(typeof this._flush==="function"&&!this.destroyed)this._flush((c,O)=>{if(c){if(k)k(c);else this.destroy(c);return}if(O!=null)this.push(O);if(this.push(null),k)k()});else if(this.push(null),k)k()}function g(){if(this._final!==P)P.call(this)}M.prototype._final=P,M.prototype._transform=function(k,c,O){throw new y("_transform()")},M.prototype._write=function(k,c,O){const l=this._readableState,D=this._writableState,p=l.length;this._transform(k,c,(E,I)=>{if(E){O(E);return}if(I!=null)this.push(I);if(D.ended||p===l.length||l.length<l.highWaterMark||l.highWaterMark===0||l.length===0)O();else this[R]=O})},M.prototype._read=function(){if(this[R]){const k=this[R];this[R]=null,k()}}}}),cq=Bq({"node_modules/readable-stream/lib/internal/streams/passthrough.js"(a,j){var{ObjectSetPrototypeOf:B}=Vq(),G=mq();function y(A){if(!(this instanceof y))return new y(A);G.call(this,A)}B(y.prototype,G.prototype),B(y,G),y.prototype._transform=function(A,M,R){R(null,A)},j.exports=y}}),gq=Bq({"node_modules/readable-stream/lib/internal/streams/pipeline.js"(a,j){var{ArrayIsArray:B,Promise:G,SymbolAsyncIterator:y}=Vq(),A=Fq(),{once:M}=Aq(),R=Tq(),P=Mq(),{aggregateTwoErrors:g,codes:{ERR_INVALID_ARG_TYPE:k,ERR_INVALID_RETURN_VALUE:c,ERR_MISSING_ARGS:O,ERR_STREAM_DESTROYED:l},AbortError:D}=Wq(),{validateFunction:p,validateAbortSignal:E}=Cq(),{isIterable:I,isReadable:Z,isReadableNodeStream:U,isNodeStream:T}=Eq(),_,t;function i(J,z,w){let S=!1;J.on("close",()=>{S=!0});const N=A(J,{readable:z,writable:w},(W)=>{S=!W});return{destroy:(W)=>{if(S)return;S=!0,R.destroyer(J,W||new l("pipe"))},cleanup:N}}function $(J){return p(J[J.length-1],"streams[stream.length - 1]"),J.pop()}function n(J){if(I(J))return J;else if(U(J))return Y(J);throw new k("val",["Readable","Iterable","AsyncIterable"],J)}async function*Y(J){if(!t)t=_q();yield*t.prototype[y].call(J)}async function K(J,z,w,{end:S}){let N,W=null;const b=(e)=>{if(e)N=e;if(W){const Hq=W;W=null,Hq()}},o=()=>new G((e,Hq)=>{if(N)Hq(N);else W=()=>{if(N)Hq(N);else e()}});z.on("drain",b);const s=A(z,{readable:!1},b);try{if(z.writableNeedDrain)await o();for await(let e of J)if(!z.write(e))await o();if(S)z.end();await o(),w()}catch(e){w(N!==e?g(N,e):e)}finally{s(),z.off("drain",b)}}function F(...J){return m(J,M($(J)))}function m(J,z,w){if(J.length===1&&B(J[0]))J=J[0];if(J.length<2)throw new O("streams");const S=new AbortController,N=S.signal,W=w===null||w===void 0?void 0:w.signal,b=[];E(W,"options.signal");function o(){Kq(new D)}W===null||W===void 0||W.addEventListener("abort",o);let s,e;const Hq=[];let $q=0;function qq(h){Kq(h,--$q===0)}function Kq(h,Q){if(h&&(!s||s.code==="ERR_STREAM_PREMATURE_CLOSE"))s=h;if(!s&&!Q)return;while(Hq.length)Hq.shift()(s);if(W===null||W===void 0||W.removeEventListener("abort",o),S.abort(),Q){if(!s)b.forEach((H)=>H());Xq(z,s,e)}}let Qq;for(let h=0;h<J.length;h++){const Q=J[h],H=h<J.length-1,L=h>0,d=H||(w===null||w===void 0?void 0:w.end)!==!1,f=h===J.length-1;if(T(Q)){let r=function(q){if(q&&q.name!=="AbortError"&&q.code!=="ERR_STREAM_PREMATURE_CLOSE")qq(q)};if(d){const{destroy:q,cleanup:X}=i(Q,H,L);if(Hq.push(q),Z(Q)&&f)b.push(X)}if(Q.on("error",r),Z(Q)&&f)b.push(()=>{Q.removeListener("error",r)})}if(h===0)if(typeof Q==="function"){if(Qq=Q({signal:N}),!I(Qq))throw new c("Iterable, AsyncIterable or Stream","source",Qq)}else if(I(Q)||U(Q))Qq=Q;else Qq=P.from(Q);else if(typeof Q==="function")if(Qq=n(Qq),Qq=Q(Qq,{signal:N}),H){if(!I(Qq,!0))throw new c("AsyncIterable",`transform[${h-1}]`,Qq)}else{var V;if(!_)_=cq();const r=new _({objectMode:!0}),q=(V=Qq)===null||V===void 0?void 0:V.then;if(typeof q==="function")$q++,q.call(Qq,(x)=>{if(e=x,x!=null)r.write(x);if(d)r.end();Xq(qq)},(x)=>{r.destroy(x),Xq(qq,x)});else if(I(Qq,!0))$q++,K(Qq,r,qq,{end:d});else throw new c("AsyncIterable or Promise","destination",Qq);Qq=r;const{destroy:X,cleanup:C}=i(Qq,!1,!0);if(Hq.push(X),f)b.push(C)}else if(T(Q)){if(U(Qq)){$q+=2;const r=u(Qq,Q,qq,{end:d});if(Z(Q)&&f)b.push(r)}else if(I(Qq))$q++,K(Qq,Q,qq,{end:d});else throw new k("val",["Readable","Iterable","AsyncIterable"],Qq);Qq=Q}else Qq=P.from(Q)}if(N!==null&&N!==void 0&&N.aborted||W!==null&&W!==void 0&&W.aborted)Xq(o);return Qq}function u(J,z,w,{end:S}){if(J.pipe(z,{end:S}),S)J.once("end",()=>z.end());else w();return A(J,{readable:!0,writable:!1},(N)=>{const W=J._readableState;if(N&&N.code==="ERR_STREAM_PREMATURE_CLOSE"&&W&&W.ended&&!W.errored&&!W.errorEmitted)J.once("end",w).once("error",w);else w(N)}),A(z,{readable:!1,writable:!0},w)}j.exports={pipelineImpl:m,pipeline:F}}}),KQ=Bq({"node_modules/readable-stream/lib/internal/streams/compose.js"(a,j){var{pipeline:B}=gq(),G=Mq(),{destroyer:y}=Tq(),{isNodeStream:A,isReadable:M,isWritable:R}=Eq(),{AbortError:P,codes:{ERR_INVALID_ARG_VALUE:g,ERR_MISSING_ARGS:k}}=Wq();j.exports=function c(...O){if(O.length===0)throw new k("streams");if(O.length===1)return G.from(O[0]);const l=[...O];if(typeof O[0]==="function")O[0]=G.from(O[0]);if(typeof O[O.length-1]==="function"){const $=O.length-1;O[$]=G.from(O[$])}for(let $=0;$<O.length;++$){if(!A(O[$]))continue;if($<O.length-1&&!M(O[$]))throw new g(`streams[${$}]`,l[$],"must be readable");if($>0&&!R(O[$]))throw new g(`streams[${$}]`,l[$],"must be writable")}let D,p,E,I,Z;function U($){const n=I;if(I=null,n)n($);else if($)Z.destroy($);else if(!i&&!t)Z.destroy()}const T=O[0],_=B(O,U),t=!!R(T),i=!!M(_);if(Z=new G({writableObjectMode:!!(T!==null&&T!==void 0&&T.writableObjectMode),readableObjectMode:!!(_!==null&&_!==void 0&&_.writableObjectMode),writable:t,readable:i}),t)Z._write=function($,n,Y){if(T.write($,n))Y();else D=Y},Z._final=function($){T.end(),p=$},T.on("drain",function(){if(D){const $=D;D=null,$()}}),_.on("finish",function(){if(p){const $=p;p=null,$()}});if(i)_.on("readable",function(){if(E){const $=E;E=null,$()}}),_.on("end",function(){Z.push(null)}),Z._read=function(){while(!0){const $=_.read();if($===null){E=Z._read;return}if(!Z.push($))return}};return Z._destroy=function($,n){if(!$&&I!==null)$=new P;if(E=null,D=null,p=null,I===null)n($);else I=n,y(_,$)},Z}}}),dq=Bq({"node_modules/readable-stream/lib/stream/promises.js"(a,j){var{ArrayPrototypePop:B,Promise:G}=Vq(),{isIterable:y,isNodeStream:A}=Eq(),{pipelineImpl:M}=gq(),{finished:R}=Fq();function P(...g){return new G((k,c)=>{let O,l;const D=g[g.length-1];if(D&&typeof D==="object"&&!A(D)&&!y(D)){const p=B(g);O=p.signal,l=p.end}M(g,(p,E)=>{if(p)c(p);else k(E)},{signal:O,end:l})})}j.exports={finished:R,pipeline:P}}}),ZQ=Bq({"node_modules/readable-stream/lib/stream.js"(a,j){var{ObjectDefineProperty:B,ObjectKeys:G,ReflectApply:y}=Vq(),{promisify:{custom:A}}=Aq(),{streamReturningOperators:M,promiseReturningOperators:R}=XQ(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:P}}=Wq(),g=KQ(),{pipeline:k}=gq(),{destroyer:c}=Tq(),O=Fq(),l=dq(),D=Eq(),p=j.exports=Rq().Stream;p.isDisturbed=D.isDisturbed,p.isErrored=D.isErrored,p.isWritable=D.isWritable,p.isReadable=D.isReadable,p.Readable=_q();for(let I of G(M)){let Z=function(...T){if(new.target)throw P();return p.Readable.from(y(U,this,T))};const U=M[I];B(Z,"name",{value:U.name}),B(Z,"length",{value:U.length}),B(p.Readable.prototype,I,{value:Z,enumerable:!1,configurable:!0,writable:!0})}for(let I of G(R)){let Z=function(...T){if(new.target)throw P();return y(U,this,T)};const U=R[I];B(Z,"name",{value:U.name}),B(Z,"length",{value:U.length}),B(p.Readable.prototype,I,{value:Z,enumerable:!1,configurable:!0,writable:!0})}p.Writable=bq(),p.Duplex=Mq(),p.Transform=mq(),p.PassThrough=cq(),p.pipeline=k;var{addAbortSignal:E}=Sq();p.addAbortSignal=E,p.finished=O,p.destroy=c,p.compose=g,B(p,"promises",{configurable:!0,enumerable:!0,get(){return l}}),B(k,A,{enumerable:!0,get(){return l.pipeline}}),B(O,A,{enumerable:!0,get(){return l.finished}}),p.Stream=p,p._isUint8Array=function I(Z){return Z instanceof Uint8Array},p._uint8ArrayToBuffer=function I(Z){return new Buffer(Z.buffer,Z.byteOffset,Z.byteLength)}}}),BQ=Bq({"node_modules/readable-stream/lib/ours/index.js"(a,j){const B=ZQ(),G=dq(),y=B.Readable.destroy;j.exports=B,j.exports._uint8ArrayToBuffer=B._uint8ArrayToBuffer,j.exports._isUint8Array=B._isUint8Array,j.exports.isDisturbed=B.isDisturbed,j.exports.isErrored=B.isErrored,j.exports.isWritable=B.isWritable,j.exports.isReadable=B.isReadable,j.exports.Readable=B.Readable,j.exports.Writable=B.Writable,j.exports.Duplex=B.Duplex,j.exports.Transform=B.Transform,j.exports.PassThrough=B.PassThrough,j.exports.addAbortSignal=B.addAbortSignal,j.exports.finished=B.finished,j.exports.destroy=B.destroy,j.exports.destroy=y,j.exports.pipeline=B.pipeline,j.exports.compose=B.compose,j.exports._getNativeReadableStreamPrototype=lq,j.exports.NativeWritable=iq,zq.defineProperty(B,"promises",{configurable:!0,enumerable:!0,get(){return G}}),j.exports.Stream=B.Stream,j.exports.default=j.exports}}),$Q={0:void 0,1:void 0,2:void 0,3:void 0,4:void 0,5:void 0},Uq=bq(),iq=class a extends Uq{#q;#Q;#X=!0;_construct;_destroy;_final;constructor(j,B={}){super(B);this._construct=this.#H,this._destroy=this.#K,this._final=this.#Z,this.#q=j}#H(j){this._writableState.constructed=!0,this.constructed=!0,j()}#J(){if(typeof this.#q==="object")if(typeof this.#q.write==="function")this.#Q=this.#q;else throw new Error("Invalid FileSink");else this.#Q=Bun.file(this.#q).writer()}write(j,B,G,y=this.#X){if(!y)return this.#X=!1,super.write(j,B,G);if(!this.#Q)this.#J();var A=this.#Q,M=A.write(j);if(xq(M))return M.then(()=>{this.emit("drain"),A.flush(!0)}),!1;if(A.flush(!0),G)G(null,j.byteLength);return!0}end(j,B,G,y=this.#X){return super.end(j,B,G,y)}#K(j,B){if(this._writableState.destroyed=!0,B)B(j)}#Z(j){if(this.#Q)this.#Q.end();if(j)j()}ref(){if(!this.#Q)this.#J();this.#Q.ref()}unref(){if(!this.#Q)return;this.#Q.unref()}},Yq=BQ();Yq[Symbol.for("CommonJS")]=0;Yq[Symbol.for("::bunternal::")]={_ReadableFromWeb:pq,_ReadableFromWebForUndici:uq};var cQ=Yq,EQ=Yq._uint8ArrayToBuffer,IQ=Yq._isUint8Array,TQ=Yq.isDisturbed,PQ=Yq.isErrored,xQ=Yq.isWritable,OQ=Yq.isReadable,CQ=Yq.Readable,Uq=Yq.Writable,_Q=Yq.Duplex,DQ=Yq.Transform,wQ=Yq.PassThrough,vQ=Yq.addAbortSignal,RQ=Yq.finished,SQ=Yq.destroy,gQ=Yq.pipeline,kQ=Yq.compose,VQ=Yq.Stream,fQ=Yq.eos=Fq,yQ=Yq._getNativeReadableStreamPrototype,iq=Yq.NativeWritable,hQ=VQ.promises;export{hQ as promises,gQ as pipeline,xQ as isWritable,OQ as isReadable,PQ as isErrored,TQ as isDisturbed,RQ as finished,fQ as eos,SQ as destroy,cQ as default,kQ as compose,vQ as addAbortSignal,EQ as _uint8ArrayToBuffer,IQ as _isUint8Array,yQ as _getNativeReadableStreamPrototype,Uq as Writable,DQ as Transform,VQ as Stream,CQ as Readable,wQ as PassThrough,iq as NativeWritable,_Q as Duplex}; diff --git a/src/string.zig b/src/string.zig index 166a0a6f7..5f107197f 100644 --- a/src/string.zig +++ b/src/string.zig @@ -257,6 +257,8 @@ pub const String = extern struct { extern fn BunString__fromLatin1(bytes: [*]const u8, len: usize) String; extern fn BunString__fromBytes(bytes: [*]const u8, len: usize) String; + extern fn BunString__fromLatin1Unitialized(len: usize) String; + extern fn BunString__fromUTF16Unitialized(len: usize) String; pub fn toOwnedSlice(this: String, allocator: std.mem.Allocator) ![]u8 { switch (this.tag) { @@ -278,6 +280,30 @@ pub const String = extern struct { } } + pub fn createUninitializedLatin1(len: usize) String { + JSC.markBinding(@src()); + return BunString__fromLatin1Unitialized(len); + } + + pub fn createUninitializedUTF16(len: usize) String { + JSC.markBinding(@src()); + return BunString__fromUTF16Unitialized(len); + } + + pub fn createUninitialized(comptime kind: @Type(.EnumLiteral), len: usize) ?String { + const without_check = switch (comptime kind) { + .latin1 => createUninitializedLatin1(len), + .utf16 => createUninitializedUTF16(len), + else => @compileError("Invalid string kind"), + }; + + if (without_check.tag == .Dead) { + return null; + } + + return without_check; + } + pub fn createLatin1(bytes: []const u8) String { JSC.markBinding(@src()); return BunString__fromLatin1(bytes.ptr, bytes.len); diff --git a/test/js/node/crypto/node-crypto.test.js b/test/js/node/crypto/node-crypto.test.js index 5a68540cf..2489f96c7 100644 --- a/test/js/node/crypto/node-crypto.test.js +++ b/test/js/node/crypto/node-crypto.test.js @@ -43,6 +43,50 @@ describe("createHash", () => { expect(Buffer.isBuffer(hash.digest())).toBeTrue(); }); + const otherEncodings = { + ucs2: [ + 11626, 2466, 37699, 38942, 64564, 53010, 48101, 47943, 44761, 18499, 12442, 26994, 46434, 62582, 39395, 20542, + ], + latin1: [ + 106, 45, 162, 9, 67, 147, 30, 152, 52, 252, 18, 207, 229, 187, 71, 187, 217, 174, 67, 72, 154, 48, 114, 105, 98, + 181, 118, 244, 227, 153, 62, 80, + ], + binary: [ + 106, 45, 162, 9, 67, 147, 30, 152, 52, 252, 18, 207, 229, 187, 71, 187, 217, 174, 67, 72, 154, 48, 114, 105, 98, + 181, 118, 244, 227, 153, 62, 80, + ], + base64: [ + 97, 105, 50, 105, 67, 85, 79, 84, 72, 112, 103, 48, 47, 66, 76, 80, 53, 98, 116, 72, 117, 57, 109, 117, 81, 48, + 105, 97, 77, 72, 74, 112, 89, 114, 86, 50, 57, 79, 79, 90, 80, 108, 65, 61, + ], + hex: [ + 54, 97, 50, 100, 97, 50, 48, 57, 52, 51, 57, 51, 49, 101, 57, 56, 51, 52, 102, 99, 49, 50, 99, 102, 101, 53, 98, + 98, 52, 55, 98, 98, 100, 57, 97, 101, 52, 51, 52, 56, 57, 97, 51, 48, 55, 50, 54, 57, 54, 50, 98, 53, 55, 54, 102, + 52, 101, 51, 57, 57, 51, 101, 53, 48, + ], + ascii: [ + 106, 45, 34, 9, 67, 19, 30, 24, 52, 124, 18, 79, 101, 59, 71, 59, 89, 46, 67, 72, 26, 48, 114, 105, 98, 53, 118, + 116, 99, 25, 62, 80, + ], + utf8: [ + 106, 45, 65533, 9, 67, 65533, 30, 65533, 52, 65533, 18, 65533, 65533, 71, 65533, 1646, 67, 72, 65533, 48, 114, + 105, 98, 65533, 118, 65533, 65533, 62, 80, + ], + }; + + for (let encoding in otherEncodings) { + it("digest " + encoding, () => { + const hash = crypto.createHash("sha256"); + hash.update("some data to hash"); + expect( + hash + .digest(encoding) + .split("") + .map(a => a.charCodeAt(0)), + ).toEqual(otherEncodings[encoding]); + }); + } + it("stream (sync)", () => { const hash = crypto.createHash("sha256"); hash.write("some data to hash"); diff --git a/test/js/node/process/process.test.js b/test/js/node/process/process.test.js index c4701f664..e038383de 100644 --- a/test/js/node/process/process.test.js +++ b/test/js/node/process/process.test.js @@ -162,7 +162,8 @@ it("process.umask()", () => { expect(process.umask()).toBe(orig); }); -const versions = existsSync(import.meta.dir + "/../../src/generated_versions_list.zig"); +const generated_versions_list = join(import.meta.dir, "../../../../src/generated_versions_list.zig"); +const versions = existsSync(generated_versions_list); (versions ? it : it.skip)("process.versions", () => { // Generate a list of all the versions in the versions object // example: @@ -178,7 +179,7 @@ const versions = existsSync(import.meta.dir + "/../../src/generated_versions_lis // pub const c_ares = "0e7a5dee0fbb04080750cf6eabbe89d8bae87faa"; // pub const usockets = "fafc241e8664243fc0c51d69684d5d02b9805134"; const versions = Object.fromEntries( - readFileSync(import.meta.dir + "/../../src/generated_versions_list.zig", "utf8") + readFileSync(generated_versions_list, "utf8") .split("\n") .filter(line => line.startsWith("pub const") && !line.includes("zig") && line.includes(' = "')) .map(line => line.split(" = ")) @@ -291,3 +292,140 @@ describe("process.onBeforeExit", () => { expect(stdout.toString().trim()).toBe("beforeExit: 0\nbeforeExit: 1\nexit: 2"); }); }); + +it("process.memoryUsage", () => { + expect(process.memoryUsage()).toEqual({ + rss: expect.any(Number), + heapTotal: expect.any(Number), + heapUsed: expect.any(Number), + external: expect.any(Number), + arrayBuffers: expect.any(Number), + }); +}); + +it("process.memoryUsage.rss", () => { + expect(process.memoryUsage.rss()).toEqual(expect.any(Number)); +}); + +describe("process.cpuUsage", () => { + it("works", () => { + expect(process.cpuUsage()).toEqual({ + user: expect.any(Number), + system: expect.any(Number), + }); + }); + + it("works with diff", () => { + const init = process.cpuUsage(); + for (let i = 0; i < 1000; i++) {} + const delta = process.cpuUsage(init); + expect(delta.user).toBeGreaterThan(0); + expect(delta.system).toBeGreaterThan(0); + }); + + it("works with diff of different structure", () => { + const init = { + user: 0, + system: 0, + }; + for (let i = 0; i < 1000; i++) {} + const delta = process.cpuUsage(init); + expect(delta.user).toBeGreaterThan(0); + expect(delta.system).toBeGreaterThan(0); + }); + + it("throws on invalid property", () => { + const fixtures = [ + {}, + { user: null }, + { user: {} }, + { user: "potato" }, + + { user: 123 }, + { user: 123, system: null }, + { user: 123, system: "potato" }, + ]; + for (const fixture of fixtures) { + expect(() => process.cpuUsage(fixture)).toThrow(); + } + }); + + // Skipped on Linux because it seems to not change as often as on macOS + it.skipIf(process.platform === "linux")("increases monotonically", () => { + const init = process.cpuUsage(); + for (let i = 0; i < 10000; i++) {} + const another = process.cpuUsage(); + expect(another.user).toBeGreaterThan(init.user); + expect(another.system).toBeGreaterThan(init.system); + }); +}); + +it("process.getegid", () => { + expect(typeof process.getegid()).toBe("number"); +}); +it("process.geteuid", () => { + expect(typeof process.geteuid()).toBe("number"); +}); +it("process.getgid", () => { + expect(typeof process.getgid()).toBe("number"); +}); +it("process.getgroups", () => { + expect(process.getgroups()).toBeInstanceOf(Array); + expect(process.getgroups().length).toBeGreaterThan(0); +}); +it("process.getuid", () => { + expect(typeof process.getuid()).toBe("number"); +}); + +it("process.getuid", () => { + expect(typeof process.getuid()).toBe("number"); +}); + +const undefinedStubs = [ + "_debugEnd", + "_debugProcess", + "_fatalException", + "_linkedBinding", + "_rawDebug", + "_startProfilerIdleNotifier", + "_stopProfilerIdleNotifier", + "_tickCallback", +]; + +for (const stub of undefinedStubs) { + it(`process.${stub}`, () => { + expect(process[stub]()).toBeUndefined(); + }); +} + +const arrayStubs = ["getActiveResourcesInfo", "_getActiveRequests", "_getActiveHandles"]; + +for (const stub of arrayStubs) { + it(`process.${stub}`, () => { + expect(process[stub]()).toBeInstanceOf(Array); + }); +} + +const emptyObjectStubs = ["_preload_modules"]; +const emptySetStubs = ["allowedNodeEnvironmentFlags"]; +const emptyArrayStubs = ["moduleLoadList"]; + +for (const stub of emptyObjectStubs) { + it(`process.${stub}`, () => { + expect(process[stub]).toEqual({}); + }); +} + +for (const stub of emptySetStubs) { + it(`process.${stub}`, () => { + expect(process[stub]).toBeInstanceOf(Set); + expect(process[stub].size).toBe(0); + }); +} + +for (const stub of emptyArrayStubs) { + it(`process.${stub}`, () => { + expect(process[stub]).toBeInstanceOf(Array); + expect(process[stub]).toHaveLength(0); + }); +} diff --git a/test/js/web/web-globals.test.js b/test/js/web/web-globals.test.js index b7a243190..d687a1290 100644 --- a/test/js/web/web-globals.test.js +++ b/test/js/web/web-globals.test.js @@ -138,6 +138,25 @@ it("crypto.randomUUID", () => { }); }); +it("crypto.randomUUID version, issues#3575", () => { + var uuid = crypto.randomUUID(); + + function validate(uuid) { + const regex = + /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; + return typeof uuid === "string" && regex.test(uuid); + } + function version(uuid) { + if (!validate(uuid)) { + throw TypeError("Invalid UUID"); + } + + return parseInt(uuid.slice(14, 15), 16); + } + + expect(version(uuid)).toBe(4); +}); + it("URL.prototype.origin", () => { const url = new URL("https://html.spec.whatwg.org/"); const { origin, host, hostname } = url; |